babylon.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. var KeyboardEventTypes = /** @class */ (function () {
  1269. function KeyboardEventTypes() {
  1270. }
  1271. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1272. get: function () {
  1273. return KeyboardEventTypes._KEYDOWN;
  1274. },
  1275. enumerable: true,
  1276. configurable: true
  1277. });
  1278. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1279. get: function () {
  1280. return KeyboardEventTypes._KEYUP;
  1281. },
  1282. enumerable: true,
  1283. configurable: true
  1284. });
  1285. KeyboardEventTypes._KEYDOWN = 0x01;
  1286. KeyboardEventTypes._KEYUP = 0x02;
  1287. return KeyboardEventTypes;
  1288. }());
  1289. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. function KeyboardInfo(type, event) {
  1292. this.type = type;
  1293. this.event = event;
  1294. }
  1295. return KeyboardInfo;
  1296. }());
  1297. BABYLON.KeyboardInfo = KeyboardInfo;
  1298. /**
  1299. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1300. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1301. */
  1302. var KeyboardInfoPre = /** @class */ (function (_super) {
  1303. __extends(KeyboardInfoPre, _super);
  1304. function KeyboardInfoPre(type, event) {
  1305. var _this = _super.call(this, type, event) || this;
  1306. _this.skipOnPointerObservable = false;
  1307. return _this;
  1308. }
  1309. return KeyboardInfoPre;
  1310. }(KeyboardInfo));
  1311. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1312. })(BABYLON || (BABYLON = {}));
  1313. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1314. var BABYLON;
  1315. (function (BABYLON) {
  1316. var PointerEventTypes = /** @class */ (function () {
  1317. function PointerEventTypes() {
  1318. }
  1319. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1320. get: function () {
  1321. return PointerEventTypes._POINTERDOWN;
  1322. },
  1323. enumerable: true,
  1324. configurable: true
  1325. });
  1326. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1327. get: function () {
  1328. return PointerEventTypes._POINTERUP;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERMOVE;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERWHEEL;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERPICK;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERTAP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERDOUBLETAP;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. PointerEventTypes._POINTERDOWN = 0x01;
  1369. PointerEventTypes._POINTERUP = 0x02;
  1370. PointerEventTypes._POINTERMOVE = 0x04;
  1371. PointerEventTypes._POINTERWHEEL = 0x08;
  1372. PointerEventTypes._POINTERPICK = 0x10;
  1373. PointerEventTypes._POINTERTAP = 0x20;
  1374. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1375. return PointerEventTypes;
  1376. }());
  1377. BABYLON.PointerEventTypes = PointerEventTypes;
  1378. var PointerInfoBase = /** @class */ (function () {
  1379. function PointerInfoBase(type, event) {
  1380. this.type = type;
  1381. this.event = event;
  1382. }
  1383. return PointerInfoBase;
  1384. }());
  1385. BABYLON.PointerInfoBase = PointerInfoBase;
  1386. /**
  1387. * This class is used to store pointer related info for the onPrePointerObservable event.
  1388. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1389. */
  1390. var PointerInfoPre = /** @class */ (function (_super) {
  1391. __extends(PointerInfoPre, _super);
  1392. function PointerInfoPre(type, event, localX, localY) {
  1393. var _this = _super.call(this, type, event) || this;
  1394. /**
  1395. * Ray from a pointer if availible (eg. 6dof controller)
  1396. */
  1397. _this.ray = null;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. BABYLON.ToGammaSpace = 1 / 2.2;
  1424. BABYLON.ToLinearSpace = 2.2;
  1425. BABYLON.Epsilon = 0.001;
  1426. /**
  1427. * Class used to hold a RBG color
  1428. */
  1429. var Color3 = /** @class */ (function () {
  1430. /**
  1431. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1432. * @param r defines the red component (between 0 and 1, default is 0)
  1433. * @param g defines the green component (between 0 and 1, default is 0)
  1434. * @param b defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. function Color3(
  1437. /**
  1438. * Defines the red component (between 0 and 1, default is 0)
  1439. */
  1440. r,
  1441. /**
  1442. * Defines the green component (between 0 and 1, default is 0)
  1443. */
  1444. g,
  1445. /**
  1446. * Defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. b) {
  1449. if (r === void 0) { r = 0; }
  1450. if (g === void 0) { g = 0; }
  1451. if (b === void 0) { b = 0; }
  1452. this.r = r;
  1453. this.g = g;
  1454. this.b = b;
  1455. }
  1456. /**
  1457. * Creates a string with the Color3 current values
  1458. * @returns the string representation of the Color3 object
  1459. */
  1460. Color3.prototype.toString = function () {
  1461. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1462. };
  1463. /**
  1464. * Returns the string "Color3"
  1465. * @returns "Color3"
  1466. */
  1467. Color3.prototype.getClassName = function () {
  1468. return "Color3";
  1469. };
  1470. /**
  1471. * Compute the Color3 hash code
  1472. * @returns an unique number that can be used to hash Color3 objects
  1473. */
  1474. Color3.prototype.getHashCode = function () {
  1475. var hash = this.r || 0;
  1476. hash = (hash * 397) ^ (this.g || 0);
  1477. hash = (hash * 397) ^ (this.b || 0);
  1478. return hash;
  1479. };
  1480. // Operators
  1481. /**
  1482. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1483. * @param array defines the array where to store the r,g,b components
  1484. * @param index defines an optional index in the target array to define where to start storing values
  1485. * @returns the current Color3 object
  1486. */
  1487. Color3.prototype.toArray = function (array, index) {
  1488. if (index === undefined) {
  1489. index = 0;
  1490. }
  1491. array[index] = this.r;
  1492. array[index + 1] = this.g;
  1493. array[index + 2] = this.b;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1498. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1499. * @returns a new {BABYLON.Color4} object
  1500. */
  1501. Color3.prototype.toColor4 = function (alpha) {
  1502. if (alpha === void 0) { alpha = 1; }
  1503. return new Color4(this.r, this.g, this.b, alpha);
  1504. };
  1505. /**
  1506. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1507. * @returns the new array
  1508. */
  1509. Color3.prototype.asArray = function () {
  1510. var result = new Array();
  1511. this.toArray(result, 0);
  1512. return result;
  1513. };
  1514. /**
  1515. * Returns the luminance value
  1516. * @returns a float value
  1517. */
  1518. Color3.prototype.toLuminance = function () {
  1519. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1520. };
  1521. /**
  1522. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1523. * @param otherColor defines the second operand
  1524. * @returns the new Color3 object
  1525. */
  1526. Color3.prototype.multiply = function (otherColor) {
  1527. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1528. };
  1529. /**
  1530. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1531. * @param otherColor defines the second operand
  1532. * @param result defines the Color3 object where to store the result
  1533. * @returns the current Color3
  1534. */
  1535. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1536. result.r = this.r * otherColor.r;
  1537. result.g = this.g * otherColor.g;
  1538. result.b = this.b * otherColor.b;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines equality between Color3 objects
  1543. * @param otherColor defines the second operand
  1544. * @returns true if the rgb values are equal to the given ones
  1545. */
  1546. Color3.prototype.equals = function (otherColor) {
  1547. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1548. };
  1549. /**
  1550. * Determines equality between the current Color3 object and a set of r,b,g values
  1551. * @param r defines the red component to check
  1552. * @param g defines the green component to check
  1553. * @param b defines the blue component to check
  1554. * @returns true if the rgb values are equal to the given ones
  1555. */
  1556. Color3.prototype.equalsFloats = function (r, g, b) {
  1557. return this.r === r && this.g === g && this.b === b;
  1558. };
  1559. /**
  1560. * Multiplies in place each rgb value by scale
  1561. * @param scale defines the scaling factor
  1562. * @returns the updated Color3
  1563. */
  1564. Color3.prototype.scale = function (scale) {
  1565. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1566. };
  1567. /**
  1568. * Multiplies the rgb values by scale and stores the result into "result"
  1569. * @param scale defines the scaling factor
  1570. * @param result defines the Color3 object where to store the result
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleToRef = function (scale, result) {
  1574. result.r = this.r * scale;
  1575. result.g = this.g * scale;
  1576. result.b = this.b * scale;
  1577. return this;
  1578. };
  1579. /**
  1580. * Scale the current Color3 values by a factor and add the result to a given Color3
  1581. * @param scale defines the scale factor
  1582. * @param result defines color to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1586. result.r += this.r * scale;
  1587. result.g += this.g * scale;
  1588. result.b += this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Clamps the rgb values by the min and max values and stores the result into "result"
  1593. * @param min defines minimum clamping value (default is 0)
  1594. * @param max defines maximum clamping value (default is 1)
  1595. * @param result defines color to store the result into
  1596. * @returns the original Color3
  1597. */
  1598. Color3.prototype.clampToRef = function (min, max, result) {
  1599. if (min === void 0) { min = 0; }
  1600. if (max === void 0) { max = 1; }
  1601. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1602. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1603. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1604. return this;
  1605. };
  1606. /**
  1607. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.add = function (otherColor) {
  1612. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.addToRef = function (otherColor, result) {
  1621. result.r = this.r + otherColor.r;
  1622. result.g = this.g + otherColor.g;
  1623. result.b = this.b + otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1628. * @param otherColor defines the second operand
  1629. * @returns the new Color3
  1630. */
  1631. Color3.prototype.subtract = function (otherColor) {
  1632. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1633. };
  1634. /**
  1635. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1636. * @param otherColor defines the second operand
  1637. * @param result defines Color3 object to store the result into
  1638. * @returns the unmodified current Color3
  1639. */
  1640. Color3.prototype.subtractToRef = function (otherColor, result) {
  1641. result.r = this.r - otherColor.r;
  1642. result.g = this.g - otherColor.g;
  1643. result.b = this.b - otherColor.b;
  1644. return this;
  1645. };
  1646. /**
  1647. * Copy the current object
  1648. * @returns a new Color3 copied the current one
  1649. */
  1650. Color3.prototype.clone = function () {
  1651. return new Color3(this.r, this.g, this.b);
  1652. };
  1653. /**
  1654. * Copies the rgb values from the source in the current Color3
  1655. * @param source defines the source Color3 object
  1656. * @returns the updated Color3 object
  1657. */
  1658. Color3.prototype.copyFrom = function (source) {
  1659. this.r = source.r;
  1660. this.g = source.g;
  1661. this.b = source.b;
  1662. return this;
  1663. };
  1664. /**
  1665. * Updates the Color3 rgb values from the given floats
  1666. * @param r defines the red component to read from
  1667. * @param g defines the green component to read from
  1668. * @param b defines the blue component to read from
  1669. * @returns the current Color3 object
  1670. */
  1671. Color3.prototype.copyFromFloats = function (r, g, b) {
  1672. this.r = r;
  1673. this.g = g;
  1674. this.b = b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Updates the Color3 rgb values from the given floats
  1679. * @param r defines the red component to read from
  1680. * @param g defines the green component to read from
  1681. * @param b defines the blue component to read from
  1682. * @returns the current Color3 object
  1683. */
  1684. Color3.prototype.set = function (r, g, b) {
  1685. return this.copyFromFloats(r, g, b);
  1686. };
  1687. /**
  1688. * Compute the Color3 hexadecimal code as a string
  1689. * @returns a string containing the hexadecimal representation of the Color3 object
  1690. */
  1691. Color3.prototype.toHexString = function () {
  1692. var intR = (this.r * 255) | 0;
  1693. var intG = (this.g * 255) | 0;
  1694. var intB = (this.b * 255) | 0;
  1695. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to linear space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toLinearSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toLinearSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the linear space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1715. return this;
  1716. };
  1717. /**
  1718. * Computes a new Color3 converted from the current one to gamma space
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.prototype.toGammaSpace = function () {
  1722. var convertedColor = new Color3();
  1723. this.toGammaSpaceToRef(convertedColor);
  1724. return convertedColor;
  1725. };
  1726. /**
  1727. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1728. * @param convertedColor defines the Color3 object where to store the gamma space version
  1729. * @returns the unmodified Color3
  1730. */
  1731. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1732. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1733. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1734. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1735. return this;
  1736. };
  1737. // Statics
  1738. /**
  1739. * Creates a new Color3 from the string containing valid hexadecimal values
  1740. * @param hex defines a string containing valid hexadecimal values
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromHexString = function (hex) {
  1744. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1745. return new Color3(0, 0, 0);
  1746. }
  1747. var r = parseInt(hex.substring(1, 3), 16);
  1748. var g = parseInt(hex.substring(3, 5), 16);
  1749. var b = parseInt(hex.substring(5, 7), 16);
  1750. return Color3.FromInts(r, g, b);
  1751. };
  1752. /**
  1753. * Creates a new Vector3 from the starting index of the given array
  1754. * @param array defines the source array
  1755. * @param offset defines an offset in the source array
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromArray = function (array, offset) {
  1759. if (offset === void 0) { offset = 0; }
  1760. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1761. };
  1762. /**
  1763. * Creates a new Color3 from integer values (< 256)
  1764. * @param r defines the red component to read from (value between 0 and 255)
  1765. * @param g defines the green component to read from (value between 0 and 255)
  1766. * @param b defines the blue component to read from (value between 0 and 255)
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.FromInts = function (r, g, b) {
  1770. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1771. };
  1772. /**
  1773. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1774. * @param start defines the start Color3 value
  1775. * @param end defines the end Color3 value
  1776. * @param amount defines the gradient value between start and end
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Lerp = function (start, end, amount) {
  1780. var r = start.r + ((end.r - start.r) * amount);
  1781. var g = start.g + ((end.g - start.g) * amount);
  1782. var b = start.b + ((end.b - start.b) * amount);
  1783. return new Color3(r, g, b);
  1784. };
  1785. /**
  1786. * Returns a Color3 value containing a red color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Red = function () { return new Color3(1, 0, 0); };
  1790. /**
  1791. * Returns a Color3 value containing a green color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Green = function () { return new Color3(0, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a blue color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1800. /**
  1801. * Returns a Color3 value containing a black color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Black = function () { return new Color3(0, 0, 0); };
  1805. /**
  1806. * Returns a Color3 value containing a white color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.White = function () { return new Color3(1, 1, 1); };
  1810. /**
  1811. * Returns a Color3 value containing a purple color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1815. /**
  1816. * Returns a Color3 value containing a magenta color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1820. /**
  1821. * Returns a Color3 value containing a yellow color
  1822. * @returns a new Color3 object
  1823. */
  1824. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1825. /**
  1826. * Returns a Color3 value containing a gray color
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1830. /**
  1831. * Returns a Color3 value containing a teal color
  1832. * @returns a new Color3 object
  1833. */
  1834. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1835. /**
  1836. * Returns a Color3 value containing a random color
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1840. return Color3;
  1841. }());
  1842. BABYLON.Color3 = Color3;
  1843. /**
  1844. * Class used to hold a RBGA color
  1845. */
  1846. var Color4 = /** @class */ (function () {
  1847. /**
  1848. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1849. * @param r defines the red component (between 0 and 1, default is 0)
  1850. * @param g defines the green component (between 0 and 1, default is 0)
  1851. * @param b defines the blue component (between 0 and 1, default is 0)
  1852. * @param a defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. function Color4(
  1855. /**
  1856. * Defines the red component (between 0 and 1, default is 0)
  1857. */
  1858. r,
  1859. /**
  1860. * Defines the green component (between 0 and 1, default is 0)
  1861. */
  1862. g,
  1863. /**
  1864. * Defines the blue component (between 0 and 1, default is 0)
  1865. */
  1866. b,
  1867. /**
  1868. * Defines the alpha component (between 0 and 1, default is 1)
  1869. */
  1870. a) {
  1871. if (r === void 0) { r = 0; }
  1872. if (g === void 0) { g = 0; }
  1873. if (b === void 0) { b = 0; }
  1874. if (a === void 0) { a = 1; }
  1875. this.r = r;
  1876. this.g = g;
  1877. this.b = b;
  1878. this.a = a;
  1879. }
  1880. // Operators
  1881. /**
  1882. * Adds in place the given Color4 values to the current Color4 object
  1883. * @param right defines the second operand
  1884. * @returns the current updated Color4 object
  1885. */
  1886. Color4.prototype.addInPlace = function (right) {
  1887. this.r += right.r;
  1888. this.g += right.g;
  1889. this.b += right.b;
  1890. this.a += right.a;
  1891. return this;
  1892. };
  1893. /**
  1894. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1895. * @returns the new array
  1896. */
  1897. Color4.prototype.asArray = function () {
  1898. var result = new Array();
  1899. this.toArray(result, 0);
  1900. return result;
  1901. };
  1902. /**
  1903. * Stores from the starting index in the given array the Color4 successive values
  1904. * @param array defines the array where to store the r,g,b components
  1905. * @param index defines an optional index in the target array to define where to start storing values
  1906. * @returns the current Color4 object
  1907. */
  1908. Color4.prototype.toArray = function (array, index) {
  1909. if (index === undefined) {
  1910. index = 0;
  1911. }
  1912. array[index] = this.r;
  1913. array[index + 1] = this.g;
  1914. array[index + 2] = this.b;
  1915. array[index + 3] = this.a;
  1916. return this;
  1917. };
  1918. /**
  1919. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1920. * @param right defines the second operand
  1921. * @returns a new Color4 object
  1922. */
  1923. Color4.prototype.add = function (right) {
  1924. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1925. };
  1926. /**
  1927. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1928. * @param right defines the second operand
  1929. * @returns a new Color4 object
  1930. */
  1931. Color4.prototype.subtract = function (right) {
  1932. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1933. };
  1934. /**
  1935. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1936. * @param right defines the second operand
  1937. * @param result defines the Color4 object where to store the result
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.subtractToRef = function (right, result) {
  1941. result.r = this.r - right.r;
  1942. result.g = this.g - right.g;
  1943. result.b = this.b - right.b;
  1944. result.a = this.a - right.a;
  1945. return this;
  1946. };
  1947. /**
  1948. * Creates a new Color4 with the current Color4 values multiplied by scale
  1949. * @param scale defines the scaling factor to apply
  1950. * @returns a new Color4 object
  1951. */
  1952. Color4.prototype.scale = function (scale) {
  1953. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1954. };
  1955. /**
  1956. * Multiplies the current Color4 values by scale and stores the result in "result"
  1957. * @param scale defines the scaling factor to apply
  1958. * @param result defines the Color4 object where to store the result
  1959. * @returns the current unmodified Color4
  1960. */
  1961. Color4.prototype.scaleToRef = function (scale, result) {
  1962. result.r = this.r * scale;
  1963. result.g = this.g * scale;
  1964. result.b = this.b * scale;
  1965. result.a = this.a * scale;
  1966. return this;
  1967. };
  1968. /**
  1969. * Scale the current Color4 values by a factor and add the result to a given Color4
  1970. * @param scale defines the scale factor
  1971. * @param result defines the Color4 object where to store the result
  1972. * @returns the unmodified current Color4
  1973. */
  1974. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1975. result.r += this.r * scale;
  1976. result.g += this.g * scale;
  1977. result.b += this.b * scale;
  1978. result.a += this.a * scale;
  1979. return this;
  1980. };
  1981. /**
  1982. * Clamps the rgb values by the min and max values and stores the result into "result"
  1983. * @param min defines minimum clamping value (default is 0)
  1984. * @param max defines maximum clamping value (default is 1)
  1985. * @param result defines color to store the result into.
  1986. * @returns the cuurent Color4
  1987. */
  1988. Color4.prototype.clampToRef = function (min, max, result) {
  1989. if (min === void 0) { min = 0; }
  1990. if (max === void 0) { max = 1; }
  1991. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1992. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1993. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1994. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1995. return this;
  1996. };
  1997. /**
  1998. * Multipy an Color4 value by another and return a new Color4 object
  1999. * @param color defines the Color4 value to multiply by
  2000. * @returns a new Color4 object
  2001. */
  2002. Color4.prototype.multiply = function (color) {
  2003. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2004. };
  2005. /**
  2006. * Multipy a Color4 value by another and push the result in a reference value
  2007. * @param color defines the Color4 value to multiply by
  2008. * @param result defines the Color4 to fill the result in
  2009. * @returns the result Color4
  2010. */
  2011. Color4.prototype.multiplyToRef = function (color, result) {
  2012. result.r = this.r * color.r;
  2013. result.g = this.g * color.g;
  2014. result.b = this.b * color.b;
  2015. result.a = this.a * color.a;
  2016. return result;
  2017. };
  2018. /**
  2019. * Creates a string with the Color4 current values
  2020. * @returns the string representation of the Color4 object
  2021. */
  2022. Color4.prototype.toString = function () {
  2023. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2024. };
  2025. /**
  2026. * Returns the string "Color4"
  2027. * @returns "Color4"
  2028. */
  2029. Color4.prototype.getClassName = function () {
  2030. return "Color4";
  2031. };
  2032. /**
  2033. * Compute the Color4 hash code
  2034. * @returns an unique number that can be used to hash Color4 objects
  2035. */
  2036. Color4.prototype.getHashCode = function () {
  2037. var hash = this.r || 0;
  2038. hash = (hash * 397) ^ (this.g || 0);
  2039. hash = (hash * 397) ^ (this.b || 0);
  2040. hash = (hash * 397) ^ (this.a || 0);
  2041. return hash;
  2042. };
  2043. /**
  2044. * Creates a new Color4 copied from the current one
  2045. * @returns a new Color4 object
  2046. */
  2047. Color4.prototype.clone = function () {
  2048. return new Color4(this.r, this.g, this.b, this.a);
  2049. };
  2050. /**
  2051. * Copies the given Color4 values into the current one
  2052. * @param source defines the source Color4 object
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.copyFrom = function (source) {
  2056. this.r = source.r;
  2057. this.g = source.g;
  2058. this.b = source.b;
  2059. this.a = source.a;
  2060. return this;
  2061. };
  2062. /**
  2063. * Copies the given float values into the current one
  2064. * @param r defines the red component to read from
  2065. * @param g defines the green component to read from
  2066. * @param b defines the blue component to read from
  2067. * @param a defines the alpha component to read from
  2068. * @returns the current updated Color4 object
  2069. */
  2070. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2071. this.r = r;
  2072. this.g = g;
  2073. this.b = b;
  2074. this.a = a;
  2075. return this;
  2076. };
  2077. /**
  2078. * Copies the given float values into the current one
  2079. * @param r defines the red component to read from
  2080. * @param g defines the green component to read from
  2081. * @param b defines the blue component to read from
  2082. * @param a defines the alpha component to read from
  2083. * @returns the current updated Color4 object
  2084. */
  2085. Color4.prototype.set = function (r, g, b, a) {
  2086. return this.copyFromFloats(r, g, b, a);
  2087. };
  2088. /**
  2089. * Compute the Color4 hexadecimal code as a string
  2090. * @returns a string containing the hexadecimal representation of the Color4 object
  2091. */
  2092. Color4.prototype.toHexString = function () {
  2093. var intR = (this.r * 255) | 0;
  2094. var intG = (this.g * 255) | 0;
  2095. var intB = (this.b * 255) | 0;
  2096. var intA = (this.a * 255) | 0;
  2097. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2098. };
  2099. /**
  2100. * Computes a new Color4 converted from the current one to linear space
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.toLinearSpace = function () {
  2104. var convertedColor = new Color4();
  2105. this.toLinearSpaceToRef(convertedColor);
  2106. return convertedColor;
  2107. };
  2108. /**
  2109. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2110. * @param convertedColor defines the Color4 object where to store the linear space version
  2111. * @returns the unmodified Color4
  2112. */
  2113. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2114. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2116. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2117. convertedColor.a = this.a;
  2118. return this;
  2119. };
  2120. /**
  2121. * Computes a new Color4 converted from the current one to gamma space
  2122. * @returns a new Color4 object
  2123. */
  2124. Color4.prototype.toGammaSpace = function () {
  2125. var convertedColor = new Color4();
  2126. this.toGammaSpaceToRef(convertedColor);
  2127. return convertedColor;
  2128. };
  2129. /**
  2130. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2131. * @param convertedColor defines the Color4 object where to store the gamma space version
  2132. * @returns the unmodified Color4
  2133. */
  2134. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2135. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2136. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2137. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2138. convertedColor.a = this.a;
  2139. return this;
  2140. };
  2141. // Statics
  2142. /**
  2143. * Creates a new Color4 from the string containing valid hexadecimal values
  2144. * @param hex defines a string containing valid hexadecimal values
  2145. * @returns a new Color4 object
  2146. */
  2147. Color4.FromHexString = function (hex) {
  2148. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2149. return new Color4(0.0, 0.0, 0.0, 0.0);
  2150. }
  2151. var r = parseInt(hex.substring(1, 3), 16);
  2152. var g = parseInt(hex.substring(3, 5), 16);
  2153. var b = parseInt(hex.substring(5, 7), 16);
  2154. var a = parseInt(hex.substring(7, 9), 16);
  2155. return Color4.FromInts(r, g, b, a);
  2156. };
  2157. /**
  2158. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2159. * @param left defines the start value
  2160. * @param right defines the end value
  2161. * @param amount defines the gradient factor
  2162. * @returns a new Color4 object
  2163. */
  2164. Color4.Lerp = function (left, right, amount) {
  2165. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2166. Color4.LerpToRef(left, right, amount, result);
  2167. return result;
  2168. };
  2169. /**
  2170. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2171. * @param left defines the start value
  2172. * @param right defines the end value
  2173. * @param amount defines the gradient factor
  2174. * @param result defines the Color4 object where to store data
  2175. */
  2176. Color4.LerpToRef = function (left, right, amount, result) {
  2177. result.r = left.r + (right.r - left.r) * amount;
  2178. result.g = left.g + (right.g - left.g) * amount;
  2179. result.b = left.b + (right.b - left.b) * amount;
  2180. result.a = left.a + (right.a - left.a) * amount;
  2181. };
  2182. /**
  2183. * Creates a new Color4 from the starting index element of the given array
  2184. * @param array defines the source array to read from
  2185. * @param offset defines the offset in the source array
  2186. * @returns a new Color4 object
  2187. */
  2188. Color4.FromArray = function (array, offset) {
  2189. if (offset === void 0) { offset = 0; }
  2190. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2191. };
  2192. /**
  2193. * Creates a new Color3 from integer values (< 256)
  2194. * @param r defines the red component to read from (value between 0 and 255)
  2195. * @param g defines the green component to read from (value between 0 and 255)
  2196. * @param b defines the blue component to read from (value between 0 and 255)
  2197. * @param a defines the alpha component to read from (value between 0 and 255)
  2198. * @returns a new Color3 object
  2199. */
  2200. Color4.FromInts = function (r, g, b, a) {
  2201. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2202. };
  2203. /**
  2204. * Check the content of a given array and convert it to an array containing RGBA data
  2205. * If the original array was already containing count * 4 values then it is returned directly
  2206. * @param colors defines the array to check
  2207. * @param count defines the number of RGBA data to expect
  2208. * @returns an array containing count * 4 values (RGBA)
  2209. */
  2210. Color4.CheckColors4 = function (colors, count) {
  2211. // Check if color3 was used
  2212. if (colors.length === count * 3) {
  2213. var colors4 = [];
  2214. for (var index = 0; index < colors.length; index += 3) {
  2215. var newIndex = (index / 3) * 4;
  2216. colors4[newIndex] = colors[index];
  2217. colors4[newIndex + 1] = colors[index + 1];
  2218. colors4[newIndex + 2] = colors[index + 2];
  2219. colors4[newIndex + 3] = 1.0;
  2220. }
  2221. return colors4;
  2222. }
  2223. return colors;
  2224. };
  2225. return Color4;
  2226. }());
  2227. BABYLON.Color4 = Color4;
  2228. /**
  2229. * Class representing a vector containing 2 coordinates
  2230. */
  2231. var Vector2 = /** @class */ (function () {
  2232. /**
  2233. * Creates a new Vector2 from the given x and y coordinates
  2234. * @param x defines the first coordinate
  2235. * @param y defines the second coordinate
  2236. */
  2237. function Vector2(
  2238. /** defines the first coordinate */
  2239. x,
  2240. /** defines the second coordinate */
  2241. y) {
  2242. if (x === void 0) { x = 0; }
  2243. if (y === void 0) { y = 0; }
  2244. this.x = x;
  2245. this.y = y;
  2246. }
  2247. /**
  2248. * Gets a string with the Vector2 coordinates
  2249. * @returns a string with the Vector2 coordinates
  2250. */
  2251. Vector2.prototype.toString = function () {
  2252. return "{X: " + this.x + " Y:" + this.y + "}";
  2253. };
  2254. /**
  2255. * Gets class name
  2256. * @returns the string "Vector2"
  2257. */
  2258. Vector2.prototype.getClassName = function () {
  2259. return "Vector2";
  2260. };
  2261. /**
  2262. * Gets current vector hash code
  2263. * @returns the Vector2 hash code as a number
  2264. */
  2265. Vector2.prototype.getHashCode = function () {
  2266. var hash = this.x || 0;
  2267. hash = (hash * 397) ^ (this.y || 0);
  2268. return hash;
  2269. };
  2270. // Operators
  2271. /**
  2272. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2273. * @param array defines the source array
  2274. * @param index defines the offset in source array
  2275. * @returns the current Vector2
  2276. */
  2277. Vector2.prototype.toArray = function (array, index) {
  2278. if (index === void 0) { index = 0; }
  2279. array[index] = this.x;
  2280. array[index + 1] = this.y;
  2281. return this;
  2282. };
  2283. /**
  2284. * Copy the current vector to an array
  2285. * @returns a new array with 2 elements: the Vector2 coordinates.
  2286. */
  2287. Vector2.prototype.asArray = function () {
  2288. var result = new Array();
  2289. this.toArray(result, 0);
  2290. return result;
  2291. };
  2292. /**
  2293. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2294. * @param source defines the source Vector2
  2295. * @returns the current updated Vector2
  2296. */
  2297. Vector2.prototype.copyFrom = function (source) {
  2298. this.x = source.x;
  2299. this.y = source.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Sets the Vector2 coordinates with the given floats
  2304. * @param x defines the first coordinate
  2305. * @param y defines the second coordinate
  2306. * @returns the current updated Vector2
  2307. */
  2308. Vector2.prototype.copyFromFloats = function (x, y) {
  2309. this.x = x;
  2310. this.y = y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Sets the Vector2 coordinates with the given floats
  2315. * @param x defines the first coordinate
  2316. * @param y defines the second coordinate
  2317. * @returns the current updated Vector2
  2318. */
  2319. Vector2.prototype.set = function (x, y) {
  2320. return this.copyFromFloats(x, y);
  2321. };
  2322. /**
  2323. * Add another vector with the current one
  2324. * @param otherVector defines the other vector
  2325. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2326. */
  2327. Vector2.prototype.add = function (otherVector) {
  2328. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2329. };
  2330. /**
  2331. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2332. * @param otherVector defines the other vector
  2333. * @param result defines the target vector
  2334. * @returns the unmodified current Vector2
  2335. */
  2336. Vector2.prototype.addToRef = function (otherVector, result) {
  2337. result.x = this.x + otherVector.x;
  2338. result.y = this.y + otherVector.y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2343. * @param otherVector defines the other vector
  2344. * @returns the current updated Vector2
  2345. */
  2346. Vector2.prototype.addInPlace = function (otherVector) {
  2347. this.x += otherVector.x;
  2348. this.y += otherVector.y;
  2349. return this;
  2350. };
  2351. /**
  2352. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2353. * @param otherVector defines the other vector
  2354. * @returns a new Vector2
  2355. */
  2356. Vector2.prototype.addVector3 = function (otherVector) {
  2357. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2358. };
  2359. /**
  2360. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2361. * @param otherVector defines the other vector
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.subtract = function (otherVector) {
  2365. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2366. };
  2367. /**
  2368. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2369. * @param otherVector defines the other vector
  2370. * @param result defines the target vector
  2371. * @returns the unmodified current Vector2
  2372. */
  2373. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2374. result.x = this.x - otherVector.x;
  2375. result.y = this.y - otherVector.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2380. * @param otherVector defines the other vector
  2381. * @returns the current updated Vector2
  2382. */
  2383. Vector2.prototype.subtractInPlace = function (otherVector) {
  2384. this.x -= otherVector.x;
  2385. this.y -= otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Multiplies in place the current Vector2 coordinates by the given ones
  2390. * @param otherVector defines the other vector
  2391. * @returns the current updated Vector2
  2392. */
  2393. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2394. this.x *= otherVector.x;
  2395. this.y *= otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.multiply = function (otherVector) {
  2404. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2405. };
  2406. /**
  2407. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2408. * @param otherVector defines the other vector
  2409. * @param result defines the target vector
  2410. * @returns the unmodified current Vector2
  2411. */
  2412. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2413. result.x = this.x * otherVector.x;
  2414. result.y = this.y * otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2419. * @param x defines the first coordinate
  2420. * @param y defines the second coordinate
  2421. * @returns a new Vector2
  2422. */
  2423. Vector2.prototype.multiplyByFloats = function (x, y) {
  2424. return new Vector2(this.x * x, this.y * y);
  2425. };
  2426. /**
  2427. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2428. * @param otherVector defines the other vector
  2429. * @returns a new Vector2
  2430. */
  2431. Vector2.prototype.divide = function (otherVector) {
  2432. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2433. };
  2434. /**
  2435. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2436. * @param otherVector defines the other vector
  2437. * @param result defines the target vector
  2438. * @returns the unmodified current Vector2
  2439. */
  2440. Vector2.prototype.divideToRef = function (otherVector, result) {
  2441. result.x = this.x / otherVector.x;
  2442. result.y = this.y / otherVector.y;
  2443. return this;
  2444. };
  2445. /**
  2446. * Divides the current Vector2 coordinates by the given ones
  2447. * @param otherVector defines the other vector
  2448. * @returns the current updated Vector2
  2449. */
  2450. Vector2.prototype.divideInPlace = function (otherVector) {
  2451. return this.divideToRef(otherVector, this);
  2452. };
  2453. /**
  2454. * Gets a new Vector2 with current Vector2 negated coordinates
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.negate = function () {
  2458. return new Vector2(-this.x, -this.y);
  2459. };
  2460. /**
  2461. * Multiply the Vector2 coordinates by scale
  2462. * @param scale defines the scaling factor
  2463. * @returns the current updated Vector2
  2464. */
  2465. Vector2.prototype.scaleInPlace = function (scale) {
  2466. this.x *= scale;
  2467. this.y *= scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2472. * @param scale defines the scaling factor
  2473. * @returns a new Vector2
  2474. */
  2475. Vector2.prototype.scale = function (scale) {
  2476. var result = new Vector2(0, 0);
  2477. this.scaleToRef(scale, result);
  2478. return result;
  2479. };
  2480. /**
  2481. * Scale the current Vector2 values by a factor to a given Vector2
  2482. * @param scale defines the scale factor
  2483. * @param result defines the Vector2 object where to store the result
  2484. * @returns the unmodified current Vector2
  2485. */
  2486. Vector2.prototype.scaleToRef = function (scale, result) {
  2487. result.x = this.x * scale;
  2488. result.y = this.y * scale;
  2489. return this;
  2490. };
  2491. /**
  2492. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2493. * @param scale defines the scale factor
  2494. * @param result defines the Vector2 object where to store the result
  2495. * @returns the unmodified current Vector2
  2496. */
  2497. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2498. result.x += this.x * scale;
  2499. result.y += this.y * scale;
  2500. return this;
  2501. };
  2502. /**
  2503. * Gets a boolean if two vectors are equals
  2504. * @param otherVector defines the other vector
  2505. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2506. */
  2507. Vector2.prototype.equals = function (otherVector) {
  2508. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2509. };
  2510. /**
  2511. * Gets a boolean if two vectors are equals (using an epsilon value)
  2512. * @param otherVector defines the other vector
  2513. * @param epsilon defines the minimal distance to consider equality
  2514. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2515. */
  2516. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2517. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2518. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2519. };
  2520. /**
  2521. * Gets a new Vector2 from current Vector2 floored values
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.prototype.floor = function () {
  2525. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2526. };
  2527. /**
  2528. * Gets a new Vector2 from current Vector2 floored values
  2529. * @returns a new Vector2
  2530. */
  2531. Vector2.prototype.fract = function () {
  2532. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2533. };
  2534. // Properties
  2535. /**
  2536. * Gets the length of the vector
  2537. * @returns the vector length (float)
  2538. */
  2539. Vector2.prototype.length = function () {
  2540. return Math.sqrt(this.x * this.x + this.y * this.y);
  2541. };
  2542. /**
  2543. * Gets the vector squared length
  2544. * @returns the vector squared length (float)
  2545. */
  2546. Vector2.prototype.lengthSquared = function () {
  2547. return (this.x * this.x + this.y * this.y);
  2548. };
  2549. // Methods
  2550. /**
  2551. * Normalize the vector
  2552. * @returns the current updated Vector2
  2553. */
  2554. Vector2.prototype.normalize = function () {
  2555. var len = this.length();
  2556. if (len === 0)
  2557. return this;
  2558. var num = 1.0 / len;
  2559. this.x *= num;
  2560. this.y *= num;
  2561. return this;
  2562. };
  2563. /**
  2564. * Gets a new Vector2 copied from the Vector2
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.prototype.clone = function () {
  2568. return new Vector2(this.x, this.y);
  2569. };
  2570. // Statics
  2571. /**
  2572. * Gets a new Vector2(0, 0)
  2573. * @returns a new Vector2
  2574. */
  2575. Vector2.Zero = function () {
  2576. return new Vector2(0, 0);
  2577. };
  2578. /**
  2579. * Gets a new Vector2(1, 1)
  2580. * @returns a new Vector2
  2581. */
  2582. Vector2.One = function () {
  2583. return new Vector2(1, 1);
  2584. };
  2585. /**
  2586. * Gets a new Vector2 set from the given index element of the given array
  2587. * @param array defines the data source
  2588. * @param offset defines the offset in the data source
  2589. * @returns a new Vector2
  2590. */
  2591. Vector2.FromArray = function (array, offset) {
  2592. if (offset === void 0) { offset = 0; }
  2593. return new Vector2(array[offset], array[offset + 1]);
  2594. };
  2595. /**
  2596. * Sets "result" from the given index element of the given array
  2597. * @param array defines the data source
  2598. * @param offset defines the offset in the data source
  2599. * @param result defines the target vector
  2600. */
  2601. Vector2.FromArrayToRef = function (array, offset, result) {
  2602. result.x = array[offset];
  2603. result.y = array[offset + 1];
  2604. };
  2605. /**
  2606. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2607. * @param value1 defines 1st point of control
  2608. * @param value2 defines 2nd point of control
  2609. * @param value3 defines 3rd point of control
  2610. * @param value4 defines 4th point of control
  2611. * @param amount defines the interpolation factor
  2612. * @returns a new Vector2
  2613. */
  2614. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2615. var squared = amount * amount;
  2616. var cubed = amount * squared;
  2617. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2618. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2619. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2620. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2621. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2622. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2623. return new Vector2(x, y);
  2624. };
  2625. /**
  2626. * 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".
  2627. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2628. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2629. * @param value defines the value to clamp
  2630. * @param min defines the lower limit
  2631. * @param max defines the upper limit
  2632. * @returns a new Vector2
  2633. */
  2634. Vector2.Clamp = function (value, min, max) {
  2635. var x = value.x;
  2636. x = (x > max.x) ? max.x : x;
  2637. x = (x < min.x) ? min.x : x;
  2638. var y = value.y;
  2639. y = (y > max.y) ? max.y : y;
  2640. y = (y < min.y) ? min.y : y;
  2641. return new Vector2(x, y);
  2642. };
  2643. /**
  2644. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2645. * @param value1 defines the 1st control point
  2646. * @param tangent1 defines the outgoing tangent
  2647. * @param value2 defines the 2nd control point
  2648. * @param tangent2 defines the incoming tangent
  2649. * @param amount defines the interpolation factor
  2650. * @returns a new Vector2
  2651. */
  2652. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2653. var squared = amount * amount;
  2654. var cubed = amount * squared;
  2655. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2656. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2657. var part3 = (cubed - (2.0 * squared)) + amount;
  2658. var part4 = cubed - squared;
  2659. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2660. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2665. * @param start defines the start vector
  2666. * @param end defines the end vector
  2667. * @param amount defines the interpolation factor
  2668. * @returns a new Vector2
  2669. */
  2670. Vector2.Lerp = function (start, end, amount) {
  2671. var x = start.x + ((end.x - start.x) * amount);
  2672. var y = start.y + ((end.y - start.y) * amount);
  2673. return new Vector2(x, y);
  2674. };
  2675. /**
  2676. * Gets the dot product of the vector "left" and the vector "right"
  2677. * @param left defines first vector
  2678. * @param right defines second vector
  2679. * @returns the dot product (float)
  2680. */
  2681. Vector2.Dot = function (left, right) {
  2682. return left.x * right.x + left.y * right.y;
  2683. };
  2684. /**
  2685. * Returns a new Vector2 equal to the normalized given vector
  2686. * @param vector defines the vector to normalize
  2687. * @returns a new Vector2
  2688. */
  2689. Vector2.Normalize = function (vector) {
  2690. var newVector = vector.clone();
  2691. newVector.normalize();
  2692. return newVector;
  2693. };
  2694. /**
  2695. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2696. * @param left defines 1st vector
  2697. * @param right defines 2nd vector
  2698. * @returns a new Vector2
  2699. */
  2700. Vector2.Minimize = function (left, right) {
  2701. var x = (left.x < right.x) ? left.x : right.x;
  2702. var y = (left.y < right.y) ? left.y : right.y;
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2707. * @param left defines 1st vector
  2708. * @param right defines 2nd vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Maximize = function (left, right) {
  2712. var x = (left.x > right.x) ? left.x : right.x;
  2713. var y = (left.y > right.y) ? left.y : right.y;
  2714. return new Vector2(x, y);
  2715. };
  2716. /**
  2717. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2718. * @param vector defines the vector to transform
  2719. * @param transformation defines the matrix to apply
  2720. * @returns a new Vector2
  2721. */
  2722. Vector2.Transform = function (vector, transformation) {
  2723. var r = Vector2.Zero();
  2724. Vector2.TransformToRef(vector, transformation, r);
  2725. return r;
  2726. };
  2727. /**
  2728. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2729. * @param vector defines the vector to transform
  2730. * @param transformation defines the matrix to apply
  2731. * @param result defines the target vector
  2732. */
  2733. Vector2.TransformToRef = function (vector, transformation, result) {
  2734. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2735. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2736. result.x = x;
  2737. result.y = y;
  2738. };
  2739. /**
  2740. * Determines if a given vector is included in a triangle
  2741. * @param p defines the vector to test
  2742. * @param p0 defines 1st triangle point
  2743. * @param p1 defines 2nd triangle point
  2744. * @param p2 defines 3rd triangle point
  2745. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2746. */
  2747. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2748. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2749. var sign = a < 0 ? -1 : 1;
  2750. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2751. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2752. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2753. };
  2754. /**
  2755. * Gets the distance between the vectors "value1" and "value2"
  2756. * @param value1 defines first vector
  2757. * @param value2 defines second vector
  2758. * @returns the distance between vectors
  2759. */
  2760. Vector2.Distance = function (value1, value2) {
  2761. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2762. };
  2763. /**
  2764. * Returns the squared distance between the vectors "value1" and "value2"
  2765. * @param value1 defines first vector
  2766. * @param value2 defines second vector
  2767. * @returns the squared distance between vectors
  2768. */
  2769. Vector2.DistanceSquared = function (value1, value2) {
  2770. var x = value1.x - value2.x;
  2771. var y = value1.y - value2.y;
  2772. return (x * x) + (y * y);
  2773. };
  2774. /**
  2775. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2776. * @param value1 defines first vector
  2777. * @param value2 defines second vector
  2778. * @returns a new Vector2
  2779. */
  2780. Vector2.Center = function (value1, value2) {
  2781. var center = value1.add(value2);
  2782. center.scaleInPlace(0.5);
  2783. return center;
  2784. };
  2785. /**
  2786. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2787. * @param p defines the middle point
  2788. * @param segA defines one point of the segment
  2789. * @param segB defines the other point of the segment
  2790. * @returns the shortest distance
  2791. */
  2792. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2793. var l2 = Vector2.DistanceSquared(segA, segB);
  2794. if (l2 === 0.0) {
  2795. return Vector2.Distance(p, segA);
  2796. }
  2797. var v = segB.subtract(segA);
  2798. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2799. var proj = segA.add(v.multiplyByFloats(t, t));
  2800. return Vector2.Distance(p, proj);
  2801. };
  2802. return Vector2;
  2803. }());
  2804. BABYLON.Vector2 = Vector2;
  2805. /**
  2806. * Classed used to store (x,y,z) vector representation
  2807. * A Vector3 is the main object used in 3D geometry
  2808. * It can represent etiher the coordinates of a point the space, either a direction
  2809. * Reminder: Babylon.js uses a left handed forward facing system
  2810. */
  2811. var Vector3 = /** @class */ (function () {
  2812. /**
  2813. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2814. * @param x defines the first coordinates (on X axis)
  2815. * @param y defines the second coordinates (on Y axis)
  2816. * @param z defines the third coordinates (on Z axis)
  2817. */
  2818. function Vector3(
  2819. /**
  2820. * Defines the first coordinates (on X axis)
  2821. */
  2822. x,
  2823. /**
  2824. * Defines the second coordinates (on Y axis)
  2825. */
  2826. y,
  2827. /**
  2828. * Defines the third coordinates (on Z axis)
  2829. */
  2830. z) {
  2831. if (x === void 0) { x = 0; }
  2832. if (y === void 0) { y = 0; }
  2833. if (z === void 0) { z = 0; }
  2834. this.x = x;
  2835. this.y = y;
  2836. this.z = z;
  2837. }
  2838. /**
  2839. * Creates a string representation of the Vector3
  2840. * @returns a string with the Vector3 coordinates.
  2841. */
  2842. Vector3.prototype.toString = function () {
  2843. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2844. };
  2845. /**
  2846. * Gets the class name
  2847. * @returns the string "Vector3"
  2848. */
  2849. Vector3.prototype.getClassName = function () {
  2850. return "Vector3";
  2851. };
  2852. /**
  2853. * Creates the Vector3 hash code
  2854. * @returns a number which tends to be unique between Vector3 instances
  2855. */
  2856. Vector3.prototype.getHashCode = function () {
  2857. var hash = this.x || 0;
  2858. hash = (hash * 397) ^ (this.y || 0);
  2859. hash = (hash * 397) ^ (this.z || 0);
  2860. return hash;
  2861. };
  2862. // Operators
  2863. /**
  2864. * Creates an array containing three elements : the coordinates of the Vector3
  2865. * @returns a new array of numbers
  2866. */
  2867. Vector3.prototype.asArray = function () {
  2868. var result = [];
  2869. this.toArray(result, 0);
  2870. return result;
  2871. };
  2872. /**
  2873. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2874. * @param array defines the destination array
  2875. * @param index defines the offset in the destination array
  2876. * @returns the current Vector3
  2877. */
  2878. Vector3.prototype.toArray = function (array, index) {
  2879. if (index === void 0) { index = 0; }
  2880. array[index] = this.x;
  2881. array[index + 1] = this.y;
  2882. array[index + 2] = this.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2887. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2888. */
  2889. Vector3.prototype.toQuaternion = function () {
  2890. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2891. };
  2892. /**
  2893. * Adds the given vector to the current Vector3
  2894. * @param otherVector defines the second operand
  2895. * @returns the current updated Vector3
  2896. */
  2897. Vector3.prototype.addInPlace = function (otherVector) {
  2898. this.x += otherVector.x;
  2899. this.y += otherVector.y;
  2900. this.z += otherVector.z;
  2901. return this;
  2902. };
  2903. /**
  2904. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2905. * @param otherVector defines the second operand
  2906. * @returns the resulting Vector3
  2907. */
  2908. Vector3.prototype.add = function (otherVector) {
  2909. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2910. };
  2911. /**
  2912. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2913. * @param otherVector defines the second operand
  2914. * @param result defines the Vector3 object where to store the result
  2915. * @returns the current Vector3
  2916. */
  2917. Vector3.prototype.addToRef = function (otherVector, result) {
  2918. result.x = this.x + otherVector.x;
  2919. result.y = this.y + otherVector.y;
  2920. result.z = this.z + otherVector.z;
  2921. return this;
  2922. };
  2923. /**
  2924. * Subtract the given vector from the current Vector3
  2925. * @param otherVector defines the second operand
  2926. * @returns the current updated Vector3
  2927. */
  2928. Vector3.prototype.subtractInPlace = function (otherVector) {
  2929. this.x -= otherVector.x;
  2930. this.y -= otherVector.y;
  2931. this.z -= otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the resulting Vector3
  2938. */
  2939. Vector3.prototype.subtract = function (otherVector) {
  2940. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2941. };
  2942. /**
  2943. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2944. * @param otherVector defines the second operand
  2945. * @param result defines the Vector3 object where to store the result
  2946. * @returns the current Vector3
  2947. */
  2948. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2949. result.x = this.x - otherVector.x;
  2950. result.y = this.y - otherVector.y;
  2951. result.z = this.z - otherVector.z;
  2952. return this;
  2953. };
  2954. /**
  2955. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2956. * @param x defines the x coordinate of the operand
  2957. * @param y defines the y coordinate of the operand
  2958. * @param z defines the z coordinate of the operand
  2959. * @returns the resulting Vector3
  2960. */
  2961. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2962. return new Vector3(this.x - x, this.y - y, this.z - z);
  2963. };
  2964. /**
  2965. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2966. * @param x defines the x coordinate of the operand
  2967. * @param y defines the y coordinate of the operand
  2968. * @param z defines the z coordinate of the operand
  2969. * @param result defines the Vector3 object where to store the result
  2970. * @returns the current Vector3
  2971. */
  2972. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2973. result.x = this.x - x;
  2974. result.y = this.y - y;
  2975. result.z = this.z - z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2980. * @returns a new Vector3
  2981. */
  2982. Vector3.prototype.negate = function () {
  2983. return new Vector3(-this.x, -this.y, -this.z);
  2984. };
  2985. /**
  2986. * Multiplies the Vector3 coordinates by the float "scale"
  2987. * @param scale defines the multiplier factor
  2988. * @returns the current updated Vector3
  2989. */
  2990. Vector3.prototype.scaleInPlace = function (scale) {
  2991. this.x *= scale;
  2992. this.y *= scale;
  2993. this.z *= scale;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2998. * @param scale defines the multiplier factor
  2999. * @returns a new Vector3
  3000. */
  3001. Vector3.prototype.scale = function (scale) {
  3002. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3003. };
  3004. /**
  3005. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3006. * @param scale defines the multiplier factor
  3007. * @param result defines the Vector3 object where to store the result
  3008. * @returns the current Vector3
  3009. */
  3010. Vector3.prototype.scaleToRef = function (scale, result) {
  3011. result.x = this.x * scale;
  3012. result.y = this.y * scale;
  3013. result.z = this.z * scale;
  3014. return this;
  3015. };
  3016. /**
  3017. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3018. * @param scale defines the scale factor
  3019. * @param result defines the Vector3 object where to store the result
  3020. * @returns the unmodified current Vector3
  3021. */
  3022. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3023. result.x += this.x * scale;
  3024. result.y += this.y * scale;
  3025. result.z += this.z * scale;
  3026. return this;
  3027. };
  3028. /**
  3029. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3030. * @param otherVector defines the second operand
  3031. * @returns true if both vectors are equals
  3032. */
  3033. Vector3.prototype.equals = function (otherVector) {
  3034. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3035. };
  3036. /**
  3037. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3038. * @param otherVector defines the second operand
  3039. * @param epsilon defines the minimal distance to define values as equals
  3040. * @returns true if both vectors are distant less than epsilon
  3041. */
  3042. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3043. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3044. 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);
  3045. };
  3046. /**
  3047. * Returns true if the current Vector3 coordinates equals the given floats
  3048. * @param x defines the x coordinate of the operand
  3049. * @param y defines the y coordinate of the operand
  3050. * @param z defines the z coordinate of the operand
  3051. * @returns true if both vectors are equals
  3052. */
  3053. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3054. return this.x === x && this.y === y && this.z === z;
  3055. };
  3056. /**
  3057. * Multiplies the current Vector3 coordinates by the given ones
  3058. * @param otherVector defines the second operand
  3059. * @returns the current updated Vector3
  3060. */
  3061. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3062. this.x *= otherVector.x;
  3063. this.y *= otherVector.y;
  3064. this.z *= otherVector.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3069. * @param otherVector defines the second operand
  3070. * @returns the new Vector3
  3071. */
  3072. Vector3.prototype.multiply = function (otherVector) {
  3073. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3074. };
  3075. /**
  3076. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3077. * @param otherVector defines the second operand
  3078. * @param result defines the Vector3 object where to store the result
  3079. * @returns the current Vector3
  3080. */
  3081. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3082. result.x = this.x * otherVector.x;
  3083. result.y = this.y * otherVector.y;
  3084. result.z = this.z * otherVector.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3089. * @param x defines the x coordinate of the operand
  3090. * @param y defines the y coordinate of the operand
  3091. * @param z defines the z coordinate of the operand
  3092. * @returns the new Vector3
  3093. */
  3094. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3095. return new Vector3(this.x * x, this.y * y, this.z * z);
  3096. };
  3097. /**
  3098. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3099. * @param otherVector defines the second operand
  3100. * @returns the new Vector3
  3101. */
  3102. Vector3.prototype.divide = function (otherVector) {
  3103. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3104. };
  3105. /**
  3106. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3107. * @param otherVector defines the second operand
  3108. * @param result defines the Vector3 object where to store the result
  3109. * @returns the current Vector3
  3110. */
  3111. Vector3.prototype.divideToRef = function (otherVector, result) {
  3112. result.x = this.x / otherVector.x;
  3113. result.y = this.y / otherVector.y;
  3114. result.z = this.z / otherVector.z;
  3115. return this;
  3116. };
  3117. /**
  3118. * Divides the current Vector3 coordinates by the given ones.
  3119. * @param otherVector defines the second operand
  3120. * @returns the current updated Vector3
  3121. */
  3122. Vector3.prototype.divideInPlace = function (otherVector) {
  3123. return this.divideToRef(otherVector, this);
  3124. };
  3125. /**
  3126. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3127. * @param other defines the second operand
  3128. * @returns the current updated Vector3
  3129. */
  3130. Vector3.prototype.minimizeInPlace = function (other) {
  3131. if (other.x < this.x)
  3132. this.x = other.x;
  3133. if (other.y < this.y)
  3134. this.y = other.y;
  3135. if (other.z < this.z)
  3136. this.z = other.z;
  3137. return this;
  3138. };
  3139. /**
  3140. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3141. * @param other defines the second operand
  3142. * @returns the current updated Vector3
  3143. */
  3144. Vector3.prototype.maximizeInPlace = function (other) {
  3145. if (other.x > this.x)
  3146. this.x = other.x;
  3147. if (other.y > this.y)
  3148. this.y = other.y;
  3149. if (other.z > this.z)
  3150. this.z = other.z;
  3151. return this;
  3152. };
  3153. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3154. /**
  3155. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3156. */
  3157. get: function () {
  3158. var absX = Math.abs(this.x);
  3159. var absY = Math.abs(this.y);
  3160. if (absX !== absY) {
  3161. return true;
  3162. }
  3163. var absZ = Math.abs(this.z);
  3164. if (absX !== absZ) {
  3165. return true;
  3166. }
  3167. if (absY !== absZ) {
  3168. return true;
  3169. }
  3170. return false;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. /**
  3176. * Gets a new Vector3 from current Vector3 floored values
  3177. * @returns a new Vector3
  3178. */
  3179. Vector3.prototype.floor = function () {
  3180. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3181. };
  3182. /**
  3183. * Gets a new Vector3 from current Vector3 floored values
  3184. * @returns a new Vector3
  3185. */
  3186. Vector3.prototype.fract = function () {
  3187. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3188. };
  3189. // Properties
  3190. /**
  3191. * Gets the length of the Vector3
  3192. * @returns the length of the Vecto3
  3193. */
  3194. Vector3.prototype.length = function () {
  3195. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3196. };
  3197. /**
  3198. * Gets the squared length of the Vector3
  3199. * @returns squared length of the Vector3
  3200. */
  3201. Vector3.prototype.lengthSquared = function () {
  3202. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3203. };
  3204. /**
  3205. * Normalize the current Vector3.
  3206. * Please note that this is an in place operation.
  3207. * @returns the current updated Vector3
  3208. */
  3209. Vector3.prototype.normalize = function () {
  3210. var len = this.length();
  3211. if (len === 0 || len === 1.0)
  3212. return this;
  3213. var num = 1.0 / len;
  3214. this.x *= num;
  3215. this.y *= num;
  3216. this.z *= num;
  3217. return this;
  3218. };
  3219. /**
  3220. * Normalize the current Vector3 to a new vector
  3221. * @returns the new Vector3
  3222. */
  3223. Vector3.prototype.normalizeToNew = function () {
  3224. var normalized = new Vector3(0, 0, 0);
  3225. this.normalizeToRef(normalized);
  3226. return normalized;
  3227. };
  3228. /**
  3229. * Normalize the current Vector3 to the reference
  3230. * @param reference define the Vector3 to update
  3231. * @returns the updated Vector3
  3232. */
  3233. Vector3.prototype.normalizeToRef = function (reference) {
  3234. var len = this.length();
  3235. if (len === 0 || len === 1.0) {
  3236. reference.set(this.x, this.y, this.z);
  3237. return reference;
  3238. }
  3239. var scale = 1.0 / len;
  3240. this.scaleToRef(scale, reference);
  3241. return reference;
  3242. };
  3243. /**
  3244. * Creates a new Vector3 copied from the current Vector3
  3245. * @returns the new Vector3
  3246. */
  3247. Vector3.prototype.clone = function () {
  3248. return new Vector3(this.x, this.y, this.z);
  3249. };
  3250. /**
  3251. * Copies the given vector coordinates to the current Vector3 ones
  3252. * @param source defines the source Vector3
  3253. * @returns the current updated Vector3
  3254. */
  3255. Vector3.prototype.copyFrom = function (source) {
  3256. this.x = source.x;
  3257. this.y = source.y;
  3258. this.z = source.z;
  3259. return this;
  3260. };
  3261. /**
  3262. * Copies the given floats to the current Vector3 coordinates
  3263. * @param x defines the x coordinate of the operand
  3264. * @param y defines the y coordinate of the operand
  3265. * @param z defines the z coordinate of the operand
  3266. * @returns the current updated Vector3
  3267. */
  3268. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3269. this.x = x;
  3270. this.y = y;
  3271. this.z = z;
  3272. return this;
  3273. };
  3274. /**
  3275. * Copies the given floats to the current Vector3 coordinates
  3276. * @param x defines the x coordinate of the operand
  3277. * @param y defines the y coordinate of the operand
  3278. * @param z defines the z coordinate of the operand
  3279. * @returns the current updated Vector3
  3280. */
  3281. Vector3.prototype.set = function (x, y, z) {
  3282. return this.copyFromFloats(x, y, z);
  3283. };
  3284. // Statics
  3285. /**
  3286. * Get the clip factor between two vectors
  3287. * @param vector0 defines the first operand
  3288. * @param vector1 defines the second operand
  3289. * @param axis defines the axis to use
  3290. * @param size defines the size along the axis
  3291. * @returns the clip factor
  3292. */
  3293. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3294. var d0 = Vector3.Dot(vector0, axis) - size;
  3295. var d1 = Vector3.Dot(vector1, axis) - size;
  3296. var s = d0 / (d0 - d1);
  3297. return s;
  3298. };
  3299. /**
  3300. * Get angle between two vectors
  3301. * @param vector0 angle between vector0 and vector1
  3302. * @param vector1 angle between vector0 and vector1
  3303. * @param normal direction of the normal
  3304. * @return the angle between vector0 and vector1
  3305. */
  3306. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3307. var v0 = vector0.clone().normalize();
  3308. var v1 = vector1.clone().normalize();
  3309. var dot = Vector3.Dot(v0, v1);
  3310. var n = Vector3.Cross(v0, v1);
  3311. if (Vector3.Dot(n, normal) > 0) {
  3312. return Math.acos(dot);
  3313. }
  3314. return -Math.acos(dot);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set from the index "offset" of the given array
  3318. * @param array defines the source array
  3319. * @param offset defines the offset in the source array
  3320. * @returns the new Vector3
  3321. */
  3322. Vector3.FromArray = function (array, offset) {
  3323. if (!offset) {
  3324. offset = 0;
  3325. }
  3326. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3330. * This function is deprecated. Use FromArray instead
  3331. * @param array defines the source array
  3332. * @param offset defines the offset in the source array
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.FromFloatArray = function (array, offset) {
  3336. return Vector3.FromArray(array, offset);
  3337. };
  3338. /**
  3339. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3340. * @param array defines the source array
  3341. * @param offset defines the offset in the source array
  3342. * @param result defines the Vector3 where to store the result
  3343. */
  3344. Vector3.FromArrayToRef = function (array, offset, result) {
  3345. result.x = array[offset];
  3346. result.y = array[offset + 1];
  3347. result.z = array[offset + 2];
  3348. };
  3349. /**
  3350. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3351. * This function is deprecated. Use FromArrayToRef instead.
  3352. * @param array defines the source array
  3353. * @param offset defines the offset in the source array
  3354. * @param result defines the Vector3 where to store the result
  3355. */
  3356. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3357. return Vector3.FromArrayToRef(array, offset, result);
  3358. };
  3359. /**
  3360. * Sets the given vector "result" with the given floats.
  3361. * @param x defines the x coordinate of the source
  3362. * @param y defines the y coordinate of the source
  3363. * @param z defines the z coordinate of the source
  3364. * @param result defines the Vector3 where to store the result
  3365. */
  3366. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3367. result.x = x;
  3368. result.y = y;
  3369. result.z = z;
  3370. };
  3371. /**
  3372. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3373. * @returns a new empty Vector3
  3374. */
  3375. Vector3.Zero = function () {
  3376. return new Vector3(0.0, 0.0, 0.0);
  3377. };
  3378. /**
  3379. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3380. * @returns a new unit Vector3
  3381. */
  3382. Vector3.One = function () {
  3383. return new Vector3(1.0, 1.0, 1.0);
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3387. * @returns a new up Vector3
  3388. */
  3389. Vector3.Up = function () {
  3390. return new Vector3(0.0, 1.0, 0.0);
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3394. * @returns a new down Vector3
  3395. */
  3396. Vector3.Down = function () {
  3397. return new Vector3(0.0, -1.0, 0.0);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3401. * @returns a new forward Vector3
  3402. */
  3403. Vector3.Forward = function () {
  3404. return new Vector3(0.0, 0.0, 1.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3408. * @returns a new right Vector3
  3409. */
  3410. Vector3.Right = function () {
  3411. return new Vector3(1.0, 0.0, 0.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3415. * @returns a new left Vector3
  3416. */
  3417. Vector3.Left = function () {
  3418. return new Vector3(-1.0, 0.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3422. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3423. * @param vector defines the Vector3 to transform
  3424. * @param transformation defines the transformation matrix
  3425. * @returns the transformed Vector3
  3426. */
  3427. Vector3.TransformCoordinates = function (vector, transformation) {
  3428. var result = Vector3.Zero();
  3429. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3430. return result;
  3431. };
  3432. /**
  3433. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3434. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3435. * @param vector defines the Vector3 to transform
  3436. * @param transformation defines the transformation matrix
  3437. * @param result defines the Vector3 where to store the result
  3438. */
  3439. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3443. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3444. result.x = x / w;
  3445. result.y = y / w;
  3446. result.z = z / w;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3450. * This method computes tranformed coordinates only, not transformed direction vectors
  3451. * @param x define the x coordinate of the source vector
  3452. * @param y define the y coordinate of the source vector
  3453. * @param z define the z coordinate of the source vector
  3454. * @param transformation defines the transformation matrix
  3455. * @param result defines the Vector3 where to store the result
  3456. */
  3457. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3458. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3459. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3460. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3461. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3462. result.x = rx / rw;
  3463. result.y = ry / rw;
  3464. result.z = rz / rw;
  3465. };
  3466. /**
  3467. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param vector defines the Vector3 to transform
  3470. * @param transformation defines the transformation matrix
  3471. * @returns the new Vector3
  3472. */
  3473. Vector3.TransformNormal = function (vector, transformation) {
  3474. var result = Vector3.Zero();
  3475. Vector3.TransformNormalToRef(vector, transformation, result);
  3476. return result;
  3477. };
  3478. /**
  3479. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3480. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3481. * @param vector defines the Vector3 to transform
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3486. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3487. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3488. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3489. result.x = x;
  3490. result.y = y;
  3491. result.z = z;
  3492. };
  3493. /**
  3494. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3495. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3496. * @param x define the x coordinate of the source vector
  3497. * @param y define the y coordinate of the source vector
  3498. * @param z define the z coordinate of the source vector
  3499. * @param transformation defines the transformation matrix
  3500. * @param result defines the Vector3 where to store the result
  3501. */
  3502. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3503. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3504. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3505. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3506. };
  3507. /**
  3508. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3509. * @param value1 defines the first control point
  3510. * @param value2 defines the second control point
  3511. * @param value3 defines the third control point
  3512. * @param value4 defines the fourth control point
  3513. * @param amount defines the amount on the spline to use
  3514. * @returns the new Vector3
  3515. */
  3516. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3517. var squared = amount * amount;
  3518. var cubed = amount * squared;
  3519. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3520. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3521. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3522. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3523. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3524. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3525. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3526. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3527. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3528. return new Vector3(x, y, z);
  3529. };
  3530. /**
  3531. * 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"
  3532. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3533. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3534. * @param value defines the current value
  3535. * @param min defines the lower range value
  3536. * @param max defines the upper range value
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.Clamp = function (value, min, max) {
  3540. var x = value.x;
  3541. x = (x > max.x) ? max.x : x;
  3542. x = (x < min.x) ? min.x : x;
  3543. var y = value.y;
  3544. y = (y > max.y) ? max.y : y;
  3545. y = (y < min.y) ? min.y : y;
  3546. var z = value.z;
  3547. z = (z > max.z) ? max.z : z;
  3548. z = (z < min.z) ? min.z : z;
  3549. return new Vector3(x, y, z);
  3550. };
  3551. /**
  3552. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3553. * @param value1 defines the first control point
  3554. * @param tangent1 defines the first tangent vector
  3555. * @param value2 defines the second control point
  3556. * @param tangent2 defines the second tangent vector
  3557. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3561. var squared = amount * amount;
  3562. var cubed = amount * squared;
  3563. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3564. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3565. var part3 = (cubed - (2.0 * squared)) + amount;
  3566. var part4 = cubed - squared;
  3567. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3568. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3569. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3570. return new Vector3(x, y, z);
  3571. };
  3572. /**
  3573. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3574. * @param start defines the start value
  3575. * @param end defines the end value
  3576. * @param amount max defines amount between both (between 0 and 1)
  3577. * @returns the new Vector3
  3578. */
  3579. Vector3.Lerp = function (start, end, amount) {
  3580. var result = new Vector3(0, 0, 0);
  3581. Vector3.LerpToRef(start, end, amount, result);
  3582. return result;
  3583. };
  3584. /**
  3585. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3586. * @param start defines the start value
  3587. * @param end defines the end value
  3588. * @param amount max defines amount between both (between 0 and 1)
  3589. * @param result defines the Vector3 where to store the result
  3590. */
  3591. Vector3.LerpToRef = function (start, end, amount, result) {
  3592. result.x = start.x + ((end.x - start.x) * amount);
  3593. result.y = start.y + ((end.y - start.y) * amount);
  3594. result.z = start.z + ((end.z - start.z) * amount);
  3595. };
  3596. /**
  3597. * Returns the dot product (float) between the vectors "left" and "right"
  3598. * @param left defines the left operand
  3599. * @param right defines the right operand
  3600. * @returns the dot product
  3601. */
  3602. Vector3.Dot = function (left, right) {
  3603. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3604. };
  3605. /**
  3606. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3607. * The cross product is then orthogonal to both "left" and "right"
  3608. * @param left defines the left operand
  3609. * @param right defines the right operand
  3610. * @returns the cross product
  3611. */
  3612. Vector3.Cross = function (left, right) {
  3613. var result = Vector3.Zero();
  3614. Vector3.CrossToRef(left, right, result);
  3615. return result;
  3616. };
  3617. /**
  3618. * Sets the given vector "result" with the cross product of "left" and "right"
  3619. * The cross product is then orthogonal to both "left" and "right"
  3620. * @param left defines the left operand
  3621. * @param right defines the right operand
  3622. * @param result defines the Vector3 where to store the result
  3623. */
  3624. Vector3.CrossToRef = function (left, right, result) {
  3625. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3626. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3627. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3628. result.copyFrom(MathTmp.Vector3[0]);
  3629. };
  3630. /**
  3631. * Returns a new Vector3 as the normalization of the given vector
  3632. * @param vector defines the Vector3 to normalize
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Normalize = function (vector) {
  3636. var result = Vector3.Zero();
  3637. Vector3.NormalizeToRef(vector, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Sets the given vector "result" with the normalization of the given first vector
  3642. * @param vector defines the Vector3 to normalize
  3643. * @param result defines the Vector3 where to store the result
  3644. */
  3645. Vector3.NormalizeToRef = function (vector, result) {
  3646. result.copyFrom(vector);
  3647. result.normalize();
  3648. };
  3649. /**
  3650. * Project a Vector3 onto screen space
  3651. * @param vector defines the Vector3 to project
  3652. * @param world defines the world matrix to use
  3653. * @param transform defines the transform (view x projection) matrix to use
  3654. * @param viewport defines the screen viewport to use
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Project = function (vector, world, transform, viewport) {
  3658. var cw = viewport.width;
  3659. var ch = viewport.height;
  3660. var cx = viewport.x;
  3661. var cy = viewport.y;
  3662. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3663. 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);
  3664. var matrix = MathTmp.Matrix[0];
  3665. world.multiplyToRef(transform, matrix);
  3666. matrix.multiplyToRef(viewportMatrix, matrix);
  3667. return Vector3.TransformCoordinates(vector, matrix);
  3668. };
  3669. /**
  3670. * Unproject from screen space to object space
  3671. * @param source defines the screen space Vector3 to use
  3672. * @param viewportWidth defines the current width of the viewport
  3673. * @param viewportHeight defines the current height of the viewport
  3674. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3675. * @param transform defines the transform (view x projection) matrix to use
  3676. * @returns the new Vector3
  3677. */
  3678. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3679. var matrix = MathTmp.Matrix[0];
  3680. world.multiplyToRef(transform, matrix);
  3681. matrix.invert();
  3682. source.x = source.x / viewportWidth * 2 - 1;
  3683. source.y = -(source.y / viewportHeight * 2 - 1);
  3684. var vector = Vector3.TransformCoordinates(source, matrix);
  3685. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3686. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3687. vector = vector.scale(1.0 / num);
  3688. }
  3689. return vector;
  3690. };
  3691. /**
  3692. * Unproject from screen space to object space
  3693. * @param source defines the screen space Vector3 to use
  3694. * @param viewportWidth defines the current width of the viewport
  3695. * @param viewportHeight defines the current height of the viewport
  3696. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3697. * @param view defines the view matrix to use
  3698. * @param projection defines the projection matrix to use
  3699. * @returns the new Vector3
  3700. */
  3701. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3702. var result = Vector3.Zero();
  3703. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3704. return result;
  3705. };
  3706. /**
  3707. * Unproject from screen space to object space
  3708. * @param source defines the screen space Vector3 to use
  3709. * @param viewportWidth defines the current width of the viewport
  3710. * @param viewportHeight defines the current height of the viewport
  3711. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3712. * @param view defines the view matrix to use
  3713. * @param projection defines the projection matrix to use
  3714. * @param result defines the Vector3 where to store the result
  3715. */
  3716. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3717. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param sourceX defines the screen space x coordinate to use
  3722. * @param sourceY defines the screen space y coordinate to use
  3723. * @param sourceZ defines the screen space z coordinate to use
  3724. * @param viewportWidth defines the current width of the viewport
  3725. * @param viewportHeight defines the current height of the viewport
  3726. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3727. * @param view defines the view matrix to use
  3728. * @param projection defines the projection matrix to use
  3729. * @param result defines the Vector3 where to store the result
  3730. */
  3731. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3732. var matrix = MathTmp.Matrix[0];
  3733. world.multiplyToRef(view, matrix);
  3734. matrix.multiplyToRef(projection, matrix);
  3735. matrix.invert();
  3736. var screenSource = MathTmp.Vector3[0];
  3737. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3738. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3739. screenSource.z = 2 * sourceZ - 1.0;
  3740. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3741. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3742. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3743. result.scaleInPlace(1.0 / num);
  3744. }
  3745. };
  3746. /**
  3747. * Gets the minimal coordinate values between two Vector3
  3748. * @param left defines the first operand
  3749. * @param right defines the second operand
  3750. * @returns the new Vector3
  3751. */
  3752. Vector3.Minimize = function (left, right) {
  3753. var min = left.clone();
  3754. min.minimizeInPlace(right);
  3755. return min;
  3756. };
  3757. /**
  3758. * Gets the maximal coordinate values between two Vector3
  3759. * @param left defines the first operand
  3760. * @param right defines the second operand
  3761. * @returns the new Vector3
  3762. */
  3763. Vector3.Maximize = function (left, right) {
  3764. var max = left.clone();
  3765. max.maximizeInPlace(right);
  3766. return max;
  3767. };
  3768. /**
  3769. * Returns the distance between the vectors "value1" and "value2"
  3770. * @param value1 defines the first operand
  3771. * @param value2 defines the second operand
  3772. * @returns the distance
  3773. */
  3774. Vector3.Distance = function (value1, value2) {
  3775. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3776. };
  3777. /**
  3778. * Returns the squared distance between the vectors "value1" and "value2"
  3779. * @param value1 defines the first operand
  3780. * @param value2 defines the second operand
  3781. * @returns the squared distance
  3782. */
  3783. Vector3.DistanceSquared = function (value1, value2) {
  3784. var x = value1.x - value2.x;
  3785. var y = value1.y - value2.y;
  3786. var z = value1.z - value2.z;
  3787. return (x * x) + (y * y) + (z * z);
  3788. };
  3789. /**
  3790. * Returns a new Vector3 located at the center between "value1" and "value2"
  3791. * @param value1 defines the first operand
  3792. * @param value2 defines the second operand
  3793. * @returns the new Vector3
  3794. */
  3795. Vector3.Center = function (value1, value2) {
  3796. var center = value1.add(value2);
  3797. center.scaleInPlace(0.5);
  3798. return center;
  3799. };
  3800. /**
  3801. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3802. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3803. * to something in order to rotate it from its local system to the given target system
  3804. * Note: axis1, axis2 and axis3 are normalized during this operation
  3805. * @param axis1 defines the first axis
  3806. * @param axis2 defines the second axis
  3807. * @param axis3 defines the third axis
  3808. * @returns a new Vector3
  3809. */
  3810. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3811. var rotation = Vector3.Zero();
  3812. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3813. return rotation;
  3814. };
  3815. /**
  3816. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3817. * @param axis1 defines the first axis
  3818. * @param axis2 defines the second axis
  3819. * @param axis3 defines the third axis
  3820. * @param ref defines the Vector3 where to store the result
  3821. */
  3822. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3823. var quat = MathTmp.Quaternion[0];
  3824. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3825. quat.toEulerAnglesToRef(ref);
  3826. };
  3827. return Vector3;
  3828. }());
  3829. BABYLON.Vector3 = Vector3;
  3830. //Vector4 class created for EulerAngle class conversion to Quaternion
  3831. var Vector4 = /** @class */ (function () {
  3832. /**
  3833. * Creates a Vector4 object from the given floats.
  3834. */
  3835. function Vector4(x, y, z, w) {
  3836. this.x = x;
  3837. this.y = y;
  3838. this.z = z;
  3839. this.w = w;
  3840. }
  3841. /**
  3842. * Returns the string with the Vector4 coordinates.
  3843. */
  3844. Vector4.prototype.toString = function () {
  3845. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3846. };
  3847. /**
  3848. * Returns the string "Vector4".
  3849. */
  3850. Vector4.prototype.getClassName = function () {
  3851. return "Vector4";
  3852. };
  3853. /**
  3854. * Returns the Vector4 hash code.
  3855. */
  3856. Vector4.prototype.getHashCode = function () {
  3857. var hash = this.x || 0;
  3858. hash = (hash * 397) ^ (this.y || 0);
  3859. hash = (hash * 397) ^ (this.z || 0);
  3860. hash = (hash * 397) ^ (this.w || 0);
  3861. return hash;
  3862. };
  3863. // Operators
  3864. /**
  3865. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3866. */
  3867. Vector4.prototype.asArray = function () {
  3868. var result = new Array();
  3869. this.toArray(result, 0);
  3870. return result;
  3871. };
  3872. /**
  3873. * Populates the given array from the given index with the Vector4 coordinates.
  3874. * Returns the Vector4.
  3875. */
  3876. Vector4.prototype.toArray = function (array, index) {
  3877. if (index === undefined) {
  3878. index = 0;
  3879. }
  3880. array[index] = this.x;
  3881. array[index + 1] = this.y;
  3882. array[index + 2] = this.z;
  3883. array[index + 3] = this.w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Adds the given vector to the current Vector4.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.addInPlace = function (otherVector) {
  3891. this.x += otherVector.x;
  3892. this.y += otherVector.y;
  3893. this.z += otherVector.z;
  3894. this.w += otherVector.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3899. */
  3900. Vector4.prototype.add = function (otherVector) {
  3901. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3902. };
  3903. /**
  3904. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3905. * Returns the current Vector4.
  3906. */
  3907. Vector4.prototype.addToRef = function (otherVector, result) {
  3908. result.x = this.x + otherVector.x;
  3909. result.y = this.y + otherVector.y;
  3910. result.z = this.z + otherVector.z;
  3911. result.w = this.w + otherVector.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Subtract in place the given vector from the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.subtractInPlace = function (otherVector) {
  3919. this.x -= otherVector.x;
  3920. this.y -= otherVector.y;
  3921. this.z -= otherVector.z;
  3922. this.w -= otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3927. */
  3928. Vector4.prototype.subtract = function (otherVector) {
  3929. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3930. };
  3931. /**
  3932. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3936. result.x = this.x - otherVector.x;
  3937. result.y = this.y - otherVector.y;
  3938. result.z = this.z - otherVector.z;
  3939. result.w = this.w - otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3946. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3947. };
  3948. /**
  3949. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3950. * Returns the current Vector4.
  3951. */
  3952. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3953. result.x = this.x - x;
  3954. result.y = this.y - y;
  3955. result.z = this.z - z;
  3956. result.w = this.w - w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3961. */
  3962. Vector4.prototype.negate = function () {
  3963. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3964. };
  3965. /**
  3966. * Multiplies the current Vector4 coordinates by scale (float).
  3967. * Returns the updated Vector4.
  3968. */
  3969. Vector4.prototype.scaleInPlace = function (scale) {
  3970. this.x *= scale;
  3971. this.y *= scale;
  3972. this.z *= scale;
  3973. this.w *= scale;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3978. */
  3979. Vector4.prototype.scale = function (scale) {
  3980. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3981. };
  3982. /**
  3983. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3984. * Returns the current Vector4.
  3985. */
  3986. Vector4.prototype.scaleToRef = function (scale, result) {
  3987. result.x = this.x * scale;
  3988. result.y = this.y * scale;
  3989. result.z = this.z * scale;
  3990. result.w = this.w * scale;
  3991. return this;
  3992. };
  3993. /**
  3994. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3995. * @param scale defines the scale factor
  3996. * @param result defines the Vector4 object where to store the result
  3997. * @returns the unmodified current Vector4
  3998. */
  3999. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4000. result.x += this.x * scale;
  4001. result.y += this.y * scale;
  4002. result.z += this.z * scale;
  4003. result.w += this.w * scale;
  4004. return this;
  4005. };
  4006. /**
  4007. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4008. */
  4009. Vector4.prototype.equals = function (otherVector) {
  4010. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4011. };
  4012. /**
  4013. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4014. */
  4015. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4016. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4017. return otherVector
  4018. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4019. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4020. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4021. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4022. };
  4023. /**
  4024. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4025. */
  4026. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4027. return this.x === x && this.y === y && this.z === z && this.w === w;
  4028. };
  4029. /**
  4030. * Multiplies in place the current Vector4 by the given one.
  4031. * Returns the updated Vector4.
  4032. */
  4033. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4034. this.x *= otherVector.x;
  4035. this.y *= otherVector.y;
  4036. this.z *= otherVector.z;
  4037. this.w *= otherVector.w;
  4038. return this;
  4039. };
  4040. /**
  4041. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4042. */
  4043. Vector4.prototype.multiply = function (otherVector) {
  4044. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4045. };
  4046. /**
  4047. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4048. * Returns the current Vector4.
  4049. */
  4050. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4051. result.x = this.x * otherVector.x;
  4052. result.y = this.y * otherVector.y;
  4053. result.z = this.z * otherVector.z;
  4054. result.w = this.w * otherVector.w;
  4055. return this;
  4056. };
  4057. /**
  4058. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4059. */
  4060. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4061. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4062. };
  4063. /**
  4064. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4065. */
  4066. Vector4.prototype.divide = function (otherVector) {
  4067. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4068. };
  4069. /**
  4070. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4071. * Returns the current Vector4.
  4072. */
  4073. Vector4.prototype.divideToRef = function (otherVector, result) {
  4074. result.x = this.x / otherVector.x;
  4075. result.y = this.y / otherVector.y;
  4076. result.z = this.z / otherVector.z;
  4077. result.w = this.w / otherVector.w;
  4078. return this;
  4079. };
  4080. /**
  4081. * Divides the current Vector3 coordinates by the given ones.
  4082. * @returns the updated Vector3.
  4083. */
  4084. Vector4.prototype.divideInPlace = function (otherVector) {
  4085. return this.divideToRef(otherVector, this);
  4086. };
  4087. /**
  4088. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4089. * @param other defines the second operand
  4090. * @returns the current updated Vector4
  4091. */
  4092. Vector4.prototype.minimizeInPlace = function (other) {
  4093. if (other.x < this.x)
  4094. this.x = other.x;
  4095. if (other.y < this.y)
  4096. this.y = other.y;
  4097. if (other.z < this.z)
  4098. this.z = other.z;
  4099. if (other.w < this.w)
  4100. this.w = other.w;
  4101. return this;
  4102. };
  4103. /**
  4104. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4105. * @param other defines the second operand
  4106. * @returns the current updated Vector4
  4107. */
  4108. Vector4.prototype.maximizeInPlace = function (other) {
  4109. if (other.x > this.x)
  4110. this.x = other.x;
  4111. if (other.y > this.y)
  4112. this.y = other.y;
  4113. if (other.z > this.z)
  4114. this.z = other.z;
  4115. if (other.w > this.w)
  4116. this.w = other.w;
  4117. return this;
  4118. };
  4119. /**
  4120. * Gets a new Vector4 from current Vector4 floored values
  4121. * @returns a new Vector4
  4122. */
  4123. Vector4.prototype.floor = function () {
  4124. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4125. };
  4126. /**
  4127. * Gets a new Vector4 from current Vector3 floored values
  4128. * @returns a new Vector4
  4129. */
  4130. Vector4.prototype.fract = function () {
  4131. 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));
  4132. };
  4133. // Properties
  4134. /**
  4135. * Returns the Vector4 length (float).
  4136. */
  4137. Vector4.prototype.length = function () {
  4138. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4139. };
  4140. /**
  4141. * Returns the Vector4 squared length (float).
  4142. */
  4143. Vector4.prototype.lengthSquared = function () {
  4144. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4145. };
  4146. // Methods
  4147. /**
  4148. * Normalizes in place the Vector4.
  4149. * Returns the updated Vector4.
  4150. */
  4151. Vector4.prototype.normalize = function () {
  4152. var len = this.length();
  4153. if (len === 0)
  4154. return this;
  4155. var num = 1.0 / len;
  4156. this.x *= num;
  4157. this.y *= num;
  4158. this.z *= num;
  4159. this.w *= num;
  4160. return this;
  4161. };
  4162. /**
  4163. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4164. */
  4165. Vector4.prototype.toVector3 = function () {
  4166. return new Vector3(this.x, this.y, this.z);
  4167. };
  4168. /**
  4169. * Returns a new Vector4 copied from the current one.
  4170. */
  4171. Vector4.prototype.clone = function () {
  4172. return new Vector4(this.x, this.y, this.z, this.w);
  4173. };
  4174. /**
  4175. * Updates the current Vector4 with the given one coordinates.
  4176. * Returns the updated Vector4.
  4177. */
  4178. Vector4.prototype.copyFrom = function (source) {
  4179. this.x = source.x;
  4180. this.y = source.y;
  4181. this.z = source.z;
  4182. this.w = source.w;
  4183. return this;
  4184. };
  4185. /**
  4186. * Updates the current Vector4 coordinates with the given floats.
  4187. * Returns the updated Vector4.
  4188. */
  4189. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4190. this.x = x;
  4191. this.y = y;
  4192. this.z = z;
  4193. this.w = w;
  4194. return this;
  4195. };
  4196. /**
  4197. * Updates the current Vector4 coordinates with the given floats.
  4198. * Returns the updated Vector4.
  4199. */
  4200. Vector4.prototype.set = function (x, y, z, w) {
  4201. return this.copyFromFloats(x, y, z, w);
  4202. };
  4203. // Statics
  4204. /**
  4205. * Returns a new Vector4 set from the starting index of the given array.
  4206. */
  4207. Vector4.FromArray = function (array, offset) {
  4208. if (!offset) {
  4209. offset = 0;
  4210. }
  4211. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4212. };
  4213. /**
  4214. * Updates the given vector "result" from the starting index of the given array.
  4215. */
  4216. Vector4.FromArrayToRef = function (array, offset, result) {
  4217. result.x = array[offset];
  4218. result.y = array[offset + 1];
  4219. result.z = array[offset + 2];
  4220. result.w = array[offset + 3];
  4221. };
  4222. /**
  4223. * Updates the given vector "result" from the starting index of the given Float32Array.
  4224. */
  4225. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4226. Vector4.FromArrayToRef(array, offset, result);
  4227. };
  4228. /**
  4229. * Updates the given vector "result" coordinates from the given floats.
  4230. */
  4231. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4232. result.x = x;
  4233. result.y = y;
  4234. result.z = z;
  4235. result.w = w;
  4236. };
  4237. /**
  4238. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4239. */
  4240. Vector4.Zero = function () {
  4241. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4242. };
  4243. /**
  4244. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4245. */
  4246. Vector4.One = function () {
  4247. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4248. };
  4249. /**
  4250. * Returns a new normalized Vector4 from the given one.
  4251. */
  4252. Vector4.Normalize = function (vector) {
  4253. var result = Vector4.Zero();
  4254. Vector4.NormalizeToRef(vector, result);
  4255. return result;
  4256. };
  4257. /**
  4258. * Updates the given vector "result" from the normalization of the given one.
  4259. */
  4260. Vector4.NormalizeToRef = function (vector, result) {
  4261. result.copyFrom(vector);
  4262. result.normalize();
  4263. };
  4264. Vector4.Minimize = function (left, right) {
  4265. var min = left.clone();
  4266. min.minimizeInPlace(right);
  4267. return min;
  4268. };
  4269. Vector4.Maximize = function (left, right) {
  4270. var max = left.clone();
  4271. max.maximizeInPlace(right);
  4272. return max;
  4273. };
  4274. /**
  4275. * Returns the distance (float) between the vectors "value1" and "value2".
  4276. */
  4277. Vector4.Distance = function (value1, value2) {
  4278. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4279. };
  4280. /**
  4281. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4282. */
  4283. Vector4.DistanceSquared = function (value1, value2) {
  4284. var x = value1.x - value2.x;
  4285. var y = value1.y - value2.y;
  4286. var z = value1.z - value2.z;
  4287. var w = value1.w - value2.w;
  4288. return (x * x) + (y * y) + (z * z) + (w * w);
  4289. };
  4290. /**
  4291. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4292. */
  4293. Vector4.Center = function (value1, value2) {
  4294. var center = value1.add(value2);
  4295. center.scaleInPlace(0.5);
  4296. return center;
  4297. };
  4298. /**
  4299. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4300. * This methods computes transformed normalized direction vectors only.
  4301. */
  4302. Vector4.TransformNormal = function (vector, transformation) {
  4303. var result = Vector4.Zero();
  4304. Vector4.TransformNormalToRef(vector, transformation, result);
  4305. return result;
  4306. };
  4307. /**
  4308. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4309. * This methods computes transformed normalized direction vectors only.
  4310. */
  4311. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4312. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4313. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4314. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4315. result.x = x;
  4316. result.y = y;
  4317. result.z = z;
  4318. result.w = vector.w;
  4319. };
  4320. /**
  4321. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4322. * This methods computes transformed normalized direction vectors only.
  4323. */
  4324. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4325. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4326. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4327. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4328. result.w = w;
  4329. };
  4330. return Vector4;
  4331. }());
  4332. BABYLON.Vector4 = Vector4;
  4333. var Size = /** @class */ (function () {
  4334. /**
  4335. * Creates a Size object from the given width and height (floats).
  4336. */
  4337. function Size(width, height) {
  4338. this.width = width;
  4339. this.height = height;
  4340. }
  4341. // Returns a string with the Size width and height.
  4342. Size.prototype.toString = function () {
  4343. return "{W: " + this.width + ", H: " + this.height + "}";
  4344. };
  4345. /**
  4346. * Returns the string "Size"
  4347. */
  4348. Size.prototype.getClassName = function () {
  4349. return "Size";
  4350. };
  4351. /**
  4352. * Returns the Size hash code.
  4353. */
  4354. Size.prototype.getHashCode = function () {
  4355. var hash = this.width || 0;
  4356. hash = (hash * 397) ^ (this.height || 0);
  4357. return hash;
  4358. };
  4359. /**
  4360. * Updates the current size from the given one.
  4361. * Returns the updated Size.
  4362. */
  4363. Size.prototype.copyFrom = function (src) {
  4364. this.width = src.width;
  4365. this.height = src.height;
  4366. };
  4367. /**
  4368. * Updates in place the current Size from the given floats.
  4369. * Returns the updated Size.
  4370. */
  4371. Size.prototype.copyFromFloats = function (width, height) {
  4372. this.width = width;
  4373. this.height = height;
  4374. return this;
  4375. };
  4376. /**
  4377. * Updates in place the current Size from the given floats.
  4378. * Returns the updated Size.
  4379. */
  4380. Size.prototype.set = function (width, height) {
  4381. return this.copyFromFloats(width, height);
  4382. };
  4383. /**
  4384. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4385. */
  4386. Size.prototype.multiplyByFloats = function (w, h) {
  4387. return new Size(this.width * w, this.height * h);
  4388. };
  4389. /**
  4390. * Returns a new Size copied from the given one.
  4391. */
  4392. Size.prototype.clone = function () {
  4393. return new Size(this.width, this.height);
  4394. };
  4395. /**
  4396. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4397. */
  4398. Size.prototype.equals = function (other) {
  4399. if (!other) {
  4400. return false;
  4401. }
  4402. return (this.width === other.width) && (this.height === other.height);
  4403. };
  4404. Object.defineProperty(Size.prototype, "surface", {
  4405. /**
  4406. * Returns the surface of the Size : width * height (float).
  4407. */
  4408. get: function () {
  4409. return this.width * this.height;
  4410. },
  4411. enumerable: true,
  4412. configurable: true
  4413. });
  4414. /**
  4415. * Returns a new Size set to (0.0, 0.0)
  4416. */
  4417. Size.Zero = function () {
  4418. return new Size(0.0, 0.0);
  4419. };
  4420. /**
  4421. * Returns a new Size set as the addition result of the current Size and the given one.
  4422. */
  4423. Size.prototype.add = function (otherSize) {
  4424. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4425. return r;
  4426. };
  4427. /**
  4428. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4429. */
  4430. Size.prototype.subtract = function (otherSize) {
  4431. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4432. return r;
  4433. };
  4434. /**
  4435. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4436. */
  4437. Size.Lerp = function (start, end, amount) {
  4438. var w = start.width + ((end.width - start.width) * amount);
  4439. var h = start.height + ((end.height - start.height) * amount);
  4440. return new Size(w, h);
  4441. };
  4442. return Size;
  4443. }());
  4444. BABYLON.Size = Size;
  4445. /**
  4446. * Class used to store quaternion data
  4447. * @see https://en.wikipedia.org/wiki/Quaternion
  4448. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4449. */
  4450. var Quaternion = /** @class */ (function () {
  4451. /**
  4452. * Creates a new Quaternion from the given floats
  4453. * @param x defines the first component (0 by default)
  4454. * @param y defines the second component (0 by default)
  4455. * @param z defines the third component (0 by default)
  4456. * @param w defines the fourth component (1.0 by default)
  4457. */
  4458. function Quaternion(
  4459. /** defines the first component (0 by default) */
  4460. x,
  4461. /** defines the second component (0 by default) */
  4462. y,
  4463. /** defines the third component (0 by default) */
  4464. z,
  4465. /** defines the fourth component (1.0 by default) */
  4466. w) {
  4467. if (x === void 0) { x = 0.0; }
  4468. if (y === void 0) { y = 0.0; }
  4469. if (z === void 0) { z = 0.0; }
  4470. if (w === void 0) { w = 1.0; }
  4471. this.x = x;
  4472. this.y = y;
  4473. this.z = z;
  4474. this.w = w;
  4475. }
  4476. /**
  4477. * Gets a string representation for the current quaternion
  4478. * @returns a string with the Quaternion coordinates
  4479. */
  4480. Quaternion.prototype.toString = function () {
  4481. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4482. };
  4483. /**
  4484. * Gets the class name of the quaternion
  4485. * @returns the string "Quaternion"
  4486. */
  4487. Quaternion.prototype.getClassName = function () {
  4488. return "Quaternion";
  4489. };
  4490. /**
  4491. * Gets a hash code for this quaternion
  4492. * @returns the quaternion hash code
  4493. */
  4494. Quaternion.prototype.getHashCode = function () {
  4495. var hash = this.x || 0;
  4496. hash = (hash * 397) ^ (this.y || 0);
  4497. hash = (hash * 397) ^ (this.z || 0);
  4498. hash = (hash * 397) ^ (this.w || 0);
  4499. return hash;
  4500. };
  4501. /**
  4502. * Copy the quaternion to an array
  4503. * @returns a new array populated with 4 elements from the quaternion coordinates
  4504. */
  4505. Quaternion.prototype.asArray = function () {
  4506. return [this.x, this.y, this.z, this.w];
  4507. };
  4508. /**
  4509. * Check if two quaternions are equals
  4510. * @param otherQuaternion defines the second operand
  4511. * @return true if the current quaternion and the given one coordinates are strictly equals
  4512. */
  4513. Quaternion.prototype.equals = function (otherQuaternion) {
  4514. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4515. };
  4516. /**
  4517. * Clone the current quaternion
  4518. * @returns a new quaternion copied from the current one
  4519. */
  4520. Quaternion.prototype.clone = function () {
  4521. return new Quaternion(this.x, this.y, this.z, this.w);
  4522. };
  4523. /**
  4524. * Copy a quaternion to the current one
  4525. * @param other defines the other quaternion
  4526. * @returns the updated current quaternion
  4527. */
  4528. Quaternion.prototype.copyFrom = function (other) {
  4529. this.x = other.x;
  4530. this.y = other.y;
  4531. this.z = other.z;
  4532. this.w = other.w;
  4533. return this;
  4534. };
  4535. /**
  4536. * Updates the current quaternion with the given float coordinates
  4537. * @param x defines the x coordinate
  4538. * @param y defines the y coordinate
  4539. * @param z defines the z coordinate
  4540. * @param w defines the w coordinate
  4541. * @returns the updated current quaternion
  4542. */
  4543. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4544. this.x = x;
  4545. this.y = y;
  4546. this.z = z;
  4547. this.w = w;
  4548. return this;
  4549. };
  4550. /**
  4551. * Updates the current quaternion from the given float coordinates
  4552. * @param x defines the x coordinate
  4553. * @param y defines the y coordinate
  4554. * @param z defines the z coordinate
  4555. * @param w defines the w coordinate
  4556. * @returns the updated current quaternion
  4557. */
  4558. Quaternion.prototype.set = function (x, y, z, w) {
  4559. return this.copyFromFloats(x, y, z, w);
  4560. };
  4561. /**
  4562. * Adds two quaternions
  4563. * @param other defines the second operand
  4564. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4565. */
  4566. Quaternion.prototype.add = function (other) {
  4567. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4568. };
  4569. /**
  4570. * Add a quaternion to the current one
  4571. * @param other defines the quaternion to add
  4572. * @returns the current quaternion
  4573. */
  4574. Quaternion.prototype.addInPlace = function (other) {
  4575. this.x += other.x;
  4576. this.y += other.y;
  4577. this.z += other.z;
  4578. this.w += other.w;
  4579. return this;
  4580. };
  4581. /**
  4582. * Subtract two quaternions
  4583. * @param other defines the second operand
  4584. * @returns a new quaternion as the subtraction result of the given one from the current one
  4585. */
  4586. Quaternion.prototype.subtract = function (other) {
  4587. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4588. };
  4589. /**
  4590. * Multiplies the current quaternion by a scale factor
  4591. * @param value defines the scale factor
  4592. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4593. */
  4594. Quaternion.prototype.scale = function (value) {
  4595. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4596. };
  4597. /**
  4598. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4599. * @param scale defines the scale factor
  4600. * @param result defines the Quaternion object where to store the result
  4601. * @returns the unmodified current quaternion
  4602. */
  4603. Quaternion.prototype.scaleToRef = function (scale, result) {
  4604. result.x = this.x * scale;
  4605. result.y = this.y * scale;
  4606. result.z = this.z * scale;
  4607. result.w = this.w * scale;
  4608. return this;
  4609. };
  4610. /**
  4611. * Multiplies in place the current quaternion by a scale factor
  4612. * @param value defines the scale factor
  4613. * @returns the current modified quaternion
  4614. */
  4615. Quaternion.prototype.scaleInPlace = function (value) {
  4616. this.x *= value;
  4617. this.y *= value;
  4618. this.z *= value;
  4619. this.w *= value;
  4620. return this;
  4621. };
  4622. /**
  4623. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4624. * @param scale defines the scale factor
  4625. * @param result defines the Quaternion object where to store the result
  4626. * @returns the unmodified current quaternion
  4627. */
  4628. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4629. result.x += this.x * scale;
  4630. result.y += this.y * scale;
  4631. result.z += this.z * scale;
  4632. result.w += this.w * scale;
  4633. return this;
  4634. };
  4635. /**
  4636. * Multiplies two quaternions
  4637. * @param q1 defines the second operand
  4638. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4639. */
  4640. Quaternion.prototype.multiply = function (q1) {
  4641. var result = new Quaternion(0, 0, 0, 1.0);
  4642. this.multiplyToRef(q1, result);
  4643. return result;
  4644. };
  4645. /**
  4646. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4647. * @param q1 defines the second operand
  4648. * @param result defines the target quaternion
  4649. * @returns the current quaternion
  4650. */
  4651. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4652. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4653. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4654. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4655. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4656. result.copyFromFloats(x, y, z, w);
  4657. return this;
  4658. };
  4659. /**
  4660. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4661. * @param q1 defines the second operand
  4662. * @returns the currentupdated quaternion
  4663. */
  4664. Quaternion.prototype.multiplyInPlace = function (q1) {
  4665. this.multiplyToRef(q1, this);
  4666. return this;
  4667. };
  4668. /**
  4669. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4670. * @param ref defines the target quaternion
  4671. * @returns the current quaternion
  4672. */
  4673. Quaternion.prototype.conjugateToRef = function (ref) {
  4674. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4675. return this;
  4676. };
  4677. /**
  4678. * Conjugates in place (1-q) the current quaternion
  4679. * @returns the current updated quaternion
  4680. */
  4681. Quaternion.prototype.conjugateInPlace = function () {
  4682. this.x *= -1;
  4683. this.y *= -1;
  4684. this.z *= -1;
  4685. return this;
  4686. };
  4687. /**
  4688. * Conjugates in place (1-q) the current quaternion
  4689. * @returns a new quaternion
  4690. */
  4691. Quaternion.prototype.conjugate = function () {
  4692. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4693. return result;
  4694. };
  4695. /**
  4696. * Gets length of current quaternion
  4697. * @returns the quaternion length (float)
  4698. */
  4699. Quaternion.prototype.length = function () {
  4700. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4701. };
  4702. /**
  4703. * Normalize in place the current quaternion
  4704. * @returns the current updated quaternion
  4705. */
  4706. Quaternion.prototype.normalize = function () {
  4707. var length = 1.0 / this.length();
  4708. this.x *= length;
  4709. this.y *= length;
  4710. this.z *= length;
  4711. this.w *= length;
  4712. return this;
  4713. };
  4714. /**
  4715. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4716. * @param order is a reserved parameter and is ignore for now
  4717. * @returns a new Vector3 containing the Euler angles
  4718. */
  4719. Quaternion.prototype.toEulerAngles = function (order) {
  4720. if (order === void 0) { order = "YZX"; }
  4721. var result = Vector3.Zero();
  4722. this.toEulerAnglesToRef(result, order);
  4723. return result;
  4724. };
  4725. /**
  4726. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4727. * @param result defines the vector which will be filled with the Euler angles
  4728. * @param order is a reserved parameter and is ignore for now
  4729. * @returns the current unchanged quaternion
  4730. */
  4731. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4732. if (order === void 0) { order = "YZX"; }
  4733. var qz = this.z;
  4734. var qx = this.x;
  4735. var qy = this.y;
  4736. var qw = this.w;
  4737. var sqw = qw * qw;
  4738. var sqz = qz * qz;
  4739. var sqx = qx * qx;
  4740. var sqy = qy * qy;
  4741. var zAxisY = qy * qz - qx * qw;
  4742. var limit = .4999999;
  4743. if (zAxisY < -limit) {
  4744. result.y = 2 * Math.atan2(qy, qw);
  4745. result.x = Math.PI / 2;
  4746. result.z = 0;
  4747. }
  4748. else if (zAxisY > limit) {
  4749. result.y = 2 * Math.atan2(qy, qw);
  4750. result.x = -Math.PI / 2;
  4751. result.z = 0;
  4752. }
  4753. else {
  4754. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4755. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4756. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4757. }
  4758. return this;
  4759. };
  4760. /**
  4761. * Updates the given rotation matrix with the current quaternion values
  4762. * @param result defines the target matrix
  4763. * @returns the current unchanged quaternion
  4764. */
  4765. Quaternion.prototype.toRotationMatrix = function (result) {
  4766. var xx = this.x * this.x;
  4767. var yy = this.y * this.y;
  4768. var zz = this.z * this.z;
  4769. var xy = this.x * this.y;
  4770. var zw = this.z * this.w;
  4771. var zx = this.z * this.x;
  4772. var yw = this.y * this.w;
  4773. var yz = this.y * this.z;
  4774. var xw = this.x * this.w;
  4775. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4776. result.m[1] = 2.0 * (xy + zw);
  4777. result.m[2] = 2.0 * (zx - yw);
  4778. result.m[3] = 0;
  4779. result.m[4] = 2.0 * (xy - zw);
  4780. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4781. result.m[6] = 2.0 * (yz + xw);
  4782. result.m[7] = 0;
  4783. result.m[8] = 2.0 * (zx + yw);
  4784. result.m[9] = 2.0 * (yz - xw);
  4785. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4786. result.m[11] = 0;
  4787. result.m[12] = 0;
  4788. result.m[13] = 0;
  4789. result.m[14] = 0;
  4790. result.m[15] = 1.0;
  4791. result._markAsUpdated();
  4792. return this;
  4793. };
  4794. /**
  4795. * Updates the current quaternion from the given rotation matrix values
  4796. * @param matrix defines the source matrix
  4797. * @returns the current updated quaternion
  4798. */
  4799. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4800. Quaternion.FromRotationMatrixToRef(matrix, this);
  4801. return this;
  4802. };
  4803. // Statics
  4804. /**
  4805. * Creates a new quaternion from a rotation matrix
  4806. * @param matrix defines the source matrix
  4807. * @returns a new quaternion created from the given rotation matrix values
  4808. */
  4809. Quaternion.FromRotationMatrix = function (matrix) {
  4810. var result = new Quaternion();
  4811. Quaternion.FromRotationMatrixToRef(matrix, result);
  4812. return result;
  4813. };
  4814. /**
  4815. * Updates the given quaternion with the given rotation matrix values
  4816. * @param matrix defines the source matrix
  4817. * @param result defines the target quaternion
  4818. */
  4819. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4820. var data = matrix.m;
  4821. var m11 = data[0], m12 = data[4], m13 = data[8];
  4822. var m21 = data[1], m22 = data[5], m23 = data[9];
  4823. var m31 = data[2], m32 = data[6], m33 = data[10];
  4824. var trace = m11 + m22 + m33;
  4825. var s;
  4826. if (trace > 0) {
  4827. s = 0.5 / Math.sqrt(trace + 1.0);
  4828. result.w = 0.25 / s;
  4829. result.x = (m32 - m23) * s;
  4830. result.y = (m13 - m31) * s;
  4831. result.z = (m21 - m12) * s;
  4832. }
  4833. else if (m11 > m22 && m11 > m33) {
  4834. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4835. result.w = (m32 - m23) / s;
  4836. result.x = 0.25 * s;
  4837. result.y = (m12 + m21) / s;
  4838. result.z = (m13 + m31) / s;
  4839. }
  4840. else if (m22 > m33) {
  4841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4842. result.w = (m13 - m31) / s;
  4843. result.x = (m12 + m21) / s;
  4844. result.y = 0.25 * s;
  4845. result.z = (m23 + m32) / s;
  4846. }
  4847. else {
  4848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4849. result.w = (m21 - m12) / s;
  4850. result.x = (m13 + m31) / s;
  4851. result.y = (m23 + m32) / s;
  4852. result.z = 0.25 * s;
  4853. }
  4854. };
  4855. /**
  4856. * Returns the dot product (float) between the quaternions "left" and "right"
  4857. * @param left defines the left operand
  4858. * @param right defines the right operand
  4859. * @returns the dot product
  4860. */
  4861. Quaternion.Dot = function (left, right) {
  4862. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4863. };
  4864. /**
  4865. * Checks if the two quaternions are close to each other
  4866. * @param quat0 defines the first quaternion to check
  4867. * @param quat1 defines the second quaternion to check
  4868. * @returns true if the two quaternions are close to each other
  4869. */
  4870. Quaternion.AreClose = function (quat0, quat1) {
  4871. var dot = Quaternion.Dot(quat0, quat1);
  4872. return dot >= 0;
  4873. };
  4874. /**
  4875. * Creates an empty quaternion
  4876. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4877. */
  4878. Quaternion.Zero = function () {
  4879. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4880. };
  4881. /**
  4882. * Inverse a given quaternion
  4883. * @param q defines the source quaternion
  4884. * @returns a new quaternion as the inverted current quaternion
  4885. */
  4886. Quaternion.Inverse = function (q) {
  4887. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4888. };
  4889. /**
  4890. * Creates an identity quaternion
  4891. * @returns the identity quaternion
  4892. */
  4893. Quaternion.Identity = function () {
  4894. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4895. };
  4896. /**
  4897. * Gets a boolean indicating if the given quaternion is identity
  4898. * @param quaternion defines the quaternion to check
  4899. * @returns true if the quaternion is identity
  4900. */
  4901. Quaternion.IsIdentity = function (quaternion) {
  4902. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4903. };
  4904. /**
  4905. * Creates a quaternion from a rotation around an axis
  4906. * @param axis defines the axis to use
  4907. * @param angle defines the angle to use
  4908. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4909. */
  4910. Quaternion.RotationAxis = function (axis, angle) {
  4911. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4912. };
  4913. /**
  4914. * Creates a rotation around an axis and stores it into the given quaternion
  4915. * @param axis defines the axis to use
  4916. * @param angle defines the angle to use
  4917. * @param result defines the target quaternion
  4918. * @returns the target quaternion
  4919. */
  4920. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4921. var sin = Math.sin(angle / 2);
  4922. axis.normalize();
  4923. result.w = Math.cos(angle / 2);
  4924. result.x = axis.x * sin;
  4925. result.y = axis.y * sin;
  4926. result.z = axis.z * sin;
  4927. return result;
  4928. };
  4929. /**
  4930. * Creates a new quaternion from data stored into an array
  4931. * @param array defines the data source
  4932. * @param offset defines the offset in the source array where the data starts
  4933. * @returns a new quaternion
  4934. */
  4935. Quaternion.FromArray = function (array, offset) {
  4936. if (!offset) {
  4937. offset = 0;
  4938. }
  4939. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4940. };
  4941. /**
  4942. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4943. * @param yaw defines the rotation around Y axis
  4944. * @param pitch defines the rotation around X axis
  4945. * @param roll defines the rotation around Z axis
  4946. * @returns the new quaternion
  4947. */
  4948. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4949. var q = new Quaternion();
  4950. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4951. return q;
  4952. };
  4953. /**
  4954. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4955. * @param yaw defines the rotation around Y axis
  4956. * @param pitch defines the rotation around X axis
  4957. * @param roll defines the rotation around Z axis
  4958. * @param result defines the target quaternion
  4959. */
  4960. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4961. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4962. var halfRoll = roll * 0.5;
  4963. var halfPitch = pitch * 0.5;
  4964. var halfYaw = yaw * 0.5;
  4965. var sinRoll = Math.sin(halfRoll);
  4966. var cosRoll = Math.cos(halfRoll);
  4967. var sinPitch = Math.sin(halfPitch);
  4968. var cosPitch = Math.cos(halfPitch);
  4969. var sinYaw = Math.sin(halfYaw);
  4970. var cosYaw = Math.cos(halfYaw);
  4971. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4972. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4973. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4974. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4975. };
  4976. /**
  4977. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4978. * @param alpha defines the rotation around first axis
  4979. * @param beta defines the rotation around second axis
  4980. * @param gamma defines the rotation around third axis
  4981. * @returns the new quaternion
  4982. */
  4983. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4984. var result = new Quaternion();
  4985. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4986. return result;
  4987. };
  4988. /**
  4989. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4990. * @param alpha defines the rotation around first axis
  4991. * @param beta defines the rotation around second axis
  4992. * @param gamma defines the rotation around third axis
  4993. * @param result defines the target quaternion
  4994. */
  4995. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4996. // Produces a quaternion from Euler angles in the z-x-z orientation
  4997. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4998. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4999. var halfBeta = beta * 0.5;
  5000. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5001. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5002. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5003. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5004. };
  5005. /**
  5006. * 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)
  5007. * @param axis1 defines the first axis
  5008. * @param axis2 defines the second axis
  5009. * @param axis3 defines the third axis
  5010. * @returns the new quaternion
  5011. */
  5012. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5013. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5014. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5015. return quat;
  5016. };
  5017. /**
  5018. * 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
  5019. * @param axis1 defines the first axis
  5020. * @param axis2 defines the second axis
  5021. * @param axis3 defines the third axis
  5022. * @param ref defines the target quaternion
  5023. */
  5024. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5025. var rotMat = MathTmp.Matrix[0];
  5026. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5027. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5028. };
  5029. /**
  5030. * Interpolates between two quaternions
  5031. * @param left defines first quaternion
  5032. * @param right defines second quaternion
  5033. * @param amount defines the gradient to use
  5034. * @returns the new interpolated quaternion
  5035. */
  5036. Quaternion.Slerp = function (left, right, amount) {
  5037. var result = Quaternion.Identity();
  5038. Quaternion.SlerpToRef(left, right, amount, result);
  5039. return result;
  5040. };
  5041. /**
  5042. * Interpolates between two quaternions and stores it into a target quaternion
  5043. * @param left defines first quaternion
  5044. * @param right defines second quaternion
  5045. * @param amount defines the gradient to use
  5046. * @param result defines the target quaternion
  5047. */
  5048. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5049. var num2;
  5050. var num3;
  5051. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5052. var flag = false;
  5053. if (num4 < 0) {
  5054. flag = true;
  5055. num4 = -num4;
  5056. }
  5057. if (num4 > 0.999999) {
  5058. num3 = 1 - amount;
  5059. num2 = flag ? -amount : amount;
  5060. }
  5061. else {
  5062. var num5 = Math.acos(num4);
  5063. var num6 = (1.0 / Math.sin(num5));
  5064. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5065. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5066. }
  5067. result.x = (num3 * left.x) + (num2 * right.x);
  5068. result.y = (num3 * left.y) + (num2 * right.y);
  5069. result.z = (num3 * left.z) + (num2 * right.z);
  5070. result.w = (num3 * left.w) + (num2 * right.w);
  5071. };
  5072. /**
  5073. * Interpolate between two quaternions using Hermite interpolation
  5074. * @param value1 defines first quaternion
  5075. * @param tangent1 defines the incoming tangent
  5076. * @param value2 defines second quaternion
  5077. * @param tangent2 defines the outgoing tangent
  5078. * @param amount defines the target quaternion
  5079. * @returns the new interpolated quaternion
  5080. */
  5081. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5082. var squared = amount * amount;
  5083. var cubed = amount * squared;
  5084. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5085. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5086. var part3 = (cubed - (2.0 * squared)) + amount;
  5087. var part4 = cubed - squared;
  5088. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5089. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5090. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5091. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5092. return new Quaternion(x, y, z, w);
  5093. };
  5094. return Quaternion;
  5095. }());
  5096. BABYLON.Quaternion = Quaternion;
  5097. /**
  5098. * Class used to store matrix data (4x4)
  5099. */
  5100. var Matrix = /** @class */ (function () {
  5101. /**
  5102. * Creates an empty matrix (filled with zeros)
  5103. */
  5104. function Matrix() {
  5105. this._isIdentity = false;
  5106. this._isIdentityDirty = true;
  5107. /**
  5108. * Gets or sets the internal data of the matrix
  5109. */
  5110. this.m = new Float32Array(16);
  5111. this._markAsUpdated();
  5112. }
  5113. /** @hidden */
  5114. Matrix.prototype._markAsUpdated = function () {
  5115. this.updateFlag = Matrix._updateFlagSeed++;
  5116. this._isIdentityDirty = true;
  5117. };
  5118. // Properties
  5119. /**
  5120. * Check if the current matrix is indentity
  5121. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5122. * @returns true is the matrix is the identity matrix
  5123. */
  5124. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5125. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5126. if (this._isIdentityDirty) {
  5127. this._isIdentityDirty = false;
  5128. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5129. this._isIdentity = false;
  5130. }
  5131. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5132. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5133. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5134. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5135. this._isIdentity = false;
  5136. }
  5137. else {
  5138. this._isIdentity = true;
  5139. }
  5140. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5141. this._isIdentity = false;
  5142. }
  5143. }
  5144. return this._isIdentity;
  5145. };
  5146. /**
  5147. * Gets the determinant of the matrix
  5148. * @returns the matrix determinant
  5149. */
  5150. Matrix.prototype.determinant = function () {
  5151. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5152. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5153. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5154. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5155. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5156. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5157. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5158. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5159. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5160. };
  5161. // Methods
  5162. /**
  5163. * Returns the matrix as a Float32Array
  5164. * @returns the matrix underlying array
  5165. */
  5166. Matrix.prototype.toArray = function () {
  5167. return this.m;
  5168. };
  5169. /**
  5170. * Returns the matrix as a Float32Array
  5171. * @returns the matrix underlying array.
  5172. */
  5173. Matrix.prototype.asArray = function () {
  5174. return this.toArray();
  5175. };
  5176. /**
  5177. * Inverts the current matrix in place
  5178. * @returns the current inverted matrix
  5179. */
  5180. Matrix.prototype.invert = function () {
  5181. this.invertToRef(this);
  5182. return this;
  5183. };
  5184. /**
  5185. * Sets all the matrix elements to zero
  5186. * @returns the current matrix
  5187. */
  5188. Matrix.prototype.reset = function () {
  5189. for (var index = 0; index < 16; index++) {
  5190. this.m[index] = 0.0;
  5191. }
  5192. this._markAsUpdated();
  5193. return this;
  5194. };
  5195. /**
  5196. * Adds the current matrix with a second one
  5197. * @param other defines the matrix to add
  5198. * @returns a new matrix as the addition of the current matrix and the given one
  5199. */
  5200. Matrix.prototype.add = function (other) {
  5201. var result = new Matrix();
  5202. this.addToRef(other, result);
  5203. return result;
  5204. };
  5205. /**
  5206. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5207. * @param other defines the matrix to add
  5208. * @param result defines the target matrix
  5209. * @returns the current matrix
  5210. */
  5211. Matrix.prototype.addToRef = function (other, result) {
  5212. for (var index = 0; index < 16; index++) {
  5213. result.m[index] = this.m[index] + other.m[index];
  5214. }
  5215. result._markAsUpdated();
  5216. return this;
  5217. };
  5218. /**
  5219. * Adds in place the given matrix to the current matrix
  5220. * @param other defines the second operand
  5221. * @returns the current updated matrix
  5222. */
  5223. Matrix.prototype.addToSelf = function (other) {
  5224. for (var index = 0; index < 16; index++) {
  5225. this.m[index] += other.m[index];
  5226. }
  5227. this._markAsUpdated();
  5228. return this;
  5229. };
  5230. /**
  5231. * Sets the given matrix to the current inverted Matrix
  5232. * @param other defines the target matrix
  5233. * @returns the unmodified current matrix
  5234. */
  5235. Matrix.prototype.invertToRef = function (other) {
  5236. var l1 = this.m[0];
  5237. var l2 = this.m[1];
  5238. var l3 = this.m[2];
  5239. var l4 = this.m[3];
  5240. var l5 = this.m[4];
  5241. var l6 = this.m[5];
  5242. var l7 = this.m[6];
  5243. var l8 = this.m[7];
  5244. var l9 = this.m[8];
  5245. var l10 = this.m[9];
  5246. var l11 = this.m[10];
  5247. var l12 = this.m[11];
  5248. var l13 = this.m[12];
  5249. var l14 = this.m[13];
  5250. var l15 = this.m[14];
  5251. var l16 = this.m[15];
  5252. var l17 = (l11 * l16) - (l12 * l15);
  5253. var l18 = (l10 * l16) - (l12 * l14);
  5254. var l19 = (l10 * l15) - (l11 * l14);
  5255. var l20 = (l9 * l16) - (l12 * l13);
  5256. var l21 = (l9 * l15) - (l11 * l13);
  5257. var l22 = (l9 * l14) - (l10 * l13);
  5258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5263. var l28 = (l7 * l16) - (l8 * l15);
  5264. var l29 = (l6 * l16) - (l8 * l14);
  5265. var l30 = (l6 * l15) - (l7 * l14);
  5266. var l31 = (l5 * l16) - (l8 * l13);
  5267. var l32 = (l5 * l15) - (l7 * l13);
  5268. var l33 = (l5 * l14) - (l6 * l13);
  5269. var l34 = (l7 * l12) - (l8 * l11);
  5270. var l35 = (l6 * l12) - (l8 * l10);
  5271. var l36 = (l6 * l11) - (l7 * l10);
  5272. var l37 = (l5 * l12) - (l8 * l9);
  5273. var l38 = (l5 * l11) - (l7 * l9);
  5274. var l39 = (l5 * l10) - (l6 * l9);
  5275. other.m[0] = l23 * l27;
  5276. other.m[4] = l24 * l27;
  5277. other.m[8] = l25 * l27;
  5278. other.m[12] = l26 * l27;
  5279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5291. other._markAsUpdated();
  5292. return this;
  5293. };
  5294. /**
  5295. * Inserts the translation vector (using 3 floats) in the current matrix
  5296. * @param x defines the 1st component of the translation
  5297. * @param y defines the 2nd component of the translation
  5298. * @param z defines the 3rd component of the translation
  5299. * @returns the current updated matrix
  5300. */
  5301. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5302. this.m[12] = x;
  5303. this.m[13] = y;
  5304. this.m[14] = z;
  5305. this._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Inserts the translation vector in the current matrix
  5310. * @param vector3 defines the translation to insert
  5311. * @returns the current updated matrix
  5312. */
  5313. Matrix.prototype.setTranslation = function (vector3) {
  5314. this.m[12] = vector3.x;
  5315. this.m[13] = vector3.y;
  5316. this.m[14] = vector3.z;
  5317. this._markAsUpdated();
  5318. return this;
  5319. };
  5320. /**
  5321. * Gets the translation value of the current matrix
  5322. * @returns a new Vector3 as the extracted translation from the matrix
  5323. */
  5324. Matrix.prototype.getTranslation = function () {
  5325. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5326. };
  5327. /**
  5328. * Fill a Vector3 with the extracted translation from the matrix
  5329. * @param result defines the Vector3 where to store the translation
  5330. * @returns the current matrix
  5331. */
  5332. Matrix.prototype.getTranslationToRef = function (result) {
  5333. result.x = this.m[12];
  5334. result.y = this.m[13];
  5335. result.z = this.m[14];
  5336. return this;
  5337. };
  5338. /**
  5339. * Remove rotation and scaling part from the matrix
  5340. * @returns the updated matrix
  5341. */
  5342. Matrix.prototype.removeRotationAndScaling = function () {
  5343. this.setRowFromFloats(0, 1, 0, 0, 0);
  5344. this.setRowFromFloats(1, 0, 1, 0, 0);
  5345. this.setRowFromFloats(2, 0, 0, 1, 0);
  5346. return this;
  5347. };
  5348. /**
  5349. * Multiply two matrices
  5350. * @param other defines the second operand
  5351. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5352. */
  5353. Matrix.prototype.multiply = function (other) {
  5354. var result = new Matrix();
  5355. this.multiplyToRef(other, result);
  5356. return result;
  5357. };
  5358. /**
  5359. * Copy the current matrix from the given one
  5360. * @param other defines the source matrix
  5361. * @returns the current updated matrix
  5362. */
  5363. Matrix.prototype.copyFrom = function (other) {
  5364. for (var index = 0; index < 16; index++) {
  5365. this.m[index] = other.m[index];
  5366. }
  5367. this._markAsUpdated();
  5368. return this;
  5369. };
  5370. /**
  5371. * Populates the given array from the starting index with the current matrix values
  5372. * @param array defines the target array
  5373. * @param offset defines the offset in the target array where to start storing values
  5374. * @returns the current matrix
  5375. */
  5376. Matrix.prototype.copyToArray = function (array, offset) {
  5377. if (offset === void 0) { offset = 0; }
  5378. for (var index = 0; index < 16; index++) {
  5379. array[offset + index] = this.m[index];
  5380. }
  5381. return this;
  5382. };
  5383. /**
  5384. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5385. * @param other defines the second operand
  5386. * @param result defines the matrix where to store the multiplication
  5387. * @returns the current matrix
  5388. */
  5389. Matrix.prototype.multiplyToRef = function (other, result) {
  5390. this.multiplyToArray(other, result.m, 0);
  5391. result._markAsUpdated();
  5392. return this;
  5393. };
  5394. /**
  5395. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5396. * @param other defines the second operand
  5397. * @param result defines the array where to store the multiplication
  5398. * @param offset defines the offset in the target array where to start storing values
  5399. * @returns the current matrix
  5400. */
  5401. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5402. var tm0 = this.m[0];
  5403. var tm1 = this.m[1];
  5404. var tm2 = this.m[2];
  5405. var tm3 = this.m[3];
  5406. var tm4 = this.m[4];
  5407. var tm5 = this.m[5];
  5408. var tm6 = this.m[6];
  5409. var tm7 = this.m[7];
  5410. var tm8 = this.m[8];
  5411. var tm9 = this.m[9];
  5412. var tm10 = this.m[10];
  5413. var tm11 = this.m[11];
  5414. var tm12 = this.m[12];
  5415. var tm13 = this.m[13];
  5416. var tm14 = this.m[14];
  5417. var tm15 = this.m[15];
  5418. var om0 = other.m[0];
  5419. var om1 = other.m[1];
  5420. var om2 = other.m[2];
  5421. var om3 = other.m[3];
  5422. var om4 = other.m[4];
  5423. var om5 = other.m[5];
  5424. var om6 = other.m[6];
  5425. var om7 = other.m[7];
  5426. var om8 = other.m[8];
  5427. var om9 = other.m[9];
  5428. var om10 = other.m[10];
  5429. var om11 = other.m[11];
  5430. var om12 = other.m[12];
  5431. var om13 = other.m[13];
  5432. var om14 = other.m[14];
  5433. var om15 = other.m[15];
  5434. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5435. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5436. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5437. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5438. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5439. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5440. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5441. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5442. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5443. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5444. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5445. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5446. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5447. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5448. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5449. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5450. return this;
  5451. };
  5452. /**
  5453. * Check equality between this matrix and a second one
  5454. * @param value defines the second matrix to compare
  5455. * @returns true is the current matrix and the given one values are strictly equal
  5456. */
  5457. Matrix.prototype.equals = function (value) {
  5458. return value &&
  5459. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5460. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5461. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5462. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5463. };
  5464. /**
  5465. * Clone the current matrix
  5466. * @returns a new matrix from the current matrix
  5467. */
  5468. Matrix.prototype.clone = function () {
  5469. 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]);
  5470. };
  5471. /**
  5472. * Returns the name of the current matrix class
  5473. * @returns the string "Matrix"
  5474. */
  5475. Matrix.prototype.getClassName = function () {
  5476. return "Matrix";
  5477. };
  5478. /**
  5479. * Gets the hash code of the current matrix
  5480. * @returns the hash code
  5481. */
  5482. Matrix.prototype.getHashCode = function () {
  5483. var hash = this.m[0] || 0;
  5484. for (var i = 1; i < 16; i++) {
  5485. hash = (hash * 397) ^ (this.m[i] || 0);
  5486. }
  5487. return hash;
  5488. };
  5489. /**
  5490. * Decomposes the current Matrix into a translation, rotation and scaling components
  5491. * @param scale defines the scale vector3 given as a reference to update
  5492. * @param rotation defines the rotation quaternion given as a reference to update
  5493. * @param translation defines the translation vector3 given as a reference to update
  5494. * @returns true if operation was successful
  5495. */
  5496. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5497. if (translation) {
  5498. translation.x = this.m[12];
  5499. translation.y = this.m[13];
  5500. translation.z = this.m[14];
  5501. }
  5502. scale = scale || MathTmp.Vector3[0];
  5503. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5504. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5505. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5506. if (this.determinant() <= 0) {
  5507. scale.y *= -1;
  5508. }
  5509. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5510. if (rotation) {
  5511. rotation.x = 0;
  5512. rotation.y = 0;
  5513. rotation.z = 0;
  5514. rotation.w = 1;
  5515. }
  5516. return false;
  5517. }
  5518. if (rotation) {
  5519. 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]);
  5520. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5521. }
  5522. return true;
  5523. };
  5524. /**
  5525. * Gets specific row of the matrix
  5526. * @param index defines the number of the row to get
  5527. * @returns the index-th row of the current matrix as a new Vector4
  5528. */
  5529. Matrix.prototype.getRow = function (index) {
  5530. if (index < 0 || index > 3) {
  5531. return null;
  5532. }
  5533. var i = index * 4;
  5534. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5535. };
  5536. /**
  5537. * Sets the index-th row of the current matrix to the vector4 values
  5538. * @param index defines the number of the row to set
  5539. * @param row defines the target vector4
  5540. * @returns the updated current matrix
  5541. */
  5542. Matrix.prototype.setRow = function (index, row) {
  5543. if (index < 0 || index > 3) {
  5544. return this;
  5545. }
  5546. var i = index * 4;
  5547. this.m[i + 0] = row.x;
  5548. this.m[i + 1] = row.y;
  5549. this.m[i + 2] = row.z;
  5550. this.m[i + 3] = row.w;
  5551. this._markAsUpdated();
  5552. return this;
  5553. };
  5554. /**
  5555. * Compute the transpose of the matrix
  5556. * @returns the new transposed matrix
  5557. */
  5558. Matrix.prototype.transpose = function () {
  5559. return Matrix.Transpose(this);
  5560. };
  5561. /**
  5562. * Compute the transpose of the matrix and store it in a given matrix
  5563. * @param result defines the target matrix
  5564. * @returns the current matrix
  5565. */
  5566. Matrix.prototype.transposeToRef = function (result) {
  5567. Matrix.TransposeToRef(this, result);
  5568. return this;
  5569. };
  5570. /**
  5571. * Sets the index-th row of the current matrix with the given 4 x float values
  5572. * @param index defines the row index
  5573. * @param x defines the x component to set
  5574. * @param y defines the y component to set
  5575. * @param z defines the z component to set
  5576. * @param w defines the w component to set
  5577. * @returns the updated current matrix
  5578. */
  5579. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5580. if (index < 0 || index > 3) {
  5581. return this;
  5582. }
  5583. var i = index * 4;
  5584. this.m[i + 0] = x;
  5585. this.m[i + 1] = y;
  5586. this.m[i + 2] = z;
  5587. this.m[i + 3] = w;
  5588. this._markAsUpdated();
  5589. return this;
  5590. };
  5591. /**
  5592. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5593. * @param scale defines the scale factor
  5594. * @returns a new matrix
  5595. */
  5596. Matrix.prototype.scale = function (scale) {
  5597. var result = new Matrix();
  5598. this.scaleToRef(scale, result);
  5599. return result;
  5600. };
  5601. /**
  5602. * Scale the current matrix values by a factor to a given result matrix
  5603. * @param scale defines the scale factor
  5604. * @param result defines the matrix to store the result
  5605. * @returns the current matrix
  5606. */
  5607. Matrix.prototype.scaleToRef = function (scale, result) {
  5608. for (var index = 0; index < 16; index++) {
  5609. result.m[index] = this.m[index] * scale;
  5610. }
  5611. result._markAsUpdated();
  5612. return this;
  5613. };
  5614. /**
  5615. * Scale the current matrix values by a factor and add the result to a given matrix
  5616. * @param scale defines the scale factor
  5617. * @param result defines the Matrix to store the result
  5618. * @returns the current matrix
  5619. */
  5620. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] += this.m[index] * scale;
  5623. }
  5624. result._markAsUpdated();
  5625. return this;
  5626. };
  5627. /**
  5628. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5629. * @param ref matrix to store the result
  5630. */
  5631. Matrix.prototype.toNormalMatrix = function (ref) {
  5632. this.invertToRef(ref);
  5633. ref.transpose();
  5634. var m = ref.m;
  5635. 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);
  5636. };
  5637. /**
  5638. * Gets only rotation part of the current matrix
  5639. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5640. */
  5641. Matrix.prototype.getRotationMatrix = function () {
  5642. var result = Matrix.Identity();
  5643. this.getRotationMatrixToRef(result);
  5644. return result;
  5645. };
  5646. /**
  5647. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5648. * @param result defines the target matrix to store data to
  5649. * @returns the current matrix
  5650. */
  5651. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5652. var m = this.m;
  5653. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5654. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5655. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5656. if (this.determinant() <= 0) {
  5657. sy *= -1;
  5658. }
  5659. if (sx === 0 || sy === 0 || sz === 0) {
  5660. Matrix.IdentityToRef(result);
  5661. }
  5662. else {
  5663. 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);
  5664. }
  5665. return this;
  5666. };
  5667. // Statics
  5668. /**
  5669. * Creates a matrix from an array
  5670. * @param array defines the source array
  5671. * @param offset defines an offset in the source array
  5672. * @returns a new Matrix set from the starting index of the given array
  5673. */
  5674. Matrix.FromArray = function (array, offset) {
  5675. var result = new Matrix();
  5676. if (!offset) {
  5677. offset = 0;
  5678. }
  5679. Matrix.FromArrayToRef(array, offset, result);
  5680. return result;
  5681. };
  5682. /**
  5683. * Copy the content of an array into a given matrix
  5684. * @param array defines the source array
  5685. * @param offset defines an offset in the source array
  5686. * @param result defines the target matrix
  5687. */
  5688. Matrix.FromArrayToRef = function (array, offset, result) {
  5689. for (var index = 0; index < 16; index++) {
  5690. result.m[index] = array[index + offset];
  5691. }
  5692. result._markAsUpdated();
  5693. };
  5694. /**
  5695. * Stores an array into a matrix after having multiplied each component by a given factor
  5696. * @param array defines the source array
  5697. * @param offset defines the offset in the source array
  5698. * @param scale defines the scaling factor
  5699. * @param result defines the target matrix
  5700. */
  5701. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5702. for (var index = 0; index < 16; index++) {
  5703. result.m[index] = array[index + offset] * scale;
  5704. }
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Stores a list of values (16) inside a given matrix
  5709. * @param initialM11 defines 1st value of 1st row
  5710. * @param initialM12 defines 2nd value of 1st row
  5711. * @param initialM13 defines 3rd value of 1st row
  5712. * @param initialM14 defines 4th value of 1st row
  5713. * @param initialM21 defines 1st value of 2nd row
  5714. * @param initialM22 defines 2nd value of 2nd row
  5715. * @param initialM23 defines 3rd value of 2nd row
  5716. * @param initialM24 defines 4th value of 2nd row
  5717. * @param initialM31 defines 1st value of 3rd row
  5718. * @param initialM32 defines 2nd value of 3rd row
  5719. * @param initialM33 defines 3rd value of 3rd row
  5720. * @param initialM34 defines 4th value of 3rd row
  5721. * @param initialM41 defines 1st value of 4th row
  5722. * @param initialM42 defines 2nd value of 4th row
  5723. * @param initialM43 defines 3rd value of 4th row
  5724. * @param initialM44 defines 4th value of 4th row
  5725. * @param result defines the target matrix
  5726. */
  5727. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5728. result.m[0] = initialM11;
  5729. result.m[1] = initialM12;
  5730. result.m[2] = initialM13;
  5731. result.m[3] = initialM14;
  5732. result.m[4] = initialM21;
  5733. result.m[5] = initialM22;
  5734. result.m[6] = initialM23;
  5735. result.m[7] = initialM24;
  5736. result.m[8] = initialM31;
  5737. result.m[9] = initialM32;
  5738. result.m[10] = initialM33;
  5739. result.m[11] = initialM34;
  5740. result.m[12] = initialM41;
  5741. result.m[13] = initialM42;
  5742. result.m[14] = initialM43;
  5743. result.m[15] = initialM44;
  5744. result._markAsUpdated();
  5745. };
  5746. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5747. /**
  5748. * Gets an identity matrix that must not be updated
  5749. */
  5750. get: function () {
  5751. return Matrix._identityReadOnly;
  5752. },
  5753. enumerable: true,
  5754. configurable: true
  5755. });
  5756. /**
  5757. * Creates new matrix from a list of values (16)
  5758. * @param initialM11 defines 1st value of 1st row
  5759. * @param initialM12 defines 2nd value of 1st row
  5760. * @param initialM13 defines 3rd value of 1st row
  5761. * @param initialM14 defines 4th value of 1st row
  5762. * @param initialM21 defines 1st value of 2nd row
  5763. * @param initialM22 defines 2nd value of 2nd row
  5764. * @param initialM23 defines 3rd value of 2nd row
  5765. * @param initialM24 defines 4th value of 2nd row
  5766. * @param initialM31 defines 1st value of 3rd row
  5767. * @param initialM32 defines 2nd value of 3rd row
  5768. * @param initialM33 defines 3rd value of 3rd row
  5769. * @param initialM34 defines 4th value of 3rd row
  5770. * @param initialM41 defines 1st value of 4th row
  5771. * @param initialM42 defines 2nd value of 4th row
  5772. * @param initialM43 defines 3rd value of 4th row
  5773. * @param initialM44 defines 4th value of 4th row
  5774. * @returns the new matrix
  5775. */
  5776. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5777. var result = new Matrix();
  5778. result.m[0] = initialM11;
  5779. result.m[1] = initialM12;
  5780. result.m[2] = initialM13;
  5781. result.m[3] = initialM14;
  5782. result.m[4] = initialM21;
  5783. result.m[5] = initialM22;
  5784. result.m[6] = initialM23;
  5785. result.m[7] = initialM24;
  5786. result.m[8] = initialM31;
  5787. result.m[9] = initialM32;
  5788. result.m[10] = initialM33;
  5789. result.m[11] = initialM34;
  5790. result.m[12] = initialM41;
  5791. result.m[13] = initialM42;
  5792. result.m[14] = initialM43;
  5793. result.m[15] = initialM44;
  5794. return result;
  5795. };
  5796. /**
  5797. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5798. * @param scale defines the scale vector3
  5799. * @param rotation defines the rotation quaternion
  5800. * @param translation defines the translation vector3
  5801. * @returns a new matrix
  5802. */
  5803. Matrix.Compose = function (scale, rotation, translation) {
  5804. var result = Matrix.Identity();
  5805. Matrix.ComposeToRef(scale, rotation, translation, result);
  5806. return result;
  5807. };
  5808. /**
  5809. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5810. * @param scale defines the scale vector3
  5811. * @param rotation defines the rotation quaternion
  5812. * @param translation defines the translation vector3
  5813. * @param result defines the target matrix
  5814. */
  5815. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5816. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5817. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5818. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5819. result.setTranslation(translation);
  5820. };
  5821. /**
  5822. * Creates a new identity matrix
  5823. * @returns a new identity matrix
  5824. */
  5825. Matrix.Identity = function () {
  5826. 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);
  5827. };
  5828. /**
  5829. * Creates a new identity matrix and stores the result in a given matrix
  5830. * @param result defines the target matrix
  5831. */
  5832. Matrix.IdentityToRef = function (result) {
  5833. 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);
  5834. };
  5835. /**
  5836. * Creates a new zero matrix
  5837. * @returns a new zero matrix
  5838. */
  5839. Matrix.Zero = function () {
  5840. 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);
  5841. };
  5842. /**
  5843. * Creates a new rotation matrix for "angle" radians around the X axis
  5844. * @param angle defines the angle (in radians) to use
  5845. * @return the new matrix
  5846. */
  5847. Matrix.RotationX = function (angle) {
  5848. var result = new Matrix();
  5849. Matrix.RotationXToRef(angle, result);
  5850. return result;
  5851. };
  5852. /**
  5853. * Creates a new matrix as the invert of a given matrix
  5854. * @param source defines the source matrix
  5855. * @returns the new matrix
  5856. */
  5857. Matrix.Invert = function (source) {
  5858. var result = new Matrix();
  5859. source.invertToRef(result);
  5860. return result;
  5861. };
  5862. /**
  5863. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5864. * @param angle defines the angle (in radians) to use
  5865. * @param result defines the target matrix
  5866. */
  5867. Matrix.RotationXToRef = function (angle, result) {
  5868. var s = Math.sin(angle);
  5869. var c = Math.cos(angle);
  5870. result.m[0] = 1.0;
  5871. result.m[15] = 1.0;
  5872. result.m[5] = c;
  5873. result.m[10] = c;
  5874. result.m[9] = -s;
  5875. result.m[6] = s;
  5876. result.m[1] = 0.0;
  5877. result.m[2] = 0.0;
  5878. result.m[3] = 0.0;
  5879. result.m[4] = 0.0;
  5880. result.m[7] = 0.0;
  5881. result.m[8] = 0.0;
  5882. result.m[11] = 0.0;
  5883. result.m[12] = 0.0;
  5884. result.m[13] = 0.0;
  5885. result.m[14] = 0.0;
  5886. result._markAsUpdated();
  5887. };
  5888. /**
  5889. * Creates a new rotation matrix for "angle" radians around the Y axis
  5890. * @param angle defines the angle (in radians) to use
  5891. * @return the new matrix
  5892. */
  5893. Matrix.RotationY = function (angle) {
  5894. var result = new Matrix();
  5895. Matrix.RotationYToRef(angle, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5900. * @param angle defines the angle (in radians) to use
  5901. * @param result defines the target matrix
  5902. */
  5903. Matrix.RotationYToRef = function (angle, result) {
  5904. var s = Math.sin(angle);
  5905. var c = Math.cos(angle);
  5906. result.m[5] = 1.0;
  5907. result.m[15] = 1.0;
  5908. result.m[0] = c;
  5909. result.m[2] = -s;
  5910. result.m[8] = s;
  5911. result.m[10] = c;
  5912. result.m[1] = 0.0;
  5913. result.m[3] = 0.0;
  5914. result.m[4] = 0.0;
  5915. result.m[6] = 0.0;
  5916. result.m[7] = 0.0;
  5917. result.m[9] = 0.0;
  5918. result.m[11] = 0.0;
  5919. result.m[12] = 0.0;
  5920. result.m[13] = 0.0;
  5921. result.m[14] = 0.0;
  5922. result._markAsUpdated();
  5923. };
  5924. /**
  5925. * Creates a new rotation matrix for "angle" radians around the Z axis
  5926. * @param angle defines the angle (in radians) to use
  5927. * @return the new matrix
  5928. */
  5929. Matrix.RotationZ = function (angle) {
  5930. var result = new Matrix();
  5931. Matrix.RotationZToRef(angle, result);
  5932. return result;
  5933. };
  5934. /**
  5935. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5936. * @param angle defines the angle (in radians) to use
  5937. * @param result defines the target matrix
  5938. */
  5939. Matrix.RotationZToRef = function (angle, result) {
  5940. var s = Math.sin(angle);
  5941. var c = Math.cos(angle);
  5942. result.m[10] = 1.0;
  5943. result.m[15] = 1.0;
  5944. result.m[0] = c;
  5945. result.m[1] = s;
  5946. result.m[4] = -s;
  5947. result.m[5] = c;
  5948. result.m[2] = 0.0;
  5949. result.m[3] = 0.0;
  5950. result.m[6] = 0.0;
  5951. result.m[7] = 0.0;
  5952. result.m[8] = 0.0;
  5953. result.m[9] = 0.0;
  5954. result.m[11] = 0.0;
  5955. result.m[12] = 0.0;
  5956. result.m[13] = 0.0;
  5957. result.m[14] = 0.0;
  5958. result._markAsUpdated();
  5959. };
  5960. /**
  5961. * Creates a new rotation matrix for "angle" radians around the given axis
  5962. * @param axis defines the axis to use
  5963. * @param angle defines the angle (in radians) to use
  5964. * @return the new matrix
  5965. */
  5966. Matrix.RotationAxis = function (axis, angle) {
  5967. var result = Matrix.Zero();
  5968. Matrix.RotationAxisToRef(axis, angle, result);
  5969. return result;
  5970. };
  5971. /**
  5972. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5973. * @param axis defines the axis to use
  5974. * @param angle defines the angle (in radians) to use
  5975. * @param result defines the target matrix
  5976. */
  5977. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5978. var s = Math.sin(-angle);
  5979. var c = Math.cos(-angle);
  5980. var c1 = 1 - c;
  5981. axis.normalize();
  5982. result.m[0] = (axis.x * axis.x) * c1 + c;
  5983. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5984. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5985. result.m[3] = 0.0;
  5986. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5987. result.m[5] = (axis.y * axis.y) * c1 + c;
  5988. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5989. result.m[7] = 0.0;
  5990. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5991. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5992. result.m[10] = (axis.z * axis.z) * c1 + c;
  5993. result.m[11] = 0.0;
  5994. result.m[15] = 1.0;
  5995. result._markAsUpdated();
  5996. };
  5997. /**
  5998. * Creates a rotation matrix
  5999. * @param yaw defines the yaw angle in radians (Y axis)
  6000. * @param pitch defines the pitch angle in radians (X axis)
  6001. * @param roll defines the roll angle in radians (X axis)
  6002. * @returns the new rotation matrix
  6003. */
  6004. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6005. var result = new Matrix();
  6006. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6007. return result;
  6008. };
  6009. /**
  6010. * Creates a rotation matrix and stores it in a given matrix
  6011. * @param yaw defines the yaw angle in radians (Y axis)
  6012. * @param pitch defines the pitch angle in radians (X axis)
  6013. * @param roll defines the roll angle in radians (X axis)
  6014. * @param result defines the target matrix
  6015. */
  6016. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6017. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6018. this._tempQuaternion.toRotationMatrix(result);
  6019. };
  6020. /**
  6021. * Creates a scaling matrix
  6022. * @param x defines the scale factor on X axis
  6023. * @param y defines the scale factor on Y axis
  6024. * @param z defines the scale factor on Z axis
  6025. * @returns the new matrix
  6026. */
  6027. Matrix.Scaling = function (x, y, z) {
  6028. var result = Matrix.Zero();
  6029. Matrix.ScalingToRef(x, y, z, result);
  6030. return result;
  6031. };
  6032. /**
  6033. * Creates a scaling matrix and stores it in a given matrix
  6034. * @param x defines the scale factor on X axis
  6035. * @param y defines the scale factor on Y axis
  6036. * @param z defines the scale factor on Z axis
  6037. * @param result defines the target matrix
  6038. */
  6039. Matrix.ScalingToRef = function (x, y, z, result) {
  6040. result.m[0] = x;
  6041. result.m[1] = 0.0;
  6042. result.m[2] = 0.0;
  6043. result.m[3] = 0.0;
  6044. result.m[4] = 0.0;
  6045. result.m[5] = y;
  6046. result.m[6] = 0.0;
  6047. result.m[7] = 0.0;
  6048. result.m[8] = 0.0;
  6049. result.m[9] = 0.0;
  6050. result.m[10] = z;
  6051. result.m[11] = 0.0;
  6052. result.m[12] = 0.0;
  6053. result.m[13] = 0.0;
  6054. result.m[14] = 0.0;
  6055. result.m[15] = 1.0;
  6056. result._markAsUpdated();
  6057. };
  6058. /**
  6059. * Creates a translation matrix
  6060. * @param x defines the translation on X axis
  6061. * @param y defines the translation on Y axis
  6062. * @param z defines the translationon Z axis
  6063. * @returns the new matrix
  6064. */
  6065. Matrix.Translation = function (x, y, z) {
  6066. var result = Matrix.Identity();
  6067. Matrix.TranslationToRef(x, y, z, result);
  6068. return result;
  6069. };
  6070. /**
  6071. * Creates a translation matrix and stores it in a given matrix
  6072. * @param x defines the translation on X axis
  6073. * @param y defines the translation on Y axis
  6074. * @param z defines the translationon Z axis
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.TranslationToRef = function (x, y, z, result) {
  6078. 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);
  6079. };
  6080. /**
  6081. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6082. * @param startValue defines the start value
  6083. * @param endValue defines the end value
  6084. * @param gradient defines the gradient factor
  6085. * @returns the new matrix
  6086. */
  6087. Matrix.Lerp = function (startValue, endValue, gradient) {
  6088. var result = Matrix.Zero();
  6089. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6090. return result;
  6091. };
  6092. /**
  6093. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6094. * @param startValue defines the start value
  6095. * @param endValue defines the end value
  6096. * @param gradient defines the gradient factor
  6097. * @param result defines the Matrix object where to store data
  6098. */
  6099. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6100. for (var index = 0; index < 16; index++) {
  6101. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6102. }
  6103. result._markAsUpdated();
  6104. };
  6105. /**
  6106. * Builds a new matrix whose values are computed by:
  6107. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6108. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6109. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6110. * @param startValue defines the first matrix
  6111. * @param endValue defines the second matrix
  6112. * @param gradient defines the gradient between the two matrices
  6113. * @returns the new matrix
  6114. */
  6115. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6116. var result = Matrix.Zero();
  6117. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6118. return result;
  6119. };
  6120. /**
  6121. * Update a matrix to values which are computed by:
  6122. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6123. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6124. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6125. * @param startValue defines the first matrix
  6126. * @param endValue defines the second matrix
  6127. * @param gradient defines the gradient between the two matrices
  6128. * @param result defines the target matrix
  6129. */
  6130. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6131. var startScale = MathTmp.Vector3[0];
  6132. var startRotation = MathTmp.Quaternion[0];
  6133. var startTranslation = MathTmp.Vector3[1];
  6134. startValue.decompose(startScale, startRotation, startTranslation);
  6135. var endScale = MathTmp.Vector3[2];
  6136. var endRotation = MathTmp.Quaternion[1];
  6137. var endTranslation = MathTmp.Vector3[3];
  6138. endValue.decompose(endScale, endRotation, endTranslation);
  6139. var resultScale = MathTmp.Vector3[4];
  6140. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6141. var resultRotation = MathTmp.Quaternion[2];
  6142. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6143. var resultTranslation = MathTmp.Vector3[5];
  6144. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6145. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6146. };
  6147. /**
  6148. * 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"
  6149. * This function works in left handed mode
  6150. * @param eye defines the final position of the entity
  6151. * @param target defines where the entity should look at
  6152. * @param up defines the up vector for the entity
  6153. * @returns the new matrix
  6154. */
  6155. Matrix.LookAtLH = function (eye, target, up) {
  6156. var result = Matrix.Zero();
  6157. Matrix.LookAtLHToRef(eye, target, up, result);
  6158. return result;
  6159. };
  6160. /**
  6161. * 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".
  6162. * This function works in left handed mode
  6163. * @param eye defines the final position of the entity
  6164. * @param target defines where the entity should look at
  6165. * @param up defines the up vector for the entity
  6166. * @param result defines the target matrix
  6167. */
  6168. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6169. // Z axis
  6170. target.subtractToRef(eye, this._zAxis);
  6171. this._zAxis.normalize();
  6172. // X axis
  6173. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6174. if (this._xAxis.lengthSquared() === 0) {
  6175. this._xAxis.x = 1.0;
  6176. }
  6177. else {
  6178. this._xAxis.normalize();
  6179. }
  6180. // Y axis
  6181. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6182. this._yAxis.normalize();
  6183. // Eye angles
  6184. var ex = -Vector3.Dot(this._xAxis, eye);
  6185. var ey = -Vector3.Dot(this._yAxis, eye);
  6186. var ez = -Vector3.Dot(this._zAxis, eye);
  6187. 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);
  6188. };
  6189. /**
  6190. * 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"
  6191. * This function works in right handed mode
  6192. * @param eye defines the final position of the entity
  6193. * @param target defines where the entity should look at
  6194. * @param up defines the up vector for the entity
  6195. * @returns the new matrix
  6196. */
  6197. Matrix.LookAtRH = function (eye, target, up) {
  6198. var result = Matrix.Zero();
  6199. Matrix.LookAtRHToRef(eye, target, up, result);
  6200. return result;
  6201. };
  6202. /**
  6203. * 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".
  6204. * This function works in right handed mode
  6205. * @param eye defines the final position of the entity
  6206. * @param target defines where the entity should look at
  6207. * @param up defines the up vector for the entity
  6208. * @param result defines the target matrix
  6209. */
  6210. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6211. // Z axis
  6212. eye.subtractToRef(target, this._zAxis);
  6213. this._zAxis.normalize();
  6214. // X axis
  6215. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6216. if (this._xAxis.lengthSquared() === 0) {
  6217. this._xAxis.x = 1.0;
  6218. }
  6219. else {
  6220. this._xAxis.normalize();
  6221. }
  6222. // Y axis
  6223. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6224. this._yAxis.normalize();
  6225. // Eye angles
  6226. var ex = -Vector3.Dot(this._xAxis, eye);
  6227. var ey = -Vector3.Dot(this._yAxis, eye);
  6228. var ez = -Vector3.Dot(this._zAxis, eye);
  6229. 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);
  6230. };
  6231. /**
  6232. * Create a left-handed orthographic projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed orthographic projection matrix
  6238. */
  6239. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6242. return matrix;
  6243. };
  6244. /**
  6245. * Store a left-handed orthographic projection to a given matrix
  6246. * @param width defines the viewport width
  6247. * @param height defines the viewport height
  6248. * @param znear defines the near clip plane
  6249. * @param zfar defines the far clip plane
  6250. * @param result defines the target matrix
  6251. */
  6252. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6253. var n = znear;
  6254. var f = zfar;
  6255. var a = 2.0 / width;
  6256. var b = 2.0 / height;
  6257. var c = 2.0 / (f - n);
  6258. var d = -(f + n) / (f - n);
  6259. 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);
  6260. };
  6261. /**
  6262. * Create a left-handed orthographic projection matrix
  6263. * @param left defines the viewport left coordinate
  6264. * @param right defines the viewport right coordinate
  6265. * @param bottom defines the viewport bottom coordinate
  6266. * @param top defines the viewport top coordinate
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @returns a new matrix as a left-handed orthographic projection matrix
  6270. */
  6271. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6272. var matrix = Matrix.Zero();
  6273. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6274. return matrix;
  6275. };
  6276. /**
  6277. * Stores a left-handed orthographic projection into a given matrix
  6278. * @param left defines the viewport left coordinate
  6279. * @param right defines the viewport right coordinate
  6280. * @param bottom defines the viewport bottom coordinate
  6281. * @param top defines the viewport top coordinate
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @param result defines the target matrix
  6285. */
  6286. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6287. var n = znear;
  6288. var f = zfar;
  6289. var a = 2.0 / (right - left);
  6290. var b = 2.0 / (top - bottom);
  6291. var c = 2.0 / (f - n);
  6292. var d = -(f + n) / (f - n);
  6293. var i0 = (left + right) / (left - right);
  6294. var i1 = (top + bottom) / (bottom - top);
  6295. 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);
  6296. };
  6297. /**
  6298. * Creates a right-handed orthographic projection matrix
  6299. * @param left defines the viewport left coordinate
  6300. * @param right defines the viewport right coordinate
  6301. * @param bottom defines the viewport bottom coordinate
  6302. * @param top defines the viewport top coordinate
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @returns a new matrix as a right-handed orthographic projection matrix
  6306. */
  6307. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6308. var matrix = Matrix.Zero();
  6309. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6310. return matrix;
  6311. };
  6312. /**
  6313. * Stores a right-handed orthographic projection into a given matrix
  6314. * @param left defines the viewport left coordinate
  6315. * @param right defines the viewport right coordinate
  6316. * @param bottom defines the viewport bottom coordinate
  6317. * @param top defines the viewport top coordinate
  6318. * @param znear defines the near clip plane
  6319. * @param zfar defines the far clip plane
  6320. * @param result defines the target matrix
  6321. */
  6322. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6323. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6324. result.m[10] *= -1.0;
  6325. };
  6326. /**
  6327. * Creates a left-handed perspective projection matrix
  6328. * @param width defines the viewport width
  6329. * @param height defines the viewport height
  6330. * @param znear defines the near clip plane
  6331. * @param zfar defines the far clip plane
  6332. * @returns a new matrix as a left-handed perspective projection matrix
  6333. */
  6334. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6335. var matrix = Matrix.Zero();
  6336. var n = znear;
  6337. var f = zfar;
  6338. var a = 2.0 * n / width;
  6339. var b = 2.0 * n / height;
  6340. var c = (f + n) / (f - n);
  6341. var d = -2.0 * f * n / (f - n);
  6342. 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);
  6343. return matrix;
  6344. };
  6345. /**
  6346. * Creates a left-handed perspective projection matrix
  6347. * @param fov defines the horizontal field of view
  6348. * @param aspect defines the aspect ratio
  6349. * @param znear defines the near clip plane
  6350. * @param zfar defines the far clip plane
  6351. * @returns a new matrix as a left-handed perspective projection matrix
  6352. */
  6353. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6354. var matrix = Matrix.Zero();
  6355. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6356. return matrix;
  6357. };
  6358. /**
  6359. * Stores a left-handed perspective projection into a given matrix
  6360. * @param fov defines the horizontal field of view
  6361. * @param aspect defines the aspect ratio
  6362. * @param znear defines the near clip plane
  6363. * @param zfar defines the far clip plane
  6364. * @param result defines the target matrix
  6365. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6366. */
  6367. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6368. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6369. var n = znear;
  6370. var f = zfar;
  6371. var t = 1.0 / (Math.tan(fov * 0.5));
  6372. var a = isVerticalFovFixed ? (t / aspect) : t;
  6373. var b = isVerticalFovFixed ? t : (t * aspect);
  6374. var c = (f + n) / (f - n);
  6375. var d = -2.0 * f * n / (f - n);
  6376. 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);
  6377. };
  6378. /**
  6379. * Creates a right-handed perspective projection matrix
  6380. * @param fov defines the horizontal field of view
  6381. * @param aspect defines the aspect ratio
  6382. * @param znear defines the near clip plane
  6383. * @param zfar defines the far clip plane
  6384. * @returns a new matrix as a right-handed perspective projection matrix
  6385. */
  6386. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6387. var matrix = Matrix.Zero();
  6388. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6389. return matrix;
  6390. };
  6391. /**
  6392. * Stores a right-handed perspective projection into a given matrix
  6393. * @param fov defines the horizontal field of view
  6394. * @param aspect defines the aspect ratio
  6395. * @param znear defines the near clip plane
  6396. * @param zfar defines the far clip plane
  6397. * @param result defines the target matrix
  6398. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6399. */
  6400. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6401. //alternatively this could be expressed as:
  6402. // m = PerspectiveFovLHToRef
  6403. // m[10] *= -1.0;
  6404. // m[11] *= -1.0;
  6405. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6406. var n = znear;
  6407. var f = zfar;
  6408. var t = 1.0 / (Math.tan(fov * 0.5));
  6409. var a = isVerticalFovFixed ? (t / aspect) : t;
  6410. var b = isVerticalFovFixed ? t : (t * aspect);
  6411. var c = -(f + n) / (f - n);
  6412. var d = -2 * f * n / (f - n);
  6413. 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);
  6414. };
  6415. /**
  6416. * Stores a perspective projection for WebVR info a given matrix
  6417. * @param fov defines the field of view
  6418. * @param znear defines the near clip plane
  6419. * @param zfar defines the far clip plane
  6420. * @param result defines the target matrix
  6421. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6422. */
  6423. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6424. if (rightHanded === void 0) { rightHanded = false; }
  6425. var rightHandedFactor = rightHanded ? -1 : 1;
  6426. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6427. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6428. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6429. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6430. var xScale = 2.0 / (leftTan + rightTan);
  6431. var yScale = 2.0 / (upTan + downTan);
  6432. result.m[0] = xScale;
  6433. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6434. result.m[5] = yScale;
  6435. result.m[6] = result.m[7] = 0.0;
  6436. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6437. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6438. result.m[10] = -zfar / (znear - zfar);
  6439. result.m[11] = 1.0 * rightHandedFactor;
  6440. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6441. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6442. result._markAsUpdated();
  6443. };
  6444. /**
  6445. * Computes a complete transformation matrix
  6446. * @param viewport defines the viewport to use
  6447. * @param world defines the world matrix
  6448. * @param view defines the view matrix
  6449. * @param projection defines the projection matrix
  6450. * @param zmin defines the near clip plane
  6451. * @param zmax defines the far clip plane
  6452. * @returns the transformation matrix
  6453. */
  6454. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6455. var cw = viewport.width;
  6456. var ch = viewport.height;
  6457. var cx = viewport.x;
  6458. var cy = viewport.y;
  6459. 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);
  6460. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6461. };
  6462. /**
  6463. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6464. * @param matrix defines the matrix to use
  6465. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6466. */
  6467. Matrix.GetAsMatrix2x2 = function (matrix) {
  6468. return new Float32Array([
  6469. matrix.m[0], matrix.m[1],
  6470. matrix.m[4], matrix.m[5]
  6471. ]);
  6472. };
  6473. /**
  6474. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6475. * @param matrix defines the matrix to use
  6476. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6477. */
  6478. Matrix.GetAsMatrix3x3 = function (matrix) {
  6479. return new Float32Array([
  6480. matrix.m[0], matrix.m[1], matrix.m[2],
  6481. matrix.m[4], matrix.m[5], matrix.m[6],
  6482. matrix.m[8], matrix.m[9], matrix.m[10]
  6483. ]);
  6484. };
  6485. /**
  6486. * Compute the transpose of a given matrix
  6487. * @param matrix defines the matrix to transpose
  6488. * @returns the new matrix
  6489. */
  6490. Matrix.Transpose = function (matrix) {
  6491. var result = new Matrix();
  6492. Matrix.TransposeToRef(matrix, result);
  6493. return result;
  6494. };
  6495. /**
  6496. * Compute the transpose of a matrix and store it in a target matrix
  6497. * @param matrix defines the matrix to transpose
  6498. * @param result defines the target matrix
  6499. */
  6500. Matrix.TransposeToRef = function (matrix, result) {
  6501. result.m[0] = matrix.m[0];
  6502. result.m[1] = matrix.m[4];
  6503. result.m[2] = matrix.m[8];
  6504. result.m[3] = matrix.m[12];
  6505. result.m[4] = matrix.m[1];
  6506. result.m[5] = matrix.m[5];
  6507. result.m[6] = matrix.m[9];
  6508. result.m[7] = matrix.m[13];
  6509. result.m[8] = matrix.m[2];
  6510. result.m[9] = matrix.m[6];
  6511. result.m[10] = matrix.m[10];
  6512. result.m[11] = matrix.m[14];
  6513. result.m[12] = matrix.m[3];
  6514. result.m[13] = matrix.m[7];
  6515. result.m[14] = matrix.m[11];
  6516. result.m[15] = matrix.m[15];
  6517. };
  6518. /**
  6519. * Computes a reflection matrix from a plane
  6520. * @param plane defines the reflection plane
  6521. * @returns a new matrix
  6522. */
  6523. Matrix.Reflection = function (plane) {
  6524. var matrix = new Matrix();
  6525. Matrix.ReflectionToRef(plane, matrix);
  6526. return matrix;
  6527. };
  6528. /**
  6529. * Computes a reflection matrix from a plane
  6530. * @param plane defines the reflection plane
  6531. * @param result defines the target matrix
  6532. */
  6533. Matrix.ReflectionToRef = function (plane, result) {
  6534. plane.normalize();
  6535. var x = plane.normal.x;
  6536. var y = plane.normal.y;
  6537. var z = plane.normal.z;
  6538. var temp = -2 * x;
  6539. var temp2 = -2 * y;
  6540. var temp3 = -2 * z;
  6541. result.m[0] = (temp * x) + 1;
  6542. result.m[1] = temp2 * x;
  6543. result.m[2] = temp3 * x;
  6544. result.m[3] = 0.0;
  6545. result.m[4] = temp * y;
  6546. result.m[5] = (temp2 * y) + 1;
  6547. result.m[6] = temp3 * y;
  6548. result.m[7] = 0.0;
  6549. result.m[8] = temp * z;
  6550. result.m[9] = temp2 * z;
  6551. result.m[10] = (temp3 * z) + 1;
  6552. result.m[11] = 0.0;
  6553. result.m[12] = temp * plane.d;
  6554. result.m[13] = temp2 * plane.d;
  6555. result.m[14] = temp3 * plane.d;
  6556. result.m[15] = 1.0;
  6557. result._markAsUpdated();
  6558. };
  6559. /**
  6560. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6561. * @param xaxis defines the value of the 1st axis
  6562. * @param yaxis defines the value of the 2nd axis
  6563. * @param zaxis defines the value of the 3rd axis
  6564. * @param result defines the target matrix
  6565. */
  6566. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6567. result.m[0] = xaxis.x;
  6568. result.m[1] = xaxis.y;
  6569. result.m[2] = xaxis.z;
  6570. result.m[3] = 0.0;
  6571. result.m[4] = yaxis.x;
  6572. result.m[5] = yaxis.y;
  6573. result.m[6] = yaxis.z;
  6574. result.m[7] = 0.0;
  6575. result.m[8] = zaxis.x;
  6576. result.m[9] = zaxis.y;
  6577. result.m[10] = zaxis.z;
  6578. result.m[11] = 0.0;
  6579. result.m[12] = 0.0;
  6580. result.m[13] = 0.0;
  6581. result.m[14] = 0.0;
  6582. result.m[15] = 1.0;
  6583. result._markAsUpdated();
  6584. };
  6585. /**
  6586. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6587. * @param quat defines the quaternion to use
  6588. * @param result defines the target matrix
  6589. */
  6590. Matrix.FromQuaternionToRef = function (quat, result) {
  6591. var xx = quat.x * quat.x;
  6592. var yy = quat.y * quat.y;
  6593. var zz = quat.z * quat.z;
  6594. var xy = quat.x * quat.y;
  6595. var zw = quat.z * quat.w;
  6596. var zx = quat.z * quat.x;
  6597. var yw = quat.y * quat.w;
  6598. var yz = quat.y * quat.z;
  6599. var xw = quat.x * quat.w;
  6600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6601. result.m[1] = 2.0 * (xy + zw);
  6602. result.m[2] = 2.0 * (zx - yw);
  6603. result.m[3] = 0.0;
  6604. result.m[4] = 2.0 * (xy - zw);
  6605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6606. result.m[6] = 2.0 * (yz + xw);
  6607. result.m[7] = 0.0;
  6608. result.m[8] = 2.0 * (zx + yw);
  6609. result.m[9] = 2.0 * (yz - xw);
  6610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6611. result.m[11] = 0.0;
  6612. result.m[12] = 0.0;
  6613. result.m[13] = 0.0;
  6614. result.m[14] = 0.0;
  6615. result.m[15] = 1.0;
  6616. result._markAsUpdated();
  6617. };
  6618. Matrix._tempQuaternion = new Quaternion();
  6619. Matrix._xAxis = Vector3.Zero();
  6620. Matrix._yAxis = Vector3.Zero();
  6621. Matrix._zAxis = Vector3.Zero();
  6622. Matrix._updateFlagSeed = 0;
  6623. Matrix._identityReadOnly = Matrix.Identity();
  6624. return Matrix;
  6625. }());
  6626. BABYLON.Matrix = Matrix;
  6627. var Plane = /** @class */ (function () {
  6628. /**
  6629. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6630. */
  6631. function Plane(a, b, c, d) {
  6632. this.normal = new Vector3(a, b, c);
  6633. this.d = d;
  6634. }
  6635. /**
  6636. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6637. */
  6638. Plane.prototype.asArray = function () {
  6639. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6640. };
  6641. // Methods
  6642. /**
  6643. * Returns a new plane copied from the current Plane.
  6644. */
  6645. Plane.prototype.clone = function () {
  6646. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6647. };
  6648. /**
  6649. * Returns the string "Plane".
  6650. */
  6651. Plane.prototype.getClassName = function () {
  6652. return "Plane";
  6653. };
  6654. /**
  6655. * Returns the Plane hash code.
  6656. */
  6657. Plane.prototype.getHashCode = function () {
  6658. var hash = this.normal.getHashCode();
  6659. hash = (hash * 397) ^ (this.d || 0);
  6660. return hash;
  6661. };
  6662. /**
  6663. * Normalize the current Plane in place.
  6664. * Returns the updated Plane.
  6665. */
  6666. Plane.prototype.normalize = function () {
  6667. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6668. var magnitude = 0.0;
  6669. if (norm !== 0) {
  6670. magnitude = 1.0 / norm;
  6671. }
  6672. this.normal.x *= magnitude;
  6673. this.normal.y *= magnitude;
  6674. this.normal.z *= magnitude;
  6675. this.d *= magnitude;
  6676. return this;
  6677. };
  6678. /**
  6679. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6680. */
  6681. Plane.prototype.transform = function (transformation) {
  6682. var transposedMatrix = Matrix.Transpose(transformation);
  6683. var x = this.normal.x;
  6684. var y = this.normal.y;
  6685. var z = this.normal.z;
  6686. var d = this.d;
  6687. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6688. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6689. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6690. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6691. return new Plane(normalX, normalY, normalZ, finalD);
  6692. };
  6693. /**
  6694. * Returns the dot product (float) of the point coordinates and the plane normal.
  6695. */
  6696. Plane.prototype.dotCoordinate = function (point) {
  6697. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6698. };
  6699. /**
  6700. * Updates the current Plane from the plane defined by the three given points.
  6701. * Returns the updated Plane.
  6702. */
  6703. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6704. var x1 = point2.x - point1.x;
  6705. var y1 = point2.y - point1.y;
  6706. var z1 = point2.z - point1.z;
  6707. var x2 = point3.x - point1.x;
  6708. var y2 = point3.y - point1.y;
  6709. var z2 = point3.z - point1.z;
  6710. var yz = (y1 * z2) - (z1 * y2);
  6711. var xz = (z1 * x2) - (x1 * z2);
  6712. var xy = (x1 * y2) - (y1 * x2);
  6713. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6714. var invPyth;
  6715. if (pyth !== 0) {
  6716. invPyth = 1.0 / pyth;
  6717. }
  6718. else {
  6719. invPyth = 0.0;
  6720. }
  6721. this.normal.x = yz * invPyth;
  6722. this.normal.y = xz * invPyth;
  6723. this.normal.z = xy * invPyth;
  6724. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6725. return this;
  6726. };
  6727. /**
  6728. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6729. */
  6730. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6731. var dot = Vector3.Dot(this.normal, direction);
  6732. return (dot <= epsilon);
  6733. };
  6734. /**
  6735. * Returns the signed distance (float) from the given point to the Plane.
  6736. */
  6737. Plane.prototype.signedDistanceTo = function (point) {
  6738. return Vector3.Dot(point, this.normal) + this.d;
  6739. };
  6740. // Statics
  6741. /**
  6742. * Returns a new Plane from the given array.
  6743. */
  6744. Plane.FromArray = function (array) {
  6745. return new Plane(array[0], array[1], array[2], array[3]);
  6746. };
  6747. /**
  6748. * Returns a new Plane defined by the three given points.
  6749. */
  6750. Plane.FromPoints = function (point1, point2, point3) {
  6751. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6752. result.copyFromPoints(point1, point2, point3);
  6753. return result;
  6754. };
  6755. /**
  6756. * Returns a new Plane the normal vector to this plane at the given origin point.
  6757. * Note : the vector "normal" is updated because normalized.
  6758. */
  6759. Plane.FromPositionAndNormal = function (origin, normal) {
  6760. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6761. normal.normalize();
  6762. result.normal = normal;
  6763. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6764. return result;
  6765. };
  6766. /**
  6767. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6768. */
  6769. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6770. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6771. return Vector3.Dot(point, normal) + d;
  6772. };
  6773. return Plane;
  6774. }());
  6775. BABYLON.Plane = Plane;
  6776. var Viewport = /** @class */ (function () {
  6777. /**
  6778. * Creates a Viewport object located at (x, y) and sized (width, height).
  6779. */
  6780. function Viewport(x, y, width, height) {
  6781. this.x = x;
  6782. this.y = y;
  6783. this.width = width;
  6784. this.height = height;
  6785. }
  6786. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6787. if (renderWidthOrEngine.getRenderWidth) {
  6788. var engine = renderWidthOrEngine;
  6789. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6790. }
  6791. var renderWidth = renderWidthOrEngine;
  6792. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6793. };
  6794. /**
  6795. * Returns a new Viewport copied from the current one.
  6796. */
  6797. Viewport.prototype.clone = function () {
  6798. return new Viewport(this.x, this.y, this.width, this.height);
  6799. };
  6800. return Viewport;
  6801. }());
  6802. BABYLON.Viewport = Viewport;
  6803. var Frustum = /** @class */ (function () {
  6804. function Frustum() {
  6805. }
  6806. /**
  6807. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6808. */
  6809. Frustum.GetPlanes = function (transform) {
  6810. var frustumPlanes = [];
  6811. for (var index = 0; index < 6; index++) {
  6812. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6813. }
  6814. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6815. return frustumPlanes;
  6816. };
  6817. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6818. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6819. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6820. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6821. frustumPlane.d = transform.m[15] + transform.m[14];
  6822. frustumPlane.normalize();
  6823. };
  6824. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6825. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6826. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6827. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6828. frustumPlane.d = transform.m[15] - transform.m[14];
  6829. frustumPlane.normalize();
  6830. };
  6831. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6832. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6833. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6834. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6835. frustumPlane.d = transform.m[15] + transform.m[12];
  6836. frustumPlane.normalize();
  6837. };
  6838. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6840. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6841. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6842. frustumPlane.d = transform.m[15] - transform.m[12];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6847. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6848. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6849. frustumPlane.d = transform.m[15] - transform.m[13];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6854. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6855. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6856. frustumPlane.d = transform.m[15] + transform.m[13];
  6857. frustumPlane.normalize();
  6858. };
  6859. /**
  6860. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6861. */
  6862. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6863. // Near
  6864. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6865. // Far
  6866. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6867. // Left
  6868. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6869. // Right
  6870. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6871. // Top
  6872. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6873. // Bottom
  6874. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6875. };
  6876. return Frustum;
  6877. }());
  6878. BABYLON.Frustum = Frustum;
  6879. /** Defines supported spaces */
  6880. var Space;
  6881. (function (Space) {
  6882. /** Local (object) space */
  6883. Space[Space["LOCAL"] = 0] = "LOCAL";
  6884. /** World space */
  6885. Space[Space["WORLD"] = 1] = "WORLD";
  6886. /** Bone space */
  6887. Space[Space["BONE"] = 2] = "BONE";
  6888. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6889. /** Defines the 3 main axes */
  6890. var Axis = /** @class */ (function () {
  6891. function Axis() {
  6892. }
  6893. /** X axis */
  6894. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6895. /** Y axis */
  6896. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6897. /** Z axis */
  6898. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6899. return Axis;
  6900. }());
  6901. BABYLON.Axis = Axis;
  6902. ;
  6903. var BezierCurve = /** @class */ (function () {
  6904. function BezierCurve() {
  6905. }
  6906. /**
  6907. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6908. */
  6909. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6910. // Extract X (which is equal to time here)
  6911. var f0 = 1 - 3 * x2 + 3 * x1;
  6912. var f1 = 3 * x2 - 6 * x1;
  6913. var f2 = 3 * x1;
  6914. var refinedT = t;
  6915. for (var i = 0; i < 5; i++) {
  6916. var refinedT2 = refinedT * refinedT;
  6917. var refinedT3 = refinedT2 * refinedT;
  6918. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6919. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6920. refinedT -= (x - t) * slope;
  6921. refinedT = Math.min(1, Math.max(0, refinedT));
  6922. }
  6923. // Resolve cubic bezier for the given x
  6924. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6925. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6926. Math.pow(refinedT, 3);
  6927. };
  6928. return BezierCurve;
  6929. }());
  6930. BABYLON.BezierCurve = BezierCurve;
  6931. /**
  6932. * Defines potential orientation for back face culling
  6933. */
  6934. var Orientation;
  6935. (function (Orientation) {
  6936. /**
  6937. * Clockwise
  6938. */
  6939. Orientation[Orientation["CW"] = 0] = "CW";
  6940. /** Counter clockwise */
  6941. Orientation[Orientation["CCW"] = 1] = "CCW";
  6942. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6943. /**
  6944. * Defines angle representation
  6945. */
  6946. var Angle = /** @class */ (function () {
  6947. /**
  6948. * Creates an Angle object of "radians" radians (float).
  6949. */
  6950. function Angle(radians) {
  6951. this._radians = radians;
  6952. if (this._radians < 0.0)
  6953. this._radians += (2.0 * Math.PI);
  6954. }
  6955. /**
  6956. * Get value in degrees
  6957. * @returns the Angle value in degrees (float)
  6958. */
  6959. Angle.prototype.degrees = function () {
  6960. return this._radians * 180.0 / Math.PI;
  6961. };
  6962. /**
  6963. * Get value in radians
  6964. * @returns the Angle value in radians (float)
  6965. */
  6966. Angle.prototype.radians = function () {
  6967. return this._radians;
  6968. };
  6969. /**
  6970. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6971. * @param a defines first vector
  6972. * @param b defines second vector
  6973. * @returns a new Angle
  6974. */
  6975. Angle.BetweenTwoPoints = function (a, b) {
  6976. var delta = b.subtract(a);
  6977. var theta = Math.atan2(delta.y, delta.x);
  6978. return new Angle(theta);
  6979. };
  6980. /**
  6981. * Gets a new Angle object from the given float in radians
  6982. * @param radians defines the angle value in radians
  6983. * @returns a new Angle
  6984. */
  6985. Angle.FromRadians = function (radians) {
  6986. return new Angle(radians);
  6987. };
  6988. /**
  6989. * Gets a new Angle object from the given float in degrees
  6990. * @param degrees defines the angle value in degrees
  6991. * @returns a new Angle
  6992. */
  6993. Angle.FromDegrees = function (degrees) {
  6994. return new Angle(degrees * Math.PI / 180.0);
  6995. };
  6996. return Angle;
  6997. }());
  6998. BABYLON.Angle = Angle;
  6999. var Arc2 = /** @class */ (function () {
  7000. /**
  7001. * Creates an Arc object from the three given points : start, middle and end.
  7002. */
  7003. function Arc2(startPoint, midPoint, endPoint) {
  7004. this.startPoint = startPoint;
  7005. this.midPoint = midPoint;
  7006. this.endPoint = endPoint;
  7007. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7008. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7009. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7010. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7011. 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);
  7012. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7013. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7014. var a1 = this.startAngle.degrees();
  7015. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7016. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7017. // angles correction
  7018. if (a2 - a1 > +180.0)
  7019. a2 -= 360.0;
  7020. if (a2 - a1 < -180.0)
  7021. a2 += 360.0;
  7022. if (a3 - a2 > +180.0)
  7023. a3 -= 360.0;
  7024. if (a3 - a2 < -180.0)
  7025. a3 += 360.0;
  7026. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7027. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7028. }
  7029. return Arc2;
  7030. }());
  7031. BABYLON.Arc2 = Arc2;
  7032. var Path2 = /** @class */ (function () {
  7033. /**
  7034. * Creates a Path2 object from the starting 2D coordinates x and y.
  7035. */
  7036. function Path2(x, y) {
  7037. this._points = new Array();
  7038. this._length = 0.0;
  7039. this.closed = false;
  7040. this._points.push(new Vector2(x, y));
  7041. }
  7042. /**
  7043. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7044. * Returns the updated Path2.
  7045. */
  7046. Path2.prototype.addLineTo = function (x, y) {
  7047. if (this.closed) {
  7048. return this;
  7049. }
  7050. var newPoint = new Vector2(x, y);
  7051. var previousPoint = this._points[this._points.length - 1];
  7052. this._points.push(newPoint);
  7053. this._length += newPoint.subtract(previousPoint).length();
  7054. return this;
  7055. };
  7056. /**
  7057. * 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.
  7058. * Returns the updated Path2.
  7059. */
  7060. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7061. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7062. if (this.closed) {
  7063. return this;
  7064. }
  7065. var startPoint = this._points[this._points.length - 1];
  7066. var midPoint = new Vector2(midX, midY);
  7067. var endPoint = new Vector2(endX, endY);
  7068. var arc = new Arc2(startPoint, midPoint, endPoint);
  7069. var increment = arc.angle.radians() / numberOfSegments;
  7070. if (arc.orientation === Orientation.CW)
  7071. increment *= -1;
  7072. var currentAngle = arc.startAngle.radians() + increment;
  7073. for (var i = 0; i < numberOfSegments; i++) {
  7074. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7075. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7076. this.addLineTo(x, y);
  7077. currentAngle += increment;
  7078. }
  7079. return this;
  7080. };
  7081. /**
  7082. * Closes the Path2.
  7083. * Returns the Path2.
  7084. */
  7085. Path2.prototype.close = function () {
  7086. this.closed = true;
  7087. return this;
  7088. };
  7089. /**
  7090. * Returns the Path2 total length (float).
  7091. */
  7092. Path2.prototype.length = function () {
  7093. var result = this._length;
  7094. if (!this.closed) {
  7095. var lastPoint = this._points[this._points.length - 1];
  7096. var firstPoint = this._points[0];
  7097. result += (firstPoint.subtract(lastPoint).length());
  7098. }
  7099. return result;
  7100. };
  7101. /**
  7102. * Returns the Path2 internal array of points.
  7103. */
  7104. Path2.prototype.getPoints = function () {
  7105. return this._points;
  7106. };
  7107. /**
  7108. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7109. */
  7110. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7111. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7112. return Vector2.Zero();
  7113. }
  7114. var lengthPosition = normalizedLengthPosition * this.length();
  7115. var previousOffset = 0;
  7116. for (var i = 0; i < this._points.length; i++) {
  7117. var j = (i + 1) % this._points.length;
  7118. var a = this._points[i];
  7119. var b = this._points[j];
  7120. var bToA = b.subtract(a);
  7121. var nextOffset = (bToA.length() + previousOffset);
  7122. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7123. var dir = bToA.normalize();
  7124. var localOffset = lengthPosition - previousOffset;
  7125. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7126. }
  7127. previousOffset = nextOffset;
  7128. }
  7129. return Vector2.Zero();
  7130. };
  7131. /**
  7132. * Returns a new Path2 starting at the coordinates (x, y).
  7133. */
  7134. Path2.StartingAt = function (x, y) {
  7135. return new Path2(x, y);
  7136. };
  7137. return Path2;
  7138. }());
  7139. BABYLON.Path2 = Path2;
  7140. var Path3D = /** @class */ (function () {
  7141. /**
  7142. * new Path3D(path, normal, raw)
  7143. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7144. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7145. * path : an array of Vector3, the curve axis of the Path3D
  7146. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7147. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7148. */
  7149. function Path3D(path, firstNormal, raw) {
  7150. if (firstNormal === void 0) { firstNormal = null; }
  7151. this.path = path;
  7152. this._curve = new Array();
  7153. this._distances = new Array();
  7154. this._tangents = new Array();
  7155. this._normals = new Array();
  7156. this._binormals = new Array();
  7157. for (var p = 0; p < path.length; p++) {
  7158. this._curve[p] = path[p].clone(); // hard copy
  7159. }
  7160. this._raw = raw || false;
  7161. this._compute(firstNormal);
  7162. }
  7163. /**
  7164. * Returns the Path3D array of successive Vector3 designing its curve.
  7165. */
  7166. Path3D.prototype.getCurve = function () {
  7167. return this._curve;
  7168. };
  7169. /**
  7170. * Returns an array populated with tangent vectors on each Path3D curve point.
  7171. */
  7172. Path3D.prototype.getTangents = function () {
  7173. return this._tangents;
  7174. };
  7175. /**
  7176. * Returns an array populated with normal vectors on each Path3D curve point.
  7177. */
  7178. Path3D.prototype.getNormals = function () {
  7179. return this._normals;
  7180. };
  7181. /**
  7182. * Returns an array populated with binormal vectors on each Path3D curve point.
  7183. */
  7184. Path3D.prototype.getBinormals = function () {
  7185. return this._binormals;
  7186. };
  7187. /**
  7188. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7189. */
  7190. Path3D.prototype.getDistances = function () {
  7191. return this._distances;
  7192. };
  7193. /**
  7194. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7195. * Returns the same object updated.
  7196. */
  7197. Path3D.prototype.update = function (path, firstNormal) {
  7198. if (firstNormal === void 0) { firstNormal = null; }
  7199. for (var p = 0; p < path.length; p++) {
  7200. this._curve[p].x = path[p].x;
  7201. this._curve[p].y = path[p].y;
  7202. this._curve[p].z = path[p].z;
  7203. }
  7204. this._compute(firstNormal);
  7205. return this;
  7206. };
  7207. // private function compute() : computes tangents, normals and binormals
  7208. Path3D.prototype._compute = function (firstNormal) {
  7209. var l = this._curve.length;
  7210. // first and last tangents
  7211. this._tangents[0] = this._getFirstNonNullVector(0);
  7212. if (!this._raw) {
  7213. this._tangents[0].normalize();
  7214. }
  7215. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7216. if (!this._raw) {
  7217. this._tangents[l - 1].normalize();
  7218. }
  7219. // normals and binormals at first point : arbitrary vector with _normalVector()
  7220. var tg0 = this._tangents[0];
  7221. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7222. this._normals[0] = pp0;
  7223. if (!this._raw) {
  7224. this._normals[0].normalize();
  7225. }
  7226. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7227. if (!this._raw) {
  7228. this._binormals[0].normalize();
  7229. }
  7230. this._distances[0] = 0.0;
  7231. // normals and binormals : next points
  7232. var prev; // previous vector (segment)
  7233. var cur; // current vector (segment)
  7234. var curTang; // current tangent
  7235. // previous normal
  7236. var prevBinor; // previous binormal
  7237. for (var i = 1; i < l; i++) {
  7238. // tangents
  7239. prev = this._getLastNonNullVector(i);
  7240. if (i < l - 1) {
  7241. cur = this._getFirstNonNullVector(i);
  7242. this._tangents[i] = prev.add(cur);
  7243. this._tangents[i].normalize();
  7244. }
  7245. this._distances[i] = this._distances[i - 1] + prev.length();
  7246. // normals and binormals
  7247. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7248. curTang = this._tangents[i];
  7249. prevBinor = this._binormals[i - 1];
  7250. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7251. if (!this._raw) {
  7252. this._normals[i].normalize();
  7253. }
  7254. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7255. if (!this._raw) {
  7256. this._binormals[i].normalize();
  7257. }
  7258. }
  7259. };
  7260. // private function getFirstNonNullVector(index)
  7261. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7262. Path3D.prototype._getFirstNonNullVector = function (index) {
  7263. var i = 1;
  7264. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7265. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7266. i++;
  7267. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7268. }
  7269. return nNVector;
  7270. };
  7271. // private function getLastNonNullVector(index)
  7272. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7273. Path3D.prototype._getLastNonNullVector = function (index) {
  7274. var i = 1;
  7275. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7276. while (nLVector.length() === 0 && index > i + 1) {
  7277. i++;
  7278. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7279. }
  7280. return nLVector;
  7281. };
  7282. // private function normalVector(v0, vt, va) :
  7283. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7284. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7285. Path3D.prototype._normalVector = function (v0, vt, va) {
  7286. var normal0;
  7287. var tgl = vt.length();
  7288. if (tgl === 0.0) {
  7289. tgl = 1.0;
  7290. }
  7291. if (va === undefined || va === null) {
  7292. var point;
  7293. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7294. point = new Vector3(0.0, -1.0, 0.0);
  7295. }
  7296. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7297. point = new Vector3(1.0, 0.0, 0.0);
  7298. }
  7299. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7300. point = new Vector3(0.0, 0.0, 1.0);
  7301. }
  7302. else {
  7303. point = Vector3.Zero();
  7304. }
  7305. normal0 = Vector3.Cross(vt, point);
  7306. }
  7307. else {
  7308. normal0 = Vector3.Cross(vt, va);
  7309. Vector3.CrossToRef(normal0, vt, normal0);
  7310. }
  7311. normal0.normalize();
  7312. return normal0;
  7313. };
  7314. return Path3D;
  7315. }());
  7316. BABYLON.Path3D = Path3D;
  7317. var Curve3 = /** @class */ (function () {
  7318. /**
  7319. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7320. * A Curve3 is designed from a series of successive Vector3.
  7321. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7322. */
  7323. function Curve3(points) {
  7324. this._length = 0.0;
  7325. this._points = points;
  7326. this._length = this._computeLength(points);
  7327. }
  7328. /**
  7329. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7330. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7331. * @param v1 (Vector3) the control point
  7332. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7333. * @param nbPoints (integer) the wanted number of points in the curve
  7334. */
  7335. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7336. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7337. var bez = new Array();
  7338. var equation = function (t, val0, val1, val2) {
  7339. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7340. return res;
  7341. };
  7342. for (var i = 0; i <= nbPoints; i++) {
  7343. 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)));
  7344. }
  7345. return new Curve3(bez);
  7346. };
  7347. /**
  7348. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7349. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7350. * @param v1 (Vector3) the first control point
  7351. * @param v2 (Vector3) the second control point
  7352. * @param v3 (Vector3) the end point of the Cubic Bezier
  7353. * @param nbPoints (integer) the wanted number of points in the curve
  7354. */
  7355. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7356. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7357. var bez = new Array();
  7358. var equation = function (t, val0, val1, val2, val3) {
  7359. 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;
  7360. return res;
  7361. };
  7362. for (var i = 0; i <= nbPoints; i++) {
  7363. 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)));
  7364. }
  7365. return new Curve3(bez);
  7366. };
  7367. /**
  7368. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7369. * @param p1 (Vector3) the origin point of the Hermite Spline
  7370. * @param t1 (Vector3) the tangent vector at the origin point
  7371. * @param p2 (Vector3) the end point of the Hermite Spline
  7372. * @param t2 (Vector3) the tangent vector at the end point
  7373. * @param nbPoints (integer) the wanted number of points in the curve
  7374. */
  7375. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7376. var hermite = new Array();
  7377. var step = 1.0 / nbPoints;
  7378. for (var i = 0; i <= nbPoints; i++) {
  7379. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7380. }
  7381. return new Curve3(hermite);
  7382. };
  7383. /**
  7384. * Returns a Curve3 object along a CatmullRom Spline curve :
  7385. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7386. * @param nbPoints (integer) the wanted number of points between each curve control points
  7387. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7388. */
  7389. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7390. var catmullRom = new Array();
  7391. var step = 1.0 / nbPoints;
  7392. var amount = 0.0;
  7393. if (closed) {
  7394. var pointsCount = points.length;
  7395. for (var i = 0; i < pointsCount; i++) {
  7396. amount = 0;
  7397. for (var c = 0; c < nbPoints; c++) {
  7398. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7399. amount += step;
  7400. }
  7401. }
  7402. catmullRom.push(catmullRom[0]);
  7403. }
  7404. else {
  7405. var totalPoints = new Array();
  7406. totalPoints.push(points[0].clone());
  7407. Array.prototype.push.apply(totalPoints, points);
  7408. totalPoints.push(points[points.length - 1].clone());
  7409. for (var i = 0; i < totalPoints.length - 3; i++) {
  7410. amount = 0;
  7411. for (var c = 0; c < nbPoints; c++) {
  7412. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7413. amount += step;
  7414. }
  7415. }
  7416. i--;
  7417. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7418. }
  7419. return new Curve3(catmullRom);
  7420. };
  7421. /**
  7422. * Returns the Curve3 stored array of successive Vector3
  7423. */
  7424. Curve3.prototype.getPoints = function () {
  7425. return this._points;
  7426. };
  7427. /**
  7428. * Returns the computed length (float) of the curve.
  7429. */
  7430. Curve3.prototype.length = function () {
  7431. return this._length;
  7432. };
  7433. /**
  7434. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7435. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7436. * curveA and curveB keep unchanged.
  7437. */
  7438. Curve3.prototype.continue = function (curve) {
  7439. var lastPoint = this._points[this._points.length - 1];
  7440. var continuedPoints = this._points.slice();
  7441. var curvePoints = curve.getPoints();
  7442. for (var i = 1; i < curvePoints.length; i++) {
  7443. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7444. }
  7445. var continuedCurve = new Curve3(continuedPoints);
  7446. return continuedCurve;
  7447. };
  7448. Curve3.prototype._computeLength = function (path) {
  7449. var l = 0;
  7450. for (var i = 1; i < path.length; i++) {
  7451. l += (path[i].subtract(path[i - 1])).length();
  7452. }
  7453. return l;
  7454. };
  7455. return Curve3;
  7456. }());
  7457. BABYLON.Curve3 = Curve3;
  7458. // Vertex formats
  7459. var PositionNormalVertex = /** @class */ (function () {
  7460. function PositionNormalVertex(position, normal) {
  7461. if (position === void 0) { position = Vector3.Zero(); }
  7462. if (normal === void 0) { normal = Vector3.Up(); }
  7463. this.position = position;
  7464. this.normal = normal;
  7465. }
  7466. PositionNormalVertex.prototype.clone = function () {
  7467. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7468. };
  7469. return PositionNormalVertex;
  7470. }());
  7471. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7472. var PositionNormalTextureVertex = /** @class */ (function () {
  7473. function PositionNormalTextureVertex(position, normal, uv) {
  7474. if (position === void 0) { position = Vector3.Zero(); }
  7475. if (normal === void 0) { normal = Vector3.Up(); }
  7476. if (uv === void 0) { uv = Vector2.Zero(); }
  7477. this.position = position;
  7478. this.normal = normal;
  7479. this.uv = uv;
  7480. }
  7481. PositionNormalTextureVertex.prototype.clone = function () {
  7482. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7483. };
  7484. return PositionNormalTextureVertex;
  7485. }());
  7486. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7487. // Temporary pre-allocated objects for engine internal use
  7488. // usage in any internal function :
  7489. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7490. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7491. var Tmp = /** @class */ (function () {
  7492. function Tmp() {
  7493. }
  7494. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7495. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7496. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7497. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7498. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7499. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7500. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7501. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7502. Matrix.Zero(), Matrix.Zero(),
  7503. Matrix.Zero(), Matrix.Zero(),
  7504. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7505. return Tmp;
  7506. }());
  7507. BABYLON.Tmp = Tmp;
  7508. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7509. var MathTmp = /** @class */ (function () {
  7510. function MathTmp() {
  7511. }
  7512. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7513. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7514. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7515. return MathTmp;
  7516. }());
  7517. })(BABYLON || (BABYLON = {}));
  7518. //# sourceMappingURL=babylon.math.js.map
  7519. var BABYLON;
  7520. (function (BABYLON) {
  7521. var Scalar = /** @class */ (function () {
  7522. function Scalar() {
  7523. }
  7524. /**
  7525. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7526. */
  7527. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7528. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7529. var num = a - b;
  7530. return -epsilon <= num && num <= epsilon;
  7531. };
  7532. /**
  7533. * Returns a string : the upper case translation of the number i to hexadecimal.
  7534. */
  7535. Scalar.ToHex = function (i) {
  7536. var str = i.toString(16);
  7537. if (i <= 15) {
  7538. return ("0" + str).toUpperCase();
  7539. }
  7540. return str.toUpperCase();
  7541. };
  7542. /**
  7543. * Returns -1 if value is negative and +1 is value is positive.
  7544. * Returns the value itself if it's equal to zero.
  7545. */
  7546. Scalar.Sign = function (value) {
  7547. value = +value; // convert to a number
  7548. if (value === 0 || isNaN(value))
  7549. return value;
  7550. return value > 0 ? 1 : -1;
  7551. };
  7552. /**
  7553. * Returns the value itself if it's between min and max.
  7554. * Returns min if the value is lower than min.
  7555. * Returns max if the value is greater than max.
  7556. */
  7557. Scalar.Clamp = function (value, min, max) {
  7558. if (min === void 0) { min = 0; }
  7559. if (max === void 0) { max = 1; }
  7560. return Math.min(max, Math.max(min, value));
  7561. };
  7562. /**
  7563. * Returns the log2 of value.
  7564. */
  7565. Scalar.Log2 = function (value) {
  7566. return Math.log(value) * Math.LOG2E;
  7567. };
  7568. /**
  7569. * Loops the value, so that it is never larger than length and never smaller than 0.
  7570. *
  7571. * This is similar to the modulo operator but it works with floating point numbers.
  7572. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7573. * With t = 5 and length = 2.5, the result would be 0.0.
  7574. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7575. */
  7576. Scalar.Repeat = function (value, length) {
  7577. return value - Math.floor(value / length) * length;
  7578. };
  7579. /**
  7580. * Normalize the value between 0.0 and 1.0 using min and max values
  7581. */
  7582. Scalar.Normalize = function (value, min, max) {
  7583. return (value - min) / (max - min);
  7584. };
  7585. /**
  7586. * Denormalize the value from 0.0 and 1.0 using min and max values
  7587. */
  7588. Scalar.Denormalize = function (normalized, min, max) {
  7589. return (normalized * (max - min) + min);
  7590. };
  7591. /**
  7592. * Calculates the shortest difference between two given angles given in degrees.
  7593. */
  7594. Scalar.DeltaAngle = function (current, target) {
  7595. var num = Scalar.Repeat(target - current, 360.0);
  7596. if (num > 180.0) {
  7597. num -= 360.0;
  7598. }
  7599. return num;
  7600. };
  7601. /**
  7602. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7603. *
  7604. * The returned value will move back and forth between 0 and length
  7605. */
  7606. Scalar.PingPong = function (tx, length) {
  7607. var t = Scalar.Repeat(tx, length * 2.0);
  7608. return length - Math.abs(t - length);
  7609. };
  7610. /**
  7611. * Interpolates between min and max with smoothing at the limits.
  7612. *
  7613. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7614. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7615. */
  7616. Scalar.SmoothStep = function (from, to, tx) {
  7617. var t = Scalar.Clamp(tx);
  7618. t = -2.0 * t * t * t + 3.0 * t * t;
  7619. return to * t + from * (1.0 - t);
  7620. };
  7621. /**
  7622. * Moves a value current towards target.
  7623. *
  7624. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7625. * Negative values of maxDelta pushes the value away from target.
  7626. */
  7627. Scalar.MoveTowards = function (current, target, maxDelta) {
  7628. var result = 0;
  7629. if (Math.abs(target - current) <= maxDelta) {
  7630. result = target;
  7631. }
  7632. else {
  7633. result = current + Scalar.Sign(target - current) * maxDelta;
  7634. }
  7635. return result;
  7636. };
  7637. /**
  7638. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7639. *
  7640. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7641. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7642. */
  7643. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7644. var num = Scalar.DeltaAngle(current, target);
  7645. var result = 0;
  7646. if (-maxDelta < num && num < maxDelta) {
  7647. result = target;
  7648. }
  7649. else {
  7650. target = current + num;
  7651. result = Scalar.MoveTowards(current, target, maxDelta);
  7652. }
  7653. return result;
  7654. };
  7655. /**
  7656. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7657. */
  7658. Scalar.Lerp = function (start, end, amount) {
  7659. return start + ((end - start) * amount);
  7660. };
  7661. /**
  7662. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7663. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7664. */
  7665. Scalar.LerpAngle = function (start, end, amount) {
  7666. var num = Scalar.Repeat(end - start, 360.0);
  7667. if (num > 180.0) {
  7668. num -= 360.0;
  7669. }
  7670. return start + num * Scalar.Clamp(amount);
  7671. };
  7672. /**
  7673. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7674. */
  7675. Scalar.InverseLerp = function (a, b, value) {
  7676. var result = 0;
  7677. if (a != b) {
  7678. result = Scalar.Clamp((value - a) / (b - a));
  7679. }
  7680. else {
  7681. result = 0.0;
  7682. }
  7683. return result;
  7684. };
  7685. /**
  7686. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7687. */
  7688. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7689. var squared = amount * amount;
  7690. var cubed = amount * squared;
  7691. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7692. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7693. var part3 = (cubed - (2.0 * squared)) + amount;
  7694. var part4 = cubed - squared;
  7695. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7696. };
  7697. /**
  7698. * Returns a random float number between and min and max values
  7699. */
  7700. Scalar.RandomRange = function (min, max) {
  7701. if (min === max)
  7702. return min;
  7703. return ((Math.random() * (max - min)) + min);
  7704. };
  7705. /**
  7706. * This function returns percentage of a number in a given range.
  7707. *
  7708. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7709. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7710. */
  7711. Scalar.RangeToPercent = function (number, min, max) {
  7712. return ((number - min) / (max - min));
  7713. };
  7714. /**
  7715. * This function returns number that corresponds to the percentage in a given range.
  7716. *
  7717. * PercentToRange(0.34,0,100) will return 34.
  7718. */
  7719. Scalar.PercentToRange = function (percent, min, max) {
  7720. return ((max - min) * percent + min);
  7721. };
  7722. /**
  7723. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7724. * @param angle The angle to normalize in radian.
  7725. * @return The converted angle.
  7726. */
  7727. Scalar.NormalizeRadians = function (angle) {
  7728. // More precise but slower version kept for reference.
  7729. // angle = angle % Tools.TwoPi;
  7730. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7731. //if (angle > Math.PI) {
  7732. // angle -= Tools.TwoPi;
  7733. //}
  7734. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7735. return angle;
  7736. };
  7737. /**
  7738. * Two pi constants convenient for computation.
  7739. */
  7740. Scalar.TwoPi = Math.PI * 2;
  7741. return Scalar;
  7742. }());
  7743. BABYLON.Scalar = Scalar;
  7744. })(BABYLON || (BABYLON = {}));
  7745. //# sourceMappingURL=babylon.math.scalar.js.map
  7746. //# sourceMappingURL=babylon.mixins.js.map
  7747. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7748. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7749. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7750. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7751. //# sourceMappingURL=babylon.webgl2.js.map
  7752. var BABYLON;
  7753. (function (BABYLON) {
  7754. var __decoratorInitialStore = {};
  7755. var __mergedStore = {};
  7756. var _copySource = function (creationFunction, source, instanciate) {
  7757. var destination = creationFunction();
  7758. // Tags
  7759. if (BABYLON.Tags) {
  7760. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7761. }
  7762. var classStore = getMergedStore(destination);
  7763. // Properties
  7764. for (var property in classStore) {
  7765. var propertyDescriptor = classStore[property];
  7766. var sourceProperty = source[property];
  7767. var propertyType = propertyDescriptor.type;
  7768. if (sourceProperty !== undefined && sourceProperty !== null) {
  7769. switch (propertyType) {
  7770. case 0: // Value
  7771. case 6: // Mesh reference
  7772. case 11: // Camera reference
  7773. destination[property] = sourceProperty;
  7774. break;
  7775. case 1: // Texture
  7776. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7777. break;
  7778. case 2: // Color3
  7779. case 3: // FresnelParameters
  7780. case 4: // Vector2
  7781. case 5: // Vector3
  7782. case 7: // Color Curves
  7783. case 10: // Quaternion
  7784. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7785. break;
  7786. }
  7787. }
  7788. }
  7789. return destination;
  7790. };
  7791. function getDirectStore(target) {
  7792. var classKey = target.getClassName();
  7793. if (!__decoratorInitialStore[classKey]) {
  7794. __decoratorInitialStore[classKey] = {};
  7795. }
  7796. return __decoratorInitialStore[classKey];
  7797. }
  7798. /**
  7799. * Return the list of properties flagged as serializable
  7800. * @param target: host object
  7801. */
  7802. function getMergedStore(target) {
  7803. var classKey = target.getClassName();
  7804. if (__mergedStore[classKey]) {
  7805. return __mergedStore[classKey];
  7806. }
  7807. __mergedStore[classKey] = {};
  7808. var store = __mergedStore[classKey];
  7809. var currentTarget = target;
  7810. var currentKey = classKey;
  7811. while (currentKey) {
  7812. var initialStore = __decoratorInitialStore[currentKey];
  7813. for (var property in initialStore) {
  7814. store[property] = initialStore[property];
  7815. }
  7816. var parent_1 = void 0;
  7817. var done = false;
  7818. do {
  7819. parent_1 = Object.getPrototypeOf(currentTarget);
  7820. if (!parent_1.getClassName) {
  7821. done = true;
  7822. break;
  7823. }
  7824. if (parent_1.getClassName() !== currentKey) {
  7825. break;
  7826. }
  7827. currentTarget = parent_1;
  7828. } while (parent_1);
  7829. if (done) {
  7830. break;
  7831. }
  7832. currentKey = parent_1.getClassName();
  7833. currentTarget = parent_1;
  7834. }
  7835. return store;
  7836. }
  7837. function generateSerializableMember(type, sourceName) {
  7838. return function (target, propertyKey) {
  7839. var classStore = getDirectStore(target);
  7840. if (!classStore[propertyKey]) {
  7841. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7842. }
  7843. };
  7844. }
  7845. function generateExpandMember(setCallback, targetKey) {
  7846. if (targetKey === void 0) { targetKey = null; }
  7847. return function (target, propertyKey) {
  7848. var key = targetKey || ("_" + propertyKey);
  7849. Object.defineProperty(target, propertyKey, {
  7850. get: function () {
  7851. return this[key];
  7852. },
  7853. set: function (value) {
  7854. if (this[key] === value) {
  7855. return;
  7856. }
  7857. this[key] = value;
  7858. target[setCallback].apply(this);
  7859. },
  7860. enumerable: true,
  7861. configurable: true
  7862. });
  7863. };
  7864. }
  7865. function expandToProperty(callback, targetKey) {
  7866. if (targetKey === void 0) { targetKey = null; }
  7867. return generateExpandMember(callback, targetKey);
  7868. }
  7869. BABYLON.expandToProperty = expandToProperty;
  7870. function serialize(sourceName) {
  7871. return generateSerializableMember(0, sourceName); // value member
  7872. }
  7873. BABYLON.serialize = serialize;
  7874. function serializeAsTexture(sourceName) {
  7875. return generateSerializableMember(1, sourceName); // texture member
  7876. }
  7877. BABYLON.serializeAsTexture = serializeAsTexture;
  7878. function serializeAsColor3(sourceName) {
  7879. return generateSerializableMember(2, sourceName); // color3 member
  7880. }
  7881. BABYLON.serializeAsColor3 = serializeAsColor3;
  7882. function serializeAsFresnelParameters(sourceName) {
  7883. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7884. }
  7885. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7886. function serializeAsVector2(sourceName) {
  7887. return generateSerializableMember(4, sourceName); // vector2 member
  7888. }
  7889. BABYLON.serializeAsVector2 = serializeAsVector2;
  7890. function serializeAsVector3(sourceName) {
  7891. return generateSerializableMember(5, sourceName); // vector3 member
  7892. }
  7893. BABYLON.serializeAsVector3 = serializeAsVector3;
  7894. function serializeAsMeshReference(sourceName) {
  7895. return generateSerializableMember(6, sourceName); // mesh reference member
  7896. }
  7897. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7898. function serializeAsColorCurves(sourceName) {
  7899. return generateSerializableMember(7, sourceName); // color curves
  7900. }
  7901. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7902. function serializeAsColor4(sourceName) {
  7903. return generateSerializableMember(8, sourceName); // color 4
  7904. }
  7905. BABYLON.serializeAsColor4 = serializeAsColor4;
  7906. function serializeAsImageProcessingConfiguration(sourceName) {
  7907. return generateSerializableMember(9, sourceName); // image processing
  7908. }
  7909. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7910. function serializeAsQuaternion(sourceName) {
  7911. return generateSerializableMember(10, sourceName); // quaternion member
  7912. }
  7913. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7914. /**
  7915. * Decorator used to define property that can be serialized as reference to a camera
  7916. * @param sourceName defines the name of the property to decorate
  7917. */
  7918. function serializeAsCameraReference(sourceName) {
  7919. return generateSerializableMember(11, sourceName); // camera reference member
  7920. }
  7921. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7922. var SerializationHelper = /** @class */ (function () {
  7923. function SerializationHelper() {
  7924. }
  7925. SerializationHelper.Serialize = function (entity, serializationObject) {
  7926. if (!serializationObject) {
  7927. serializationObject = {};
  7928. }
  7929. // Tags
  7930. if (BABYLON.Tags) {
  7931. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7932. }
  7933. var serializedProperties = getMergedStore(entity);
  7934. // Properties
  7935. for (var property in serializedProperties) {
  7936. var propertyDescriptor = serializedProperties[property];
  7937. var targetPropertyName = propertyDescriptor.sourceName || property;
  7938. var propertyType = propertyDescriptor.type;
  7939. var sourceProperty = entity[property];
  7940. if (sourceProperty !== undefined && sourceProperty !== null) {
  7941. switch (propertyType) {
  7942. case 0: // Value
  7943. serializationObject[targetPropertyName] = sourceProperty;
  7944. break;
  7945. case 1: // Texture
  7946. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7947. break;
  7948. case 2: // Color3
  7949. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7950. break;
  7951. case 3: // FresnelParameters
  7952. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7953. break;
  7954. case 4: // Vector2
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 5: // Vector3
  7958. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7959. break;
  7960. case 6: // Mesh reference
  7961. serializationObject[targetPropertyName] = sourceProperty.id;
  7962. break;
  7963. case 7: // Color Curves
  7964. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7965. break;
  7966. case 8: // Color 4
  7967. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7968. break;
  7969. case 9: // Image Processing
  7970. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7971. break;
  7972. case 10: // Quaternion
  7973. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7974. break;
  7975. case 11: // Camera reference
  7976. serializationObject[targetPropertyName] = sourceProperty.id;
  7977. break;
  7978. }
  7979. }
  7980. }
  7981. return serializationObject;
  7982. };
  7983. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7984. if (rootUrl === void 0) { rootUrl = null; }
  7985. var destination = creationFunction();
  7986. if (!rootUrl) {
  7987. rootUrl = "";
  7988. }
  7989. // Tags
  7990. if (BABYLON.Tags) {
  7991. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7992. }
  7993. var classStore = getMergedStore(destination);
  7994. // Properties
  7995. for (var property in classStore) {
  7996. var propertyDescriptor = classStore[property];
  7997. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7998. var propertyType = propertyDescriptor.type;
  7999. if (sourceProperty !== undefined && sourceProperty !== null) {
  8000. var dest = destination;
  8001. switch (propertyType) {
  8002. case 0: // Value
  8003. dest[property] = sourceProperty;
  8004. break;
  8005. case 1: // Texture
  8006. if (scene) {
  8007. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8008. }
  8009. break;
  8010. case 2: // Color3
  8011. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8012. break;
  8013. case 3: // FresnelParameters
  8014. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8015. break;
  8016. case 4: // Vector2
  8017. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8018. break;
  8019. case 5: // Vector3
  8020. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8021. break;
  8022. case 6: // Mesh reference
  8023. if (scene) {
  8024. dest[property] = scene.getLastMeshByID(sourceProperty);
  8025. }
  8026. break;
  8027. case 7: // Color Curves
  8028. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8029. break;
  8030. case 8: // Color 4
  8031. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8032. break;
  8033. case 9: // Image Processing
  8034. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8035. break;
  8036. case 10: // Quaternion
  8037. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8038. break;
  8039. case 11: // Camera reference
  8040. if (scene) {
  8041. dest[property] = scene.getCameraByID(sourceProperty);
  8042. }
  8043. break;
  8044. }
  8045. }
  8046. }
  8047. return destination;
  8048. };
  8049. SerializationHelper.Clone = function (creationFunction, source) {
  8050. return _copySource(creationFunction, source, false);
  8051. };
  8052. SerializationHelper.Instanciate = function (creationFunction, source) {
  8053. return _copySource(creationFunction, source, true);
  8054. };
  8055. return SerializationHelper;
  8056. }());
  8057. BABYLON.SerializationHelper = SerializationHelper;
  8058. })(BABYLON || (BABYLON = {}));
  8059. //# sourceMappingURL=babylon.decorators.js.map
  8060. var BABYLON;
  8061. (function (BABYLON) {
  8062. /**
  8063. * Wrapper class for promise with external resolve and reject.
  8064. */
  8065. var Deferred = /** @class */ (function () {
  8066. /**
  8067. * Constructor for this deferred object.
  8068. */
  8069. function Deferred() {
  8070. var _this = this;
  8071. this.promise = new Promise(function (resolve, reject) {
  8072. _this._resolve = resolve;
  8073. _this._reject = reject;
  8074. });
  8075. }
  8076. Object.defineProperty(Deferred.prototype, "resolve", {
  8077. /**
  8078. * The resolve method of the promise associated with this deferred object.
  8079. */
  8080. get: function () {
  8081. return this._resolve;
  8082. },
  8083. enumerable: true,
  8084. configurable: true
  8085. });
  8086. Object.defineProperty(Deferred.prototype, "reject", {
  8087. /**
  8088. * The reject method of the promise associated with this deferred object.
  8089. */
  8090. get: function () {
  8091. return this._reject;
  8092. },
  8093. enumerable: true,
  8094. configurable: true
  8095. });
  8096. return Deferred;
  8097. }());
  8098. BABYLON.Deferred = Deferred;
  8099. })(BABYLON || (BABYLON = {}));
  8100. //# sourceMappingURL=babylon.deferred.js.map
  8101. var BABYLON;
  8102. (function (BABYLON) {
  8103. /**
  8104. * A class serves as a medium between the observable and its observers
  8105. */
  8106. var EventState = /** @class */ (function () {
  8107. /**
  8108. * Create a new EventState
  8109. * @param mask defines the mask associated with this state
  8110. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8111. * @param target defines the original target of the state
  8112. * @param currentTarget defines the current target of the state
  8113. */
  8114. function EventState(mask, skipNextObservers, target, currentTarget) {
  8115. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8116. this.initalize(mask, skipNextObservers, target, currentTarget);
  8117. }
  8118. /**
  8119. * Initialize the current event state
  8120. * @param mask defines the mask associated with this state
  8121. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8122. * @param target defines the original target of the state
  8123. * @param currentTarget defines the current target of the state
  8124. * @returns the current event state
  8125. */
  8126. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8127. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8128. this.mask = mask;
  8129. this.skipNextObservers = skipNextObservers;
  8130. this.target = target;
  8131. this.currentTarget = currentTarget;
  8132. return this;
  8133. };
  8134. return EventState;
  8135. }());
  8136. BABYLON.EventState = EventState;
  8137. /**
  8138. * Represent an Observer registered to a given Observable object.
  8139. */
  8140. var Observer = /** @class */ (function () {
  8141. /**
  8142. * Creates a new observer
  8143. * @param callback defines the callback to call when the observer is notified
  8144. * @param mask defines the mask of the observer (used to filter notifications)
  8145. * @param scope defines the current scope used to restore the JS context
  8146. */
  8147. function Observer(
  8148. /**
  8149. * Defines the callback to call when the observer is notified
  8150. */
  8151. callback,
  8152. /**
  8153. * Defines the mask of the observer (used to filter notifications)
  8154. */
  8155. mask,
  8156. /**
  8157. * Defines the current scope used to restore the JS context
  8158. */
  8159. scope) {
  8160. if (scope === void 0) { scope = null; }
  8161. this.callback = callback;
  8162. this.mask = mask;
  8163. this.scope = scope;
  8164. /** @hidden */
  8165. this._willBeUnregistered = false;
  8166. /**
  8167. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8168. */
  8169. this.unregisterOnNextCall = false;
  8170. }
  8171. return Observer;
  8172. }());
  8173. BABYLON.Observer = Observer;
  8174. /**
  8175. * Represent a list of observers registered to multiple Observables object.
  8176. */
  8177. var MultiObserver = /** @class */ (function () {
  8178. function MultiObserver() {
  8179. }
  8180. /**
  8181. * Release associated resources
  8182. */
  8183. MultiObserver.prototype.dispose = function () {
  8184. if (this._observers && this._observables) {
  8185. for (var index = 0; index < this._observers.length; index++) {
  8186. this._observables[index].remove(this._observers[index]);
  8187. }
  8188. }
  8189. this._observers = null;
  8190. this._observables = null;
  8191. };
  8192. /**
  8193. * Raise a callback when one of the observable will notify
  8194. * @param observables defines a list of observables to watch
  8195. * @param callback defines the callback to call on notification
  8196. * @param mask defines the mask used to filter notifications
  8197. * @param scope defines the current scope used to restore the JS context
  8198. * @returns the new MultiObserver
  8199. */
  8200. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8201. if (mask === void 0) { mask = -1; }
  8202. if (scope === void 0) { scope = null; }
  8203. var result = new MultiObserver();
  8204. result._observers = new Array();
  8205. result._observables = observables;
  8206. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8207. var observable = observables_1[_i];
  8208. var observer = observable.add(callback, mask, false, scope);
  8209. if (observer) {
  8210. result._observers.push(observer);
  8211. }
  8212. }
  8213. return result;
  8214. };
  8215. return MultiObserver;
  8216. }());
  8217. BABYLON.MultiObserver = MultiObserver;
  8218. /**
  8219. * The Observable class is a simple implementation of the Observable pattern.
  8220. *
  8221. * 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.
  8222. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8223. * 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).
  8224. * 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.
  8225. */
  8226. var Observable = /** @class */ (function () {
  8227. /**
  8228. * Creates a new observable
  8229. * @param onObserverAdded defines a callback to call when a new observer is added
  8230. */
  8231. function Observable(onObserverAdded) {
  8232. this._observers = new Array();
  8233. this._eventState = new EventState(0);
  8234. if (onObserverAdded) {
  8235. this._onObserverAdded = onObserverAdded;
  8236. }
  8237. }
  8238. /**
  8239. * Create a new Observer with the specified callback
  8240. * @param callback the callback that will be executed for that Observer
  8241. * @param mask the mask used to filter observers
  8242. * @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.
  8243. * @param scope optional scope for the callback to be called from
  8244. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8245. * @returns the new observer created for the callback
  8246. */
  8247. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8248. if (mask === void 0) { mask = -1; }
  8249. if (insertFirst === void 0) { insertFirst = false; }
  8250. if (scope === void 0) { scope = null; }
  8251. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8252. if (!callback) {
  8253. return null;
  8254. }
  8255. var observer = new Observer(callback, mask, scope);
  8256. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8257. if (insertFirst) {
  8258. this._observers.unshift(observer);
  8259. }
  8260. else {
  8261. this._observers.push(observer);
  8262. }
  8263. if (this._onObserverAdded) {
  8264. this._onObserverAdded(observer);
  8265. }
  8266. return observer;
  8267. };
  8268. /**
  8269. * Create a new Observer with the specified callback and unregisters after the next notification
  8270. * @param callback the callback that will be executed for that Observer
  8271. * @returns the new observer created for the callback
  8272. */
  8273. Observable.prototype.addOnce = function (callback) {
  8274. return this.add(callback, undefined, undefined, undefined, true);
  8275. };
  8276. /**
  8277. * Remove an Observer from the Observable object
  8278. * @param observer the instance of the Observer to remove
  8279. * @returns false if it doesn't belong to this Observable
  8280. */
  8281. Observable.prototype.remove = function (observer) {
  8282. if (!observer) {
  8283. return false;
  8284. }
  8285. var index = this._observers.indexOf(observer);
  8286. if (index !== -1) {
  8287. this._deferUnregister(observer);
  8288. return true;
  8289. }
  8290. return false;
  8291. };
  8292. /**
  8293. * Remove a callback from the Observable object
  8294. * @param callback the callback to remove
  8295. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8296. * @returns false if it doesn't belong to this Observable
  8297. */
  8298. Observable.prototype.removeCallback = function (callback, scope) {
  8299. for (var index = 0; index < this._observers.length; index++) {
  8300. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8301. this._deferUnregister(this._observers[index]);
  8302. return true;
  8303. }
  8304. }
  8305. return false;
  8306. };
  8307. Observable.prototype._deferUnregister = function (observer) {
  8308. var _this = this;
  8309. observer.unregisterOnNextCall = false;
  8310. observer._willBeUnregistered = true;
  8311. BABYLON.Tools.SetImmediate(function () {
  8312. _this._remove(observer);
  8313. });
  8314. };
  8315. // This should only be called when not iterating over _observers to avoid callback skipping.
  8316. // Removes an observer from the _observer Array.
  8317. Observable.prototype._remove = function (observer) {
  8318. if (!observer) {
  8319. return false;
  8320. }
  8321. var index = this._observers.indexOf(observer);
  8322. if (index !== -1) {
  8323. this._observers.splice(index, 1);
  8324. return true;
  8325. }
  8326. return false;
  8327. };
  8328. /**
  8329. * Notify all Observers by calling their respective callback with the given data
  8330. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8331. * @param eventData defines the data to send to all observers
  8332. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8333. * @param target defines the original target of the state
  8334. * @param currentTarget defines the current target of the state
  8335. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8336. */
  8337. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8338. if (mask === void 0) { mask = -1; }
  8339. if (!this._observers.length) {
  8340. return true;
  8341. }
  8342. var state = this._eventState;
  8343. state.mask = mask;
  8344. state.target = target;
  8345. state.currentTarget = currentTarget;
  8346. state.skipNextObservers = false;
  8347. state.lastReturnValue = eventData;
  8348. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8349. var obs = _a[_i];
  8350. if (obs._willBeUnregistered) {
  8351. continue;
  8352. }
  8353. if (obs.mask & mask) {
  8354. if (obs.scope) {
  8355. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8356. }
  8357. else {
  8358. state.lastReturnValue = obs.callback(eventData, state);
  8359. }
  8360. if (obs.unregisterOnNextCall) {
  8361. this._deferUnregister(obs);
  8362. }
  8363. }
  8364. if (state.skipNextObservers) {
  8365. return false;
  8366. }
  8367. }
  8368. return true;
  8369. };
  8370. /**
  8371. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8372. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8373. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8374. * and it is crucial that all callbacks will be executed.
  8375. * The order of the callbacks is kept, callbacks are not executed parallel.
  8376. *
  8377. * @param eventData The data to be sent to each callback
  8378. * @param mask is used to filter observers defaults to -1
  8379. * @param target defines the callback target (see EventState)
  8380. * @param currentTarget defines he current object in the bubbling phase
  8381. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8382. */
  8383. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8384. var _this = this;
  8385. if (mask === void 0) { mask = -1; }
  8386. // create an empty promise
  8387. var p = Promise.resolve(eventData);
  8388. // no observers? return this promise.
  8389. if (!this._observers.length) {
  8390. return p;
  8391. }
  8392. var state = this._eventState;
  8393. state.mask = mask;
  8394. state.target = target;
  8395. state.currentTarget = currentTarget;
  8396. state.skipNextObservers = false;
  8397. // execute one callback after another (not using Promise.all, the order is important)
  8398. this._observers.forEach(function (obs) {
  8399. if (state.skipNextObservers) {
  8400. return;
  8401. }
  8402. if (obs._willBeUnregistered) {
  8403. return;
  8404. }
  8405. if (obs.mask & mask) {
  8406. if (obs.scope) {
  8407. p = p.then(function (lastReturnedValue) {
  8408. state.lastReturnValue = lastReturnedValue;
  8409. return obs.callback.apply(obs.scope, [eventData, state]);
  8410. });
  8411. }
  8412. else {
  8413. p = p.then(function (lastReturnedValue) {
  8414. state.lastReturnValue = lastReturnedValue;
  8415. return obs.callback(eventData, state);
  8416. });
  8417. }
  8418. if (obs.unregisterOnNextCall) {
  8419. _this._deferUnregister(obs);
  8420. }
  8421. }
  8422. });
  8423. // return the eventData
  8424. return p.then(function () { return eventData; });
  8425. };
  8426. /**
  8427. * Notify a specific observer
  8428. * @param observer defines the observer to notify
  8429. * @param eventData defines the data to be sent to each callback
  8430. * @param mask is used to filter observers defaults to -1
  8431. */
  8432. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8433. if (mask === void 0) { mask = -1; }
  8434. var state = this._eventState;
  8435. state.mask = mask;
  8436. state.skipNextObservers = false;
  8437. observer.callback(eventData, state);
  8438. };
  8439. /**
  8440. * Gets a boolean indicating if the observable has at least one observer
  8441. * @returns true is the Observable has at least one Observer registered
  8442. */
  8443. Observable.prototype.hasObservers = function () {
  8444. return this._observers.length > 0;
  8445. };
  8446. /**
  8447. * Clear the list of observers
  8448. */
  8449. Observable.prototype.clear = function () {
  8450. this._observers = new Array();
  8451. this._onObserverAdded = null;
  8452. };
  8453. /**
  8454. * Clone the current observable
  8455. * @returns a new observable
  8456. */
  8457. Observable.prototype.clone = function () {
  8458. var result = new Observable();
  8459. result._observers = this._observers.slice(0);
  8460. return result;
  8461. };
  8462. /**
  8463. * Does this observable handles observer registered with a given mask
  8464. * @param mask defines the mask to be tested
  8465. * @return whether or not one observer registered with the given mask is handeled
  8466. **/
  8467. Observable.prototype.hasSpecificMask = function (mask) {
  8468. if (mask === void 0) { mask = -1; }
  8469. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8470. var obs = _a[_i];
  8471. if (obs.mask & mask || obs.mask === mask) {
  8472. return true;
  8473. }
  8474. }
  8475. return false;
  8476. };
  8477. return Observable;
  8478. }());
  8479. BABYLON.Observable = Observable;
  8480. })(BABYLON || (BABYLON = {}));
  8481. //# sourceMappingURL=babylon.observable.js.map
  8482. var BABYLON;
  8483. (function (BABYLON) {
  8484. /**
  8485. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8486. */
  8487. var SmartArray = /** @class */ (function () {
  8488. /**
  8489. * Instantiates a Smart Array.
  8490. * @param capacity defines the default capacity of the array.
  8491. */
  8492. function SmartArray(capacity) {
  8493. /**
  8494. * The active length of the array.
  8495. */
  8496. this.length = 0;
  8497. this.data = new Array(capacity);
  8498. this._id = SmartArray._GlobalId++;
  8499. }
  8500. /**
  8501. * Pushes a value at the end of the active data.
  8502. * @param value defines the object to push in the array.
  8503. */
  8504. SmartArray.prototype.push = function (value) {
  8505. this.data[this.length++] = value;
  8506. if (this.length > this.data.length) {
  8507. this.data.length *= 2;
  8508. }
  8509. };
  8510. /**
  8511. * Iterates over the active data and apply the lambda to them.
  8512. * @param func defines the action to apply on each value.
  8513. */
  8514. SmartArray.prototype.forEach = function (func) {
  8515. for (var index = 0; index < this.length; index++) {
  8516. func(this.data[index]);
  8517. }
  8518. };
  8519. /**
  8520. * Sorts the full sets of data.
  8521. * @param compareFn defines the comparison function to apply.
  8522. */
  8523. SmartArray.prototype.sort = function (compareFn) {
  8524. this.data.sort(compareFn);
  8525. };
  8526. /**
  8527. * Resets the active data to an empty array.
  8528. */
  8529. SmartArray.prototype.reset = function () {
  8530. this.length = 0;
  8531. };
  8532. /**
  8533. * Releases all the data from the array as well as the array.
  8534. */
  8535. SmartArray.prototype.dispose = function () {
  8536. this.reset();
  8537. if (this.data) {
  8538. this.data.length = 0;
  8539. this.data = [];
  8540. }
  8541. };
  8542. /**
  8543. * Concats the active data with a given array.
  8544. * @param array defines the data to concatenate with.
  8545. */
  8546. SmartArray.prototype.concat = function (array) {
  8547. if (array.length === 0) {
  8548. return;
  8549. }
  8550. if (this.length + array.length > this.data.length) {
  8551. this.data.length = (this.length + array.length) * 2;
  8552. }
  8553. for (var index = 0; index < array.length; index++) {
  8554. this.data[this.length++] = (array.data || array)[index];
  8555. }
  8556. };
  8557. /**
  8558. * Returns the position of a value in the active data.
  8559. * @param value defines the value to find the index for
  8560. * @returns the index if found in the active data otherwise -1
  8561. */
  8562. SmartArray.prototype.indexOf = function (value) {
  8563. var position = this.data.indexOf(value);
  8564. if (position >= this.length) {
  8565. return -1;
  8566. }
  8567. return position;
  8568. };
  8569. /**
  8570. * Returns whether an element is part of the active data.
  8571. * @param value defines the value to look for
  8572. * @returns true if found in the active data otherwise false
  8573. */
  8574. SmartArray.prototype.contains = function (value) {
  8575. return this.indexOf(value) !== -1;
  8576. };
  8577. // Statics
  8578. SmartArray._GlobalId = 0;
  8579. return SmartArray;
  8580. }());
  8581. BABYLON.SmartArray = SmartArray;
  8582. /**
  8583. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8584. * The data in this array can only be present once
  8585. */
  8586. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8587. __extends(SmartArrayNoDuplicate, _super);
  8588. function SmartArrayNoDuplicate() {
  8589. var _this = _super !== null && _super.apply(this, arguments) || this;
  8590. _this._duplicateId = 0;
  8591. return _this;
  8592. }
  8593. /**
  8594. * Pushes a value at the end of the active data.
  8595. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8596. * @param value defines the object to push in the array.
  8597. */
  8598. SmartArrayNoDuplicate.prototype.push = function (value) {
  8599. _super.prototype.push.call(this, value);
  8600. if (!value.__smartArrayFlags) {
  8601. value.__smartArrayFlags = {};
  8602. }
  8603. value.__smartArrayFlags[this._id] = this._duplicateId;
  8604. };
  8605. /**
  8606. * Pushes a value at the end of the active data.
  8607. * If the data is already present, it won t be added again
  8608. * @param value defines the object to push in the array.
  8609. * @returns true if added false if it was already present
  8610. */
  8611. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8612. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8613. return false;
  8614. }
  8615. this.push(value);
  8616. return true;
  8617. };
  8618. /**
  8619. * Resets the active data to an empty array.
  8620. */
  8621. SmartArrayNoDuplicate.prototype.reset = function () {
  8622. _super.prototype.reset.call(this);
  8623. this._duplicateId++;
  8624. };
  8625. /**
  8626. * Concats the active data with a given array.
  8627. * This ensures no dupplicate will be present in the result.
  8628. * @param array defines the data to concatenate with.
  8629. */
  8630. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8631. if (array.length === 0) {
  8632. return;
  8633. }
  8634. if (this.length + array.length > this.data.length) {
  8635. this.data.length = (this.length + array.length) * 2;
  8636. }
  8637. for (var index = 0; index < array.length; index++) {
  8638. var item = (array.data || array)[index];
  8639. this.pushNoDuplicate(item);
  8640. }
  8641. };
  8642. return SmartArrayNoDuplicate;
  8643. }(SmartArray));
  8644. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8645. })(BABYLON || (BABYLON = {}));
  8646. //# sourceMappingURL=babylon.smartArray.js.map
  8647. var BABYLON;
  8648. (function (BABYLON) {
  8649. /** Class used to store color gradient */
  8650. var ColorGradient = /** @class */ (function () {
  8651. function ColorGradient() {
  8652. }
  8653. /**
  8654. * Will get a color picked randomly between color1 and color2.
  8655. * If color2 is undefined then color1 will be used
  8656. * @param result defines the target Color4 to store the result in
  8657. */
  8658. ColorGradient.prototype.getColorToRef = function (result) {
  8659. if (!this.color2) {
  8660. result.copyFrom(this.color1);
  8661. return;
  8662. }
  8663. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8664. };
  8665. return ColorGradient;
  8666. }());
  8667. BABYLON.ColorGradient = ColorGradient;
  8668. /** Class used to store factor gradient */
  8669. var FactorGradient = /** @class */ (function () {
  8670. function FactorGradient() {
  8671. }
  8672. /**
  8673. * Will get a number picked randomly between factor1 and factor2.
  8674. * If factor2 is undefined then factor1 will be used
  8675. * @returns the picked number
  8676. */
  8677. FactorGradient.prototype.getFactor = function () {
  8678. if (this.factor2 === undefined) {
  8679. return this.factor1;
  8680. }
  8681. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8682. };
  8683. return FactorGradient;
  8684. }());
  8685. BABYLON.FactorGradient = FactorGradient;
  8686. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8687. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8688. var LoadFileError = /** @class */ (function (_super) {
  8689. __extends(LoadFileError, _super);
  8690. function LoadFileError(message, request) {
  8691. var _this = _super.call(this, message) || this;
  8692. _this.request = request;
  8693. _this.name = "LoadFileError";
  8694. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8695. return _this;
  8696. }
  8697. // Polyfill for Object.setPrototypeOf if necessary.
  8698. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8699. return LoadFileError;
  8700. }(Error));
  8701. BABYLON.LoadFileError = LoadFileError;
  8702. var RetryStrategy = /** @class */ (function () {
  8703. function RetryStrategy() {
  8704. }
  8705. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8706. if (maxRetries === void 0) { maxRetries = 3; }
  8707. if (baseInterval === void 0) { baseInterval = 500; }
  8708. return function (url, request, retryIndex) {
  8709. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8710. return -1;
  8711. }
  8712. return Math.pow(2, retryIndex) * baseInterval;
  8713. };
  8714. };
  8715. return RetryStrategy;
  8716. }());
  8717. BABYLON.RetryStrategy = RetryStrategy;
  8718. // Screenshots
  8719. var screenshotCanvas;
  8720. var cloneValue = function (source, destinationObject) {
  8721. if (!source)
  8722. return null;
  8723. if (source instanceof BABYLON.Mesh) {
  8724. return null;
  8725. }
  8726. if (source instanceof BABYLON.SubMesh) {
  8727. return source.clone(destinationObject);
  8728. }
  8729. else if (source.clone) {
  8730. return source.clone();
  8731. }
  8732. return null;
  8733. };
  8734. var Tools = /** @class */ (function () {
  8735. function Tools() {
  8736. }
  8737. /**
  8738. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8739. * @param u defines the coordinate on X axis
  8740. * @param v defines the coordinate on Y axis
  8741. * @param width defines the width of the source data
  8742. * @param height defines the height of the source data
  8743. * @param pixels defines the source byte array
  8744. * @param color defines the output color
  8745. */
  8746. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8747. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8748. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8749. var position = (wrappedU + wrappedV * width) * 4;
  8750. color.r = pixels[position] / 255;
  8751. color.g = pixels[position + 1] / 255;
  8752. color.b = pixels[position + 2] / 255;
  8753. color.a = pixels[position + 3] / 255;
  8754. };
  8755. /**
  8756. * Interpolates between a and b via alpha
  8757. * @param a The lower value (returned when alpha = 0)
  8758. * @param b The upper value (returned when alpha = 1)
  8759. * @param alpha The interpolation-factor
  8760. * @return The mixed value
  8761. */
  8762. Tools.Mix = function (a, b, alpha) {
  8763. return a * (1 - alpha) + b * alpha;
  8764. };
  8765. Tools.Instantiate = function (className) {
  8766. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8767. return Tools.RegisteredExternalClasses[className];
  8768. }
  8769. var arr = className.split(".");
  8770. var fn = (window || this);
  8771. for (var i = 0, len = arr.length; i < len; i++) {
  8772. fn = fn[arr[i]];
  8773. }
  8774. if (typeof fn !== "function") {
  8775. return null;
  8776. }
  8777. return fn;
  8778. };
  8779. /**
  8780. * Provides a slice function that will work even on IE
  8781. * @param data defines the array to slice
  8782. * @param start defines the start of the data (optional)
  8783. * @param end defines the end of the data (optional)
  8784. * @returns the new sliced array
  8785. */
  8786. Tools.Slice = function (data, start, end) {
  8787. if (data.slice) {
  8788. return data.slice(start, end);
  8789. }
  8790. return Array.prototype.slice.call(data, start, end);
  8791. };
  8792. Tools.SetImmediate = function (action) {
  8793. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8794. window.setImmediate(action);
  8795. }
  8796. else {
  8797. setTimeout(action, 1);
  8798. }
  8799. };
  8800. Tools.IsExponentOfTwo = function (value) {
  8801. var count = 1;
  8802. do {
  8803. count *= 2;
  8804. } while (count < value);
  8805. return count === value;
  8806. };
  8807. /**
  8808. * Returns the nearest 32-bit single precision float representation of a Number
  8809. * @param value A Number. If the parameter is of a different type, it will get converted
  8810. * to a number or to NaN if it cannot be converted
  8811. * @returns number
  8812. */
  8813. Tools.FloatRound = function (value) {
  8814. if (Math.fround) {
  8815. return Math.fround(value);
  8816. }
  8817. return (Tools._tmpFloatArray[0] = value);
  8818. };
  8819. /**
  8820. * Find the next highest power of two.
  8821. * @param x Number to start search from.
  8822. * @return Next highest power of two.
  8823. */
  8824. Tools.CeilingPOT = function (x) {
  8825. x--;
  8826. x |= x >> 1;
  8827. x |= x >> 2;
  8828. x |= x >> 4;
  8829. x |= x >> 8;
  8830. x |= x >> 16;
  8831. x++;
  8832. return x;
  8833. };
  8834. /**
  8835. * Find the next lowest power of two.
  8836. * @param x Number to start search from.
  8837. * @return Next lowest power of two.
  8838. */
  8839. Tools.FloorPOT = function (x) {
  8840. x = x | (x >> 1);
  8841. x = x | (x >> 2);
  8842. x = x | (x >> 4);
  8843. x = x | (x >> 8);
  8844. x = x | (x >> 16);
  8845. return x - (x >> 1);
  8846. };
  8847. /**
  8848. * Find the nearest power of two.
  8849. * @param x Number to start search from.
  8850. * @return Next nearest power of two.
  8851. */
  8852. Tools.NearestPOT = function (x) {
  8853. var c = Tools.CeilingPOT(x);
  8854. var f = Tools.FloorPOT(x);
  8855. return (c - x) > (x - f) ? f : c;
  8856. };
  8857. Tools.GetExponentOfTwo = function (value, max, mode) {
  8858. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8859. var pot;
  8860. switch (mode) {
  8861. case BABYLON.Engine.SCALEMODE_FLOOR:
  8862. pot = Tools.FloorPOT(value);
  8863. break;
  8864. case BABYLON.Engine.SCALEMODE_NEAREST:
  8865. pot = Tools.NearestPOT(value);
  8866. break;
  8867. case BABYLON.Engine.SCALEMODE_CEILING:
  8868. default:
  8869. pot = Tools.CeilingPOT(value);
  8870. break;
  8871. }
  8872. return Math.min(pot, max);
  8873. };
  8874. Tools.GetFilename = function (path) {
  8875. var index = path.lastIndexOf("/");
  8876. if (index < 0)
  8877. return path;
  8878. return path.substring(index + 1);
  8879. };
  8880. /**
  8881. * Extracts the "folder" part of a path (everything before the filename).
  8882. * @param uri The URI to extract the info from
  8883. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8884. * @returns The "folder" part of the path
  8885. */
  8886. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8887. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8888. var index = uri.lastIndexOf("/");
  8889. if (index < 0) {
  8890. if (returnUnchangedIfNoSlash) {
  8891. return uri;
  8892. }
  8893. return "";
  8894. }
  8895. return uri.substring(0, index + 1);
  8896. };
  8897. Tools.GetDOMTextContent = function (element) {
  8898. var result = "";
  8899. var child = element.firstChild;
  8900. while (child) {
  8901. if (child.nodeType === 3) {
  8902. result += child.textContent;
  8903. }
  8904. child = child.nextSibling;
  8905. }
  8906. return result;
  8907. };
  8908. Tools.ToDegrees = function (angle) {
  8909. return angle * 180 / Math.PI;
  8910. };
  8911. Tools.ToRadians = function (angle) {
  8912. return angle * Math.PI / 180;
  8913. };
  8914. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8915. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8916. var output = "";
  8917. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8918. var i = 0;
  8919. var bytes = new Uint8Array(buffer);
  8920. while (i < bytes.length) {
  8921. chr1 = bytes[i++];
  8922. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8923. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8924. enc1 = chr1 >> 2;
  8925. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8926. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8927. enc4 = chr3 & 63;
  8928. if (isNaN(chr2)) {
  8929. enc3 = enc4 = 64;
  8930. }
  8931. else if (isNaN(chr3)) {
  8932. enc4 = 64;
  8933. }
  8934. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8935. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8936. }
  8937. return "data:image/png;base64," + output;
  8938. };
  8939. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8940. if (bias === void 0) { bias = null; }
  8941. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8942. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8943. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8944. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8945. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8946. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8947. }
  8948. if (bias) {
  8949. minimum.x -= minimum.x * bias.x + bias.y;
  8950. minimum.y -= minimum.y * bias.x + bias.y;
  8951. minimum.z -= minimum.z * bias.x + bias.y;
  8952. maximum.x += maximum.x * bias.x + bias.y;
  8953. maximum.y += maximum.y * bias.x + bias.y;
  8954. maximum.z += maximum.z * bias.x + bias.y;
  8955. }
  8956. return {
  8957. minimum: minimum,
  8958. maximum: maximum
  8959. };
  8960. };
  8961. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8962. if (bias === void 0) { bias = null; }
  8963. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8964. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8965. if (!stride) {
  8966. stride = 3;
  8967. }
  8968. for (var index = start; index < start + count; index++) {
  8969. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8970. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8971. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8972. }
  8973. if (bias) {
  8974. minimum.x -= minimum.x * bias.x + bias.y;
  8975. minimum.y -= minimum.y * bias.x + bias.y;
  8976. minimum.z -= minimum.z * bias.x + bias.y;
  8977. maximum.x += maximum.x * bias.x + bias.y;
  8978. maximum.y += maximum.y * bias.x + bias.y;
  8979. maximum.z += maximum.z * bias.x + bias.y;
  8980. }
  8981. return {
  8982. minimum: minimum,
  8983. maximum: maximum
  8984. };
  8985. };
  8986. Tools.Vector2ArrayFeeder = function (array) {
  8987. return function (index) {
  8988. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8989. var length = isFloatArray ? array.length / 2 : array.length;
  8990. if (index >= length) {
  8991. return null;
  8992. }
  8993. if (isFloatArray) {
  8994. var fa = array;
  8995. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8996. }
  8997. var a = array;
  8998. return a[index];
  8999. };
  9000. };
  9001. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9002. if (bias === void 0) { bias = null; }
  9003. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9004. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9005. var i = 0;
  9006. var cur = feeder(i++);
  9007. while (cur) {
  9008. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9009. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9010. cur = feeder(i++);
  9011. }
  9012. if (bias) {
  9013. minimum.x -= minimum.x * bias.x + bias.y;
  9014. minimum.y -= minimum.y * bias.x + bias.y;
  9015. maximum.x += maximum.x * bias.x + bias.y;
  9016. maximum.y += maximum.y * bias.x + bias.y;
  9017. }
  9018. return {
  9019. minimum: minimum,
  9020. maximum: maximum
  9021. };
  9022. };
  9023. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9024. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9025. return null;
  9026. return Array.isArray(obj) ? obj : [obj];
  9027. };
  9028. // Misc.
  9029. Tools.GetPointerPrefix = function () {
  9030. var eventPrefix = "pointer";
  9031. // Check if pointer events are supported
  9032. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9033. eventPrefix = "mouse";
  9034. }
  9035. return eventPrefix;
  9036. };
  9037. /**
  9038. * @param func - the function to be called
  9039. * @param requester - the object that will request the next frame. Falls back to window.
  9040. */
  9041. Tools.QueueNewFrame = function (func, requester) {
  9042. if (!Tools.IsWindowObjectExist()) {
  9043. return setTimeout(func, 16);
  9044. }
  9045. if (!requester) {
  9046. requester = window;
  9047. }
  9048. if (requester.requestAnimationFrame) {
  9049. return requester.requestAnimationFrame(func);
  9050. }
  9051. else if (requester.msRequestAnimationFrame) {
  9052. return requester.msRequestAnimationFrame(func);
  9053. }
  9054. else if (requester.webkitRequestAnimationFrame) {
  9055. return requester.webkitRequestAnimationFrame(func);
  9056. }
  9057. else if (requester.mozRequestAnimationFrame) {
  9058. return requester.mozRequestAnimationFrame(func);
  9059. }
  9060. else if (requester.oRequestAnimationFrame) {
  9061. return requester.oRequestAnimationFrame(func);
  9062. }
  9063. else {
  9064. return window.setTimeout(func, 16);
  9065. }
  9066. };
  9067. Tools.RequestFullscreen = function (element) {
  9068. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9069. if (!requestFunction)
  9070. return;
  9071. requestFunction.call(element);
  9072. };
  9073. Tools.ExitFullscreen = function () {
  9074. if (document.exitFullscreen) {
  9075. document.exitFullscreen();
  9076. }
  9077. else if (document.mozCancelFullScreen) {
  9078. document.mozCancelFullScreen();
  9079. }
  9080. else if (document.webkitCancelFullScreen) {
  9081. document.webkitCancelFullScreen();
  9082. }
  9083. else if (document.msCancelFullScreen) {
  9084. document.msCancelFullScreen();
  9085. }
  9086. };
  9087. Tools.SetCorsBehavior = function (url, element) {
  9088. if (url && url.indexOf("data:") === 0) {
  9089. return;
  9090. }
  9091. if (Tools.CorsBehavior) {
  9092. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9093. element.crossOrigin = Tools.CorsBehavior;
  9094. }
  9095. else {
  9096. var result = Tools.CorsBehavior(url);
  9097. if (result) {
  9098. element.crossOrigin = result;
  9099. }
  9100. }
  9101. }
  9102. };
  9103. // External files
  9104. Tools.CleanUrl = function (url) {
  9105. url = url.replace(/#/mg, "%23");
  9106. return url;
  9107. };
  9108. /**
  9109. * Loads an image as an HTMLImageElement.
  9110. * @param input url string, ArrayBuffer, or Blob to load
  9111. * @param onLoad callback called when the image successfully loads
  9112. * @param onError callback called when the image fails to load
  9113. * @param database database for caching
  9114. * @returns the HTMLImageElement of the loaded image
  9115. */
  9116. Tools.LoadImage = function (input, onLoad, onError, database) {
  9117. var url;
  9118. var usingObjectURL = false;
  9119. if (input instanceof ArrayBuffer) {
  9120. url = URL.createObjectURL(new Blob([input]));
  9121. usingObjectURL = true;
  9122. }
  9123. else if (input instanceof Blob) {
  9124. url = URL.createObjectURL(input);
  9125. usingObjectURL = true;
  9126. }
  9127. else {
  9128. url = Tools.CleanUrl(input);
  9129. url = Tools.PreprocessUrl(input);
  9130. }
  9131. var img = new Image();
  9132. Tools.SetCorsBehavior(url, img);
  9133. var loadHandler = function () {
  9134. if (usingObjectURL && img.src) {
  9135. URL.revokeObjectURL(img.src);
  9136. }
  9137. img.removeEventListener("load", loadHandler);
  9138. img.removeEventListener("error", errorHandler);
  9139. onLoad(img);
  9140. };
  9141. var errorHandler = function (err) {
  9142. if (usingObjectURL && img.src) {
  9143. URL.revokeObjectURL(img.src);
  9144. }
  9145. img.removeEventListener("load", loadHandler);
  9146. img.removeEventListener("error", errorHandler);
  9147. Tools.Error("Error while trying to load image: " + input);
  9148. if (onError) {
  9149. onError("Error while trying to load image: " + input, err);
  9150. }
  9151. };
  9152. img.addEventListener("load", loadHandler);
  9153. img.addEventListener("error", errorHandler);
  9154. var noIndexedDB = function () {
  9155. img.src = url;
  9156. };
  9157. var loadFromIndexedDB = function () {
  9158. if (database) {
  9159. database.loadImageFromDB(url, img);
  9160. }
  9161. };
  9162. //ANY database to do!
  9163. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9164. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9165. }
  9166. else {
  9167. if (url.indexOf("file:") !== -1) {
  9168. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9169. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9170. try {
  9171. var blobURL;
  9172. try {
  9173. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9174. }
  9175. catch (ex) {
  9176. // Chrome doesn't support oneTimeOnly parameter
  9177. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9178. }
  9179. img.src = blobURL;
  9180. usingObjectURL = true;
  9181. }
  9182. catch (e) {
  9183. img.src = "";
  9184. }
  9185. return img;
  9186. }
  9187. }
  9188. noIndexedDB();
  9189. }
  9190. return img;
  9191. };
  9192. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9193. url = Tools.CleanUrl(url);
  9194. url = Tools.PreprocessUrl(url);
  9195. // If file and file input are set
  9196. if (url.indexOf("file:") !== -1) {
  9197. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9198. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9199. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9200. }
  9201. }
  9202. var loadUrl = Tools.BaseUrl + url;
  9203. var aborted = false;
  9204. var fileRequest = {
  9205. onCompleteObservable: new BABYLON.Observable(),
  9206. abort: function () { return aborted = true; },
  9207. };
  9208. var requestFile = function () {
  9209. var request = new XMLHttpRequest();
  9210. var retryHandle = null;
  9211. fileRequest.abort = function () {
  9212. aborted = true;
  9213. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9214. request.abort();
  9215. }
  9216. if (retryHandle !== null) {
  9217. clearTimeout(retryHandle);
  9218. retryHandle = null;
  9219. }
  9220. };
  9221. var retryLoop = function (retryIndex) {
  9222. request.open('GET', loadUrl, true);
  9223. if (useArrayBuffer) {
  9224. request.responseType = "arraybuffer";
  9225. }
  9226. if (onProgress) {
  9227. request.addEventListener("progress", onProgress);
  9228. }
  9229. var onLoadEnd = function () {
  9230. request.removeEventListener("loadend", onLoadEnd);
  9231. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9232. fileRequest.onCompleteObservable.clear();
  9233. };
  9234. request.addEventListener("loadend", onLoadEnd);
  9235. var onReadyStateChange = function () {
  9236. if (aborted) {
  9237. return;
  9238. }
  9239. // In case of undefined state in some browsers.
  9240. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9241. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9242. request.removeEventListener("readystatechange", onReadyStateChange);
  9243. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9244. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9245. return;
  9246. }
  9247. var retryStrategy = Tools.DefaultRetryStrategy;
  9248. if (retryStrategy) {
  9249. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9250. if (waitTime !== -1) {
  9251. // Prevent the request from completing for retry.
  9252. request.removeEventListener("loadend", onLoadEnd);
  9253. request = new XMLHttpRequest();
  9254. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9255. return;
  9256. }
  9257. }
  9258. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9259. if (onError) {
  9260. onError(request, e);
  9261. }
  9262. else {
  9263. throw e;
  9264. }
  9265. }
  9266. };
  9267. request.addEventListener("readystatechange", onReadyStateChange);
  9268. request.send();
  9269. };
  9270. retryLoop(0);
  9271. };
  9272. // Caching all files
  9273. if (database && database.enableSceneOffline) {
  9274. var noIndexedDB_1 = function (request) {
  9275. if (request && request.status > 400) {
  9276. if (onError) {
  9277. onError(request);
  9278. }
  9279. }
  9280. else {
  9281. if (!aborted) {
  9282. requestFile();
  9283. }
  9284. }
  9285. };
  9286. var loadFromIndexedDB = function () {
  9287. // TODO: database needs to support aborting and should return a IFileRequest
  9288. if (aborted) {
  9289. return;
  9290. }
  9291. if (database) {
  9292. database.loadFileFromDB(url, function (data) {
  9293. if (!aborted) {
  9294. onSuccess(data);
  9295. }
  9296. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9297. }, onProgress ? function (event) {
  9298. if (!aborted) {
  9299. onProgress(event);
  9300. }
  9301. } : undefined, noIndexedDB_1, useArrayBuffer);
  9302. }
  9303. };
  9304. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9305. }
  9306. else {
  9307. requestFile();
  9308. }
  9309. return fileRequest;
  9310. };
  9311. /**
  9312. * Load a script (identified by an url). When the url returns, the
  9313. * content of this file is added into a new script element, attached to the DOM (body element)
  9314. */
  9315. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9316. if (!Tools.IsWindowObjectExist()) {
  9317. return;
  9318. }
  9319. var head = document.getElementsByTagName('head')[0];
  9320. var script = document.createElement('script');
  9321. script.type = 'text/javascript';
  9322. script.src = scriptUrl;
  9323. script.onload = function () {
  9324. if (onSuccess) {
  9325. onSuccess();
  9326. }
  9327. };
  9328. script.onerror = function (e) {
  9329. if (onError) {
  9330. onError("Unable to load script '" + scriptUrl + "'", e);
  9331. }
  9332. };
  9333. head.appendChild(script);
  9334. };
  9335. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9336. var reader = new FileReader();
  9337. var request = {
  9338. onCompleteObservable: new BABYLON.Observable(),
  9339. abort: function () { return reader.abort(); },
  9340. };
  9341. reader.onloadend = function (e) {
  9342. request.onCompleteObservable.notifyObservers(request);
  9343. };
  9344. reader.onload = function (e) {
  9345. //target doesn't have result from ts 1.3
  9346. callback(e.target['result']);
  9347. };
  9348. reader.onprogress = progressCallback;
  9349. reader.readAsDataURL(fileToLoad);
  9350. return request;
  9351. };
  9352. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9353. var reader = new FileReader();
  9354. var request = {
  9355. onCompleteObservable: new BABYLON.Observable(),
  9356. abort: function () { return reader.abort(); },
  9357. };
  9358. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9359. reader.onerror = function (e) {
  9360. Tools.Log("Error while reading file: " + fileToLoad.name);
  9361. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9362. };
  9363. reader.onload = function (e) {
  9364. //target doesn't have result from ts 1.3
  9365. callback(e.target['result']);
  9366. };
  9367. if (progressCallBack) {
  9368. reader.onprogress = progressCallBack;
  9369. }
  9370. if (!useArrayBuffer) {
  9371. // Asynchronous read
  9372. reader.readAsText(fileToLoad);
  9373. }
  9374. else {
  9375. reader.readAsArrayBuffer(fileToLoad);
  9376. }
  9377. return request;
  9378. };
  9379. //returns a downloadable url to a file content.
  9380. Tools.FileAsURL = function (content) {
  9381. var fileBlob = new Blob([content]);
  9382. var url = window.URL || window.webkitURL;
  9383. var link = url.createObjectURL(fileBlob);
  9384. return link;
  9385. };
  9386. // Misc.
  9387. Tools.Format = function (value, decimals) {
  9388. if (decimals === void 0) { decimals = 2; }
  9389. return value.toFixed(decimals);
  9390. };
  9391. Tools.CheckExtends = function (v, min, max) {
  9392. if (v.x < min.x)
  9393. min.x = v.x;
  9394. if (v.y < min.y)
  9395. min.y = v.y;
  9396. if (v.z < min.z)
  9397. min.z = v.z;
  9398. if (v.x > max.x)
  9399. max.x = v.x;
  9400. if (v.y > max.y)
  9401. max.y = v.y;
  9402. if (v.z > max.z)
  9403. max.z = v.z;
  9404. };
  9405. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9406. for (var prop in source) {
  9407. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9408. continue;
  9409. }
  9410. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9411. continue;
  9412. }
  9413. var sourceValue = source[prop];
  9414. var typeOfSourceValue = typeof sourceValue;
  9415. if (typeOfSourceValue === "function") {
  9416. continue;
  9417. }
  9418. try {
  9419. if (typeOfSourceValue === "object") {
  9420. if (sourceValue instanceof Array) {
  9421. destination[prop] = [];
  9422. if (sourceValue.length > 0) {
  9423. if (typeof sourceValue[0] == "object") {
  9424. for (var index = 0; index < sourceValue.length; index++) {
  9425. var clonedValue = cloneValue(sourceValue[index], destination);
  9426. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9427. destination[prop].push(clonedValue);
  9428. }
  9429. }
  9430. }
  9431. else {
  9432. destination[prop] = sourceValue.slice(0);
  9433. }
  9434. }
  9435. }
  9436. else {
  9437. destination[prop] = cloneValue(sourceValue, destination);
  9438. }
  9439. }
  9440. else {
  9441. destination[prop] = sourceValue;
  9442. }
  9443. }
  9444. catch (e) {
  9445. // Just ignore error (it could be because of a read-only property)
  9446. }
  9447. }
  9448. };
  9449. Tools.IsEmpty = function (obj) {
  9450. for (var i in obj) {
  9451. if (obj.hasOwnProperty(i)) {
  9452. return false;
  9453. }
  9454. }
  9455. return true;
  9456. };
  9457. Tools.RegisterTopRootEvents = function (events) {
  9458. for (var index = 0; index < events.length; index++) {
  9459. var event = events[index];
  9460. window.addEventListener(event.name, event.handler, false);
  9461. try {
  9462. if (window.parent) {
  9463. window.parent.addEventListener(event.name, event.handler, false);
  9464. }
  9465. }
  9466. catch (e) {
  9467. // Silently fails...
  9468. }
  9469. }
  9470. };
  9471. Tools.UnregisterTopRootEvents = function (events) {
  9472. for (var index = 0; index < events.length; index++) {
  9473. var event = events[index];
  9474. window.removeEventListener(event.name, event.handler);
  9475. try {
  9476. if (window.parent) {
  9477. window.parent.removeEventListener(event.name, event.handler);
  9478. }
  9479. }
  9480. catch (e) {
  9481. // Silently fails...
  9482. }
  9483. }
  9484. };
  9485. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9486. if (mimeType === void 0) { mimeType = "image/png"; }
  9487. // Read the contents of the framebuffer
  9488. var numberOfChannelsByLine = width * 4;
  9489. var halfHeight = height / 2;
  9490. //Reading datas from WebGL
  9491. var data = engine.readPixels(0, 0, width, height);
  9492. //To flip image on Y axis.
  9493. for (var i = 0; i < halfHeight; i++) {
  9494. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9495. var currentCell = j + i * numberOfChannelsByLine;
  9496. var targetLine = height - i - 1;
  9497. var targetCell = j + targetLine * numberOfChannelsByLine;
  9498. var temp = data[currentCell];
  9499. data[currentCell] = data[targetCell];
  9500. data[targetCell] = temp;
  9501. }
  9502. }
  9503. // Create a 2D canvas to store the result
  9504. if (!screenshotCanvas) {
  9505. screenshotCanvas = document.createElement('canvas');
  9506. }
  9507. screenshotCanvas.width = width;
  9508. screenshotCanvas.height = height;
  9509. var context = screenshotCanvas.getContext('2d');
  9510. if (context) {
  9511. // Copy the pixels to a 2D canvas
  9512. var imageData = context.createImageData(width, height);
  9513. var castData = (imageData.data);
  9514. castData.set(data);
  9515. context.putImageData(imageData, 0, 0);
  9516. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9517. }
  9518. };
  9519. /**
  9520. * Converts the canvas data to blob.
  9521. * This acts as a polyfill for browsers not supporting the to blob function.
  9522. * @param canvas Defines the canvas to extract the data from
  9523. * @param successCallback Defines the callback triggered once the data are available
  9524. * @param mimeType Defines the mime type of the result
  9525. */
  9526. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9527. if (mimeType === void 0) { mimeType = "image/png"; }
  9528. // We need HTMLCanvasElement.toBlob for HD screenshots
  9529. if (!canvas.toBlob) {
  9530. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9531. canvas.toBlob = function (callback, type, quality) {
  9532. var _this = this;
  9533. setTimeout(function () {
  9534. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9535. for (var i = 0; i < len; i++) {
  9536. arr[i] = binStr.charCodeAt(i);
  9537. }
  9538. callback(new Blob([arr]));
  9539. });
  9540. };
  9541. }
  9542. canvas.toBlob(function (blob) {
  9543. successCallback(blob);
  9544. }, mimeType);
  9545. };
  9546. /**
  9547. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9548. * @param successCallback Defines the callback triggered once the data are available
  9549. * @param mimeType Defines the mime type of the result
  9550. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9551. */
  9552. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9553. if (mimeType === void 0) { mimeType = "image/png"; }
  9554. if (successCallback) {
  9555. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9556. successCallback(base64Image);
  9557. }
  9558. else {
  9559. this.ToBlob(screenshotCanvas, function (blob) {
  9560. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9561. if (("download" in document.createElement("a"))) {
  9562. if (!fileName) {
  9563. var date = new Date();
  9564. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9565. fileName = "screenshot_" + stringDate + ".png";
  9566. }
  9567. Tools.Download(blob, fileName);
  9568. }
  9569. else {
  9570. var url = URL.createObjectURL(blob);
  9571. var newWindow = window.open("");
  9572. if (!newWindow)
  9573. return;
  9574. var img = newWindow.document.createElement("img");
  9575. img.onload = function () {
  9576. // no longer need to read the blob so it's revoked
  9577. URL.revokeObjectURL(url);
  9578. };
  9579. img.src = url;
  9580. newWindow.document.body.appendChild(img);
  9581. }
  9582. }, mimeType);
  9583. }
  9584. };
  9585. /**
  9586. * Downloads a blob in the browser
  9587. * @param blob defines the blob to download
  9588. * @param fileName defines the name of the downloaded file
  9589. */
  9590. Tools.Download = function (blob, fileName) {
  9591. if (navigator && navigator.msSaveBlob) {
  9592. navigator.msSaveBlob(blob, fileName);
  9593. return;
  9594. }
  9595. var url = window.URL.createObjectURL(blob);
  9596. var a = document.createElement("a");
  9597. document.body.appendChild(a);
  9598. a.style.display = "none";
  9599. a.href = url;
  9600. a.download = fileName;
  9601. a.addEventListener("click", function () {
  9602. if (a.parentElement) {
  9603. a.parentElement.removeChild(a);
  9604. }
  9605. });
  9606. a.click();
  9607. window.URL.revokeObjectURL(url);
  9608. };
  9609. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9610. if (mimeType === void 0) { mimeType = "image/png"; }
  9611. var width;
  9612. var height;
  9613. // If a precision value is specified
  9614. if (size.precision) {
  9615. width = Math.round(engine.getRenderWidth() * size.precision);
  9616. height = Math.round(width / engine.getAspectRatio(camera));
  9617. }
  9618. else if (size.width && size.height) {
  9619. width = size.width;
  9620. height = size.height;
  9621. }
  9622. //If passing only width, computing height to keep display canvas ratio.
  9623. else if (size.width && !size.height) {
  9624. width = size.width;
  9625. height = Math.round(width / engine.getAspectRatio(camera));
  9626. }
  9627. //If passing only height, computing width to keep display canvas ratio.
  9628. else if (size.height && !size.width) {
  9629. height = size.height;
  9630. width = Math.round(height * engine.getAspectRatio(camera));
  9631. }
  9632. //Assuming here that "size" parameter is a number
  9633. else if (!isNaN(size)) {
  9634. height = size;
  9635. width = size;
  9636. }
  9637. else {
  9638. Tools.Error("Invalid 'size' parameter !");
  9639. return;
  9640. }
  9641. if (!screenshotCanvas) {
  9642. screenshotCanvas = document.createElement('canvas');
  9643. }
  9644. screenshotCanvas.width = width;
  9645. screenshotCanvas.height = height;
  9646. var renderContext = screenshotCanvas.getContext("2d");
  9647. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9648. var newWidth = width;
  9649. var newHeight = newWidth / ratio;
  9650. if (newHeight > height) {
  9651. newHeight = height;
  9652. newWidth = newHeight * ratio;
  9653. }
  9654. var offsetX = Math.max(0, width - newWidth) / 2;
  9655. var offsetY = Math.max(0, height - newHeight) / 2;
  9656. var renderingCanvas = engine.getRenderingCanvas();
  9657. if (renderContext && renderingCanvas) {
  9658. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9659. }
  9660. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9661. };
  9662. /**
  9663. * Generates an image screenshot from the specified camera.
  9664. *
  9665. * @param engine The engine to use for rendering
  9666. * @param camera The camera to use for rendering
  9667. * @param size This parameter can be set to a single number or to an object with the
  9668. * following (optional) properties: precision, width, height. If a single number is passed,
  9669. * it will be used for both width and height. If an object is passed, the screenshot size
  9670. * will be derived from the parameters. The precision property is a multiplier allowing
  9671. * rendering at a higher or lower resolution.
  9672. * @param successCallback The callback receives a single parameter which contains the
  9673. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9674. * src parameter of an <img> to display it.
  9675. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9676. * Check your browser for supported MIME types.
  9677. * @param samples Texture samples (default: 1)
  9678. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9679. * @param fileName A name for for the downloaded file.
  9680. * @constructor
  9681. */
  9682. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9683. if (mimeType === void 0) { mimeType = "image/png"; }
  9684. if (samples === void 0) { samples = 1; }
  9685. if (antialiasing === void 0) { antialiasing = false; }
  9686. var width;
  9687. var height;
  9688. //If a precision value is specified
  9689. if (size.precision) {
  9690. width = Math.round(engine.getRenderWidth() * size.precision);
  9691. height = Math.round(width / engine.getAspectRatio(camera));
  9692. size = { width: width, height: height };
  9693. }
  9694. else if (size.width && size.height) {
  9695. width = size.width;
  9696. height = size.height;
  9697. }
  9698. //If passing only width, computing height to keep display canvas ratio.
  9699. else if (size.width && !size.height) {
  9700. width = size.width;
  9701. height = Math.round(width / engine.getAspectRatio(camera));
  9702. size = { width: width, height: height };
  9703. }
  9704. //If passing only height, computing width to keep display canvas ratio.
  9705. else if (size.height && !size.width) {
  9706. height = size.height;
  9707. width = Math.round(height * engine.getAspectRatio(camera));
  9708. size = { width: width, height: height };
  9709. }
  9710. //Assuming here that "size" parameter is a number
  9711. else if (!isNaN(size)) {
  9712. height = size;
  9713. width = size;
  9714. }
  9715. else {
  9716. Tools.Error("Invalid 'size' parameter !");
  9717. return;
  9718. }
  9719. var scene = camera.getScene();
  9720. var previousCamera = null;
  9721. if (scene.activeCamera !== camera) {
  9722. previousCamera = scene.activeCamera;
  9723. scene.activeCamera = camera;
  9724. }
  9725. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9726. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9727. texture.renderList = null;
  9728. texture.samples = samples;
  9729. if (antialiasing) {
  9730. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9731. }
  9732. texture.onAfterRenderObservable.add(function () {
  9733. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9734. });
  9735. scene.incrementRenderId();
  9736. scene.resetCachedMaterial();
  9737. texture.render(true);
  9738. texture.dispose();
  9739. if (previousCamera) {
  9740. scene.activeCamera = previousCamera;
  9741. }
  9742. camera.getProjectionMatrix(true); // Force cache refresh;
  9743. };
  9744. // XHR response validator for local file scenario
  9745. Tools.ValidateXHRData = function (xhr, dataType) {
  9746. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9747. if (dataType === void 0) { dataType = 7; }
  9748. try {
  9749. if (dataType & 1) {
  9750. if (xhr.responseText && xhr.responseText.length > 0) {
  9751. return true;
  9752. }
  9753. else if (dataType === 1) {
  9754. return false;
  9755. }
  9756. }
  9757. if (dataType & 2) {
  9758. // Check header width and height since there is no "TGA" magic number
  9759. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9760. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9761. return true;
  9762. }
  9763. else if (dataType === 2) {
  9764. return false;
  9765. }
  9766. }
  9767. if (dataType & 4) {
  9768. // Check for the "DDS" magic number
  9769. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9770. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9771. return true;
  9772. }
  9773. else {
  9774. return false;
  9775. }
  9776. }
  9777. }
  9778. catch (e) {
  9779. // Global protection
  9780. }
  9781. return false;
  9782. };
  9783. /**
  9784. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9785. * Be aware Math.random() could cause collisions, but:
  9786. * "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"
  9787. */
  9788. Tools.RandomId = function () {
  9789. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9790. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9791. return v.toString(16);
  9792. });
  9793. };
  9794. /**
  9795. * Test if the given uri is a base64 string.
  9796. * @param uri The uri to test
  9797. * @return True if the uri is a base64 string or false otherwise.
  9798. */
  9799. Tools.IsBase64 = function (uri) {
  9800. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9801. };
  9802. /**
  9803. * Decode the given base64 uri.
  9804. * @param uri The uri to decode
  9805. * @return The decoded base64 data.
  9806. */
  9807. Tools.DecodeBase64 = function (uri) {
  9808. var decodedString = atob(uri.split(",")[1]);
  9809. var bufferLength = decodedString.length;
  9810. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9811. for (var i = 0; i < bufferLength; i++) {
  9812. bufferView[i] = decodedString.charCodeAt(i);
  9813. }
  9814. return bufferView.buffer;
  9815. };
  9816. Object.defineProperty(Tools, "NoneLogLevel", {
  9817. get: function () {
  9818. return Tools._NoneLogLevel;
  9819. },
  9820. enumerable: true,
  9821. configurable: true
  9822. });
  9823. Object.defineProperty(Tools, "MessageLogLevel", {
  9824. get: function () {
  9825. return Tools._MessageLogLevel;
  9826. },
  9827. enumerable: true,
  9828. configurable: true
  9829. });
  9830. Object.defineProperty(Tools, "WarningLogLevel", {
  9831. get: function () {
  9832. return Tools._WarningLogLevel;
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. Object.defineProperty(Tools, "ErrorLogLevel", {
  9838. get: function () {
  9839. return Tools._ErrorLogLevel;
  9840. },
  9841. enumerable: true,
  9842. configurable: true
  9843. });
  9844. Object.defineProperty(Tools, "AllLogLevel", {
  9845. get: function () {
  9846. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Tools._AddLogEntry = function (entry) {
  9852. Tools._LogCache = entry + Tools._LogCache;
  9853. if (Tools.OnNewCacheEntry) {
  9854. Tools.OnNewCacheEntry(entry);
  9855. }
  9856. };
  9857. Tools._FormatMessage = function (message) {
  9858. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9859. var date = new Date();
  9860. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9861. };
  9862. Tools._LogDisabled = function (message) {
  9863. // nothing to do
  9864. };
  9865. Tools._LogEnabled = function (message) {
  9866. var formattedMessage = Tools._FormatMessage(message);
  9867. console.log("BJS - " + formattedMessage);
  9868. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9869. Tools._AddLogEntry(entry);
  9870. };
  9871. Tools._WarnDisabled = function (message) {
  9872. // nothing to do
  9873. };
  9874. Tools._WarnEnabled = function (message) {
  9875. var formattedMessage = Tools._FormatMessage(message);
  9876. console.warn("BJS - " + formattedMessage);
  9877. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9878. Tools._AddLogEntry(entry);
  9879. };
  9880. Tools._ErrorDisabled = function (message) {
  9881. // nothing to do
  9882. };
  9883. Tools._ErrorEnabled = function (message) {
  9884. Tools.errorsCount++;
  9885. var formattedMessage = Tools._FormatMessage(message);
  9886. console.error("BJS - " + formattedMessage);
  9887. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9888. Tools._AddLogEntry(entry);
  9889. };
  9890. Object.defineProperty(Tools, "LogCache", {
  9891. get: function () {
  9892. return Tools._LogCache;
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. Tools.ClearLogCache = function () {
  9898. Tools._LogCache = "";
  9899. Tools.errorsCount = 0;
  9900. };
  9901. Object.defineProperty(Tools, "LogLevels", {
  9902. set: function (level) {
  9903. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9904. Tools.Log = Tools._LogEnabled;
  9905. }
  9906. else {
  9907. Tools.Log = Tools._LogDisabled;
  9908. }
  9909. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9910. Tools.Warn = Tools._WarnEnabled;
  9911. }
  9912. else {
  9913. Tools.Warn = Tools._WarnDisabled;
  9914. }
  9915. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9916. Tools.Error = Tools._ErrorEnabled;
  9917. }
  9918. else {
  9919. Tools.Error = Tools._ErrorDisabled;
  9920. }
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. /**
  9926. * Check if the loaded document was accessed via `file:`-Protocol.
  9927. * @returns boolean
  9928. */
  9929. Tools.IsFileURL = function () {
  9930. return location.protocol === "file:";
  9931. };
  9932. Tools.IsWindowObjectExist = function () {
  9933. return (typeof window) !== "undefined";
  9934. };
  9935. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9936. get: function () {
  9937. return Tools._PerformanceNoneLogLevel;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9943. get: function () {
  9944. return Tools._PerformanceUserMarkLogLevel;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9950. get: function () {
  9951. return Tools._PerformanceConsoleLogLevel;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9957. set: function (level) {
  9958. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9959. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9960. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9961. return;
  9962. }
  9963. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9964. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9965. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9966. return;
  9967. }
  9968. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9969. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9975. };
  9976. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9977. };
  9978. Tools._StartUserMark = function (counterName, condition) {
  9979. if (condition === void 0) { condition = true; }
  9980. if (!Tools._performance) {
  9981. if (!Tools.IsWindowObjectExist()) {
  9982. return;
  9983. }
  9984. Tools._performance = window.performance;
  9985. }
  9986. if (!condition || !Tools._performance.mark) {
  9987. return;
  9988. }
  9989. Tools._performance.mark(counterName + "-Begin");
  9990. };
  9991. Tools._EndUserMark = function (counterName, condition) {
  9992. if (condition === void 0) { condition = true; }
  9993. if (!condition || !Tools._performance.mark) {
  9994. return;
  9995. }
  9996. Tools._performance.mark(counterName + "-End");
  9997. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9998. };
  9999. Tools._StartPerformanceConsole = function (counterName, condition) {
  10000. if (condition === void 0) { condition = true; }
  10001. if (!condition) {
  10002. return;
  10003. }
  10004. Tools._StartUserMark(counterName, condition);
  10005. if (console.time) {
  10006. console.time(counterName);
  10007. }
  10008. };
  10009. Tools._EndPerformanceConsole = function (counterName, condition) {
  10010. if (condition === void 0) { condition = true; }
  10011. if (!condition) {
  10012. return;
  10013. }
  10014. Tools._EndUserMark(counterName, condition);
  10015. if (console.time) {
  10016. console.timeEnd(counterName);
  10017. }
  10018. };
  10019. Object.defineProperty(Tools, "Now", {
  10020. get: function () {
  10021. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10022. return window.performance.now();
  10023. }
  10024. return Date.now();
  10025. },
  10026. enumerable: true,
  10027. configurable: true
  10028. });
  10029. /**
  10030. * This method will return the name of the class used to create the instance of the given object.
  10031. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10032. * @param object the object to get the class name from
  10033. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10034. */
  10035. Tools.GetClassName = function (object, isType) {
  10036. if (isType === void 0) { isType = false; }
  10037. var name = null;
  10038. if (!isType && object.getClassName) {
  10039. name = object.getClassName();
  10040. }
  10041. else {
  10042. if (object instanceof Object) {
  10043. var classObj = isType ? object : Object.getPrototypeOf(object);
  10044. name = classObj.constructor["__bjsclassName__"];
  10045. }
  10046. if (!name) {
  10047. name = typeof object;
  10048. }
  10049. }
  10050. return name;
  10051. };
  10052. Tools.First = function (array, predicate) {
  10053. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10054. var el = array_1[_i];
  10055. if (predicate(el)) {
  10056. return el;
  10057. }
  10058. }
  10059. return null;
  10060. };
  10061. /**
  10062. * This method will return the name of the full name of the class, including its owning module (if any).
  10063. * 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).
  10064. * @param object the object to get the class name from
  10065. * @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.
  10066. */
  10067. Tools.getFullClassName = function (object, isType) {
  10068. if (isType === void 0) { isType = false; }
  10069. var className = null;
  10070. var moduleName = null;
  10071. if (!isType && object.getClassName) {
  10072. className = object.getClassName();
  10073. }
  10074. else {
  10075. if (object instanceof Object) {
  10076. var classObj = isType ? object : Object.getPrototypeOf(object);
  10077. className = classObj.constructor["__bjsclassName__"];
  10078. moduleName = classObj.constructor["__bjsmoduleName__"];
  10079. }
  10080. if (!className) {
  10081. className = typeof object;
  10082. }
  10083. }
  10084. if (!className) {
  10085. return null;
  10086. }
  10087. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10088. };
  10089. /**
  10090. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  10091. * @param array
  10092. */
  10093. Tools.arrayOrStringFeeder = function (array) {
  10094. return function (index) {
  10095. if (index >= array.length) {
  10096. return null;
  10097. }
  10098. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10099. if (val && val.getHashCode) {
  10100. val = val.getHashCode();
  10101. }
  10102. if (typeof val === "string") {
  10103. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10104. }
  10105. return val;
  10106. };
  10107. };
  10108. /**
  10109. * Compute the hashCode of a stream of number
  10110. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10111. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10112. * @return the hash code computed
  10113. */
  10114. Tools.hashCodeFromStream = function (feeder) {
  10115. // Based from here: http://stackoverflow.com/a/7616484/802124
  10116. var hash = 0;
  10117. var index = 0;
  10118. var chr = feeder(index++);
  10119. while (chr != null) {
  10120. hash = ((hash << 5) - hash) + chr;
  10121. hash |= 0; // Convert to 32bit integer
  10122. chr = feeder(index++);
  10123. }
  10124. return hash;
  10125. };
  10126. /**
  10127. * Returns a promise that resolves after the given amount of time.
  10128. * @param delay Number of milliseconds to delay
  10129. * @returns Promise that resolves after the given amount of time
  10130. */
  10131. Tools.DelayAsync = function (delay) {
  10132. return new Promise(function (resolve) {
  10133. setTimeout(function () {
  10134. resolve();
  10135. }, delay);
  10136. });
  10137. };
  10138. /**
  10139. * Gets the current gradient from an array of IValueGradient
  10140. * @param ratio defines the current ratio to get
  10141. * @param gradients defines the array of IValueGradient
  10142. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10143. */
  10144. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10145. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10146. var currentGradient = gradients[gradientIndex];
  10147. var nextGradient = gradients[gradientIndex + 1];
  10148. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10149. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10150. updateFunc(currentGradient, nextGradient, scale);
  10151. return;
  10152. }
  10153. }
  10154. // Use last index if over
  10155. var lastIndex = gradients.length - 1;
  10156. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10157. };
  10158. Tools.BaseUrl = "";
  10159. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10160. /**
  10161. * Default behaviour for cors in the application.
  10162. * It can be a string if the expected behavior is identical in the entire app.
  10163. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10164. */
  10165. Tools.CorsBehavior = "anonymous";
  10166. Tools.UseFallbackTexture = true;
  10167. /**
  10168. * Use this object to register external classes like custom textures or material
  10169. * to allow the laoders to instantiate them
  10170. */
  10171. Tools.RegisteredExternalClasses = {};
  10172. // Used in case of a texture loading problem
  10173. 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";
  10174. Tools._tmpFloatArray = new Float32Array(1);
  10175. Tools.PreprocessUrl = function (url) {
  10176. return url;
  10177. };
  10178. // Logs
  10179. Tools._NoneLogLevel = 0;
  10180. Tools._MessageLogLevel = 1;
  10181. Tools._WarningLogLevel = 2;
  10182. Tools._ErrorLogLevel = 4;
  10183. Tools._LogCache = "";
  10184. Tools.errorsCount = 0;
  10185. Tools.Log = Tools._LogEnabled;
  10186. Tools.Warn = Tools._WarnEnabled;
  10187. Tools.Error = Tools._ErrorEnabled;
  10188. // Performances
  10189. Tools._PerformanceNoneLogLevel = 0;
  10190. Tools._PerformanceUserMarkLogLevel = 1;
  10191. Tools._PerformanceConsoleLogLevel = 2;
  10192. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10193. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10194. return Tools;
  10195. }());
  10196. BABYLON.Tools = Tools;
  10197. /**
  10198. * This class is used to track a performance counter which is number based.
  10199. * The user has access to many properties which give statistics of different nature
  10200. *
  10201. * The implementer can track two kinds of Performance Counter: time and count
  10202. * 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.
  10203. * 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.
  10204. */
  10205. var PerfCounter = /** @class */ (function () {
  10206. function PerfCounter() {
  10207. this._startMonitoringTime = 0;
  10208. this._min = 0;
  10209. this._max = 0;
  10210. this._average = 0;
  10211. this._lastSecAverage = 0;
  10212. this._current = 0;
  10213. this._totalValueCount = 0;
  10214. this._totalAccumulated = 0;
  10215. this._lastSecAccumulated = 0;
  10216. this._lastSecTime = 0;
  10217. this._lastSecValueCount = 0;
  10218. }
  10219. Object.defineProperty(PerfCounter.prototype, "min", {
  10220. /**
  10221. * Returns the smallest value ever
  10222. */
  10223. get: function () {
  10224. return this._min;
  10225. },
  10226. enumerable: true,
  10227. configurable: true
  10228. });
  10229. Object.defineProperty(PerfCounter.prototype, "max", {
  10230. /**
  10231. * Returns the biggest value ever
  10232. */
  10233. get: function () {
  10234. return this._max;
  10235. },
  10236. enumerable: true,
  10237. configurable: true
  10238. });
  10239. Object.defineProperty(PerfCounter.prototype, "average", {
  10240. /**
  10241. * Returns the average value since the performance counter is running
  10242. */
  10243. get: function () {
  10244. return this._average;
  10245. },
  10246. enumerable: true,
  10247. configurable: true
  10248. });
  10249. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10250. /**
  10251. * Returns the average value of the last second the counter was monitored
  10252. */
  10253. get: function () {
  10254. return this._lastSecAverage;
  10255. },
  10256. enumerable: true,
  10257. configurable: true
  10258. });
  10259. Object.defineProperty(PerfCounter.prototype, "current", {
  10260. /**
  10261. * Returns the current value
  10262. */
  10263. get: function () {
  10264. return this._current;
  10265. },
  10266. enumerable: true,
  10267. configurable: true
  10268. });
  10269. Object.defineProperty(PerfCounter.prototype, "total", {
  10270. get: function () {
  10271. return this._totalAccumulated;
  10272. },
  10273. enumerable: true,
  10274. configurable: true
  10275. });
  10276. Object.defineProperty(PerfCounter.prototype, "count", {
  10277. get: function () {
  10278. return this._totalValueCount;
  10279. },
  10280. enumerable: true,
  10281. configurable: true
  10282. });
  10283. /**
  10284. * Call this method to start monitoring a new frame.
  10285. * 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.
  10286. */
  10287. PerfCounter.prototype.fetchNewFrame = function () {
  10288. this._totalValueCount++;
  10289. this._current = 0;
  10290. this._lastSecValueCount++;
  10291. };
  10292. /**
  10293. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10294. * @param newCount the count value to add to the monitored count
  10295. * @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.
  10296. */
  10297. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10298. if (!PerfCounter.Enabled) {
  10299. return;
  10300. }
  10301. this._current += newCount;
  10302. if (fetchResult) {
  10303. this._fetchResult();
  10304. }
  10305. };
  10306. /**
  10307. * Start monitoring this performance counter
  10308. */
  10309. PerfCounter.prototype.beginMonitoring = function () {
  10310. if (!PerfCounter.Enabled) {
  10311. return;
  10312. }
  10313. this._startMonitoringTime = Tools.Now;
  10314. };
  10315. /**
  10316. * Compute the time lapsed since the previous beginMonitoring() call.
  10317. * @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
  10318. */
  10319. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10320. if (newFrame === void 0) { newFrame = true; }
  10321. if (!PerfCounter.Enabled) {
  10322. return;
  10323. }
  10324. if (newFrame) {
  10325. this.fetchNewFrame();
  10326. }
  10327. var currentTime = Tools.Now;
  10328. this._current = currentTime - this._startMonitoringTime;
  10329. if (newFrame) {
  10330. this._fetchResult();
  10331. }
  10332. };
  10333. PerfCounter.prototype._fetchResult = function () {
  10334. this._totalAccumulated += this._current;
  10335. this._lastSecAccumulated += this._current;
  10336. // Min/Max update
  10337. this._min = Math.min(this._min, this._current);
  10338. this._max = Math.max(this._max, this._current);
  10339. this._average = this._totalAccumulated / this._totalValueCount;
  10340. // Reset last sec?
  10341. var now = Tools.Now;
  10342. if ((now - this._lastSecTime) > 1000) {
  10343. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10344. this._lastSecTime = now;
  10345. this._lastSecAccumulated = 0;
  10346. this._lastSecValueCount = 0;
  10347. }
  10348. };
  10349. PerfCounter.Enabled = true;
  10350. return PerfCounter;
  10351. }());
  10352. BABYLON.PerfCounter = PerfCounter;
  10353. /**
  10354. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10355. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10356. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10357. * @param name The name of the class, case should be preserved
  10358. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10359. */
  10360. function className(name, module) {
  10361. return function (target) {
  10362. target["__bjsclassName__"] = name;
  10363. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10364. };
  10365. }
  10366. BABYLON.className = className;
  10367. /**
  10368. * An implementation of a loop for asynchronous functions.
  10369. */
  10370. var AsyncLoop = /** @class */ (function () {
  10371. /**
  10372. * Constroctor.
  10373. * @param iterations the number of iterations.
  10374. * @param _fn the function to run each iteration
  10375. * @param _successCallback the callback that will be called upon succesful execution
  10376. * @param offset starting offset.
  10377. */
  10378. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10379. if (offset === void 0) { offset = 0; }
  10380. this.iterations = iterations;
  10381. this._fn = _fn;
  10382. this._successCallback = _successCallback;
  10383. this.index = offset - 1;
  10384. this._done = false;
  10385. }
  10386. /**
  10387. * Execute the next iteration. Must be called after the last iteration was finished.
  10388. */
  10389. AsyncLoop.prototype.executeNext = function () {
  10390. if (!this._done) {
  10391. if (this.index + 1 < this.iterations) {
  10392. ++this.index;
  10393. this._fn(this);
  10394. }
  10395. else {
  10396. this.breakLoop();
  10397. }
  10398. }
  10399. };
  10400. /**
  10401. * Break the loop and run the success callback.
  10402. */
  10403. AsyncLoop.prototype.breakLoop = function () {
  10404. this._done = true;
  10405. this._successCallback();
  10406. };
  10407. /**
  10408. * Helper function
  10409. */
  10410. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10411. if (offset === void 0) { offset = 0; }
  10412. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10413. loop.executeNext();
  10414. return loop;
  10415. };
  10416. /**
  10417. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10418. * @param iterations total number of iterations
  10419. * @param syncedIterations number of synchronous iterations in each async iteration.
  10420. * @param fn the function to call each iteration.
  10421. * @param callback a success call back that will be called when iterating stops.
  10422. * @param breakFunction a break condition (optional)
  10423. * @param timeout timeout settings for the setTimeout function. default - 0.
  10424. * @constructor
  10425. */
  10426. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10427. if (timeout === void 0) { timeout = 0; }
  10428. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10429. if (breakFunction && breakFunction())
  10430. loop.breakLoop();
  10431. else {
  10432. setTimeout(function () {
  10433. for (var i = 0; i < syncedIterations; ++i) {
  10434. var iteration = (loop.index * syncedIterations) + i;
  10435. if (iteration >= iterations)
  10436. break;
  10437. fn(iteration);
  10438. if (breakFunction && breakFunction()) {
  10439. loop.breakLoop();
  10440. break;
  10441. }
  10442. }
  10443. loop.executeNext();
  10444. }, timeout);
  10445. }
  10446. }, callback);
  10447. };
  10448. return AsyncLoop;
  10449. }());
  10450. BABYLON.AsyncLoop = AsyncLoop;
  10451. })(BABYLON || (BABYLON = {}));
  10452. //# sourceMappingURL=babylon.tools.js.map
  10453. var BABYLON;
  10454. (function (BABYLON) {
  10455. var PromiseStates;
  10456. (function (PromiseStates) {
  10457. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10458. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10459. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10460. })(PromiseStates || (PromiseStates = {}));
  10461. var FulFillmentAgregator = /** @class */ (function () {
  10462. function FulFillmentAgregator() {
  10463. this.count = 0;
  10464. this.target = 0;
  10465. this.results = [];
  10466. }
  10467. return FulFillmentAgregator;
  10468. }());
  10469. var InternalPromise = /** @class */ (function () {
  10470. function InternalPromise(resolver) {
  10471. var _this = this;
  10472. this._state = PromiseStates.Pending;
  10473. this._children = new Array();
  10474. this._rejectWasConsumed = false;
  10475. if (!resolver) {
  10476. return;
  10477. }
  10478. try {
  10479. resolver(function (value) {
  10480. _this._resolve(value);
  10481. }, function (reason) {
  10482. _this._reject(reason);
  10483. });
  10484. }
  10485. catch (e) {
  10486. this._reject(e);
  10487. }
  10488. }
  10489. Object.defineProperty(InternalPromise.prototype, "_result", {
  10490. get: function () {
  10491. return this._resultValue;
  10492. },
  10493. set: function (value) {
  10494. this._resultValue = value;
  10495. if (this._parent && this._parent._result === undefined) {
  10496. this._parent._result = value;
  10497. }
  10498. },
  10499. enumerable: true,
  10500. configurable: true
  10501. });
  10502. InternalPromise.prototype.catch = function (onRejected) {
  10503. return this.then(undefined, onRejected);
  10504. };
  10505. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10506. var _this = this;
  10507. var newPromise = new InternalPromise();
  10508. newPromise._onFulfilled = onFulfilled;
  10509. newPromise._onRejected = onRejected;
  10510. // Composition
  10511. this._children.push(newPromise);
  10512. newPromise._parent = this;
  10513. if (this._state !== PromiseStates.Pending) {
  10514. BABYLON.Tools.SetImmediate(function () {
  10515. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10516. var returnedValue = newPromise._resolve(_this._result);
  10517. if (returnedValue !== undefined && returnedValue !== null) {
  10518. if (returnedValue._state !== undefined) {
  10519. var returnedPromise = returnedValue;
  10520. newPromise._children.push(returnedPromise);
  10521. returnedPromise._parent = newPromise;
  10522. newPromise = returnedPromise;
  10523. }
  10524. else {
  10525. newPromise._result = returnedValue;
  10526. }
  10527. }
  10528. }
  10529. else {
  10530. newPromise._reject(_this._reason);
  10531. }
  10532. });
  10533. }
  10534. return newPromise;
  10535. };
  10536. InternalPromise.prototype._moveChildren = function (children) {
  10537. var _this = this;
  10538. var _a;
  10539. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10540. this._children.forEach(function (child) {
  10541. child._parent = _this;
  10542. });
  10543. if (this._state === PromiseStates.Fulfilled) {
  10544. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10545. var child = _b[_i];
  10546. child._resolve(this._result);
  10547. }
  10548. }
  10549. else if (this._state === PromiseStates.Rejected) {
  10550. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10551. var child = _d[_c];
  10552. child._reject(this._reason);
  10553. }
  10554. }
  10555. };
  10556. InternalPromise.prototype._resolve = function (value) {
  10557. try {
  10558. this._state = PromiseStates.Fulfilled;
  10559. var returnedValue = null;
  10560. if (this._onFulfilled) {
  10561. returnedValue = this._onFulfilled(value);
  10562. }
  10563. if (returnedValue !== undefined && returnedValue !== null) {
  10564. if (returnedValue._state !== undefined) {
  10565. // Transmit children
  10566. var returnedPromise = returnedValue;
  10567. returnedPromise._parent = this;
  10568. returnedPromise._moveChildren(this._children);
  10569. value = returnedPromise._result;
  10570. }
  10571. else {
  10572. value = returnedValue;
  10573. }
  10574. }
  10575. this._result = value;
  10576. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10577. var child = _a[_i];
  10578. child._resolve(value);
  10579. }
  10580. this._children.length = 0;
  10581. delete this._onFulfilled;
  10582. delete this._onRejected;
  10583. }
  10584. catch (e) {
  10585. this._reject(e, true);
  10586. }
  10587. };
  10588. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10589. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10590. this._state = PromiseStates.Rejected;
  10591. this._reason = reason;
  10592. if (this._onRejected && !onLocalThrow) {
  10593. try {
  10594. this._onRejected(reason);
  10595. this._rejectWasConsumed = true;
  10596. }
  10597. catch (e) {
  10598. reason = e;
  10599. }
  10600. }
  10601. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10602. var child = _a[_i];
  10603. if (this._rejectWasConsumed) {
  10604. child._resolve(null);
  10605. }
  10606. else {
  10607. child._reject(reason);
  10608. }
  10609. }
  10610. this._children.length = 0;
  10611. delete this._onFulfilled;
  10612. delete this._onRejected;
  10613. };
  10614. InternalPromise.resolve = function (value) {
  10615. var newPromise = new InternalPromise();
  10616. newPromise._resolve(value);
  10617. return newPromise;
  10618. };
  10619. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10620. promise.then(function (value) {
  10621. agregator.results[index] = value;
  10622. agregator.count++;
  10623. if (agregator.count === agregator.target) {
  10624. agregator.rootPromise._resolve(agregator.results);
  10625. }
  10626. return null;
  10627. }, function (reason) {
  10628. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10629. agregator.rootPromise._reject(reason);
  10630. }
  10631. });
  10632. };
  10633. InternalPromise.all = function (promises) {
  10634. var newPromise = new InternalPromise();
  10635. var agregator = new FulFillmentAgregator();
  10636. agregator.target = promises.length;
  10637. agregator.rootPromise = newPromise;
  10638. if (promises.length) {
  10639. for (var index = 0; index < promises.length; index++) {
  10640. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10641. }
  10642. }
  10643. else {
  10644. newPromise._resolve([]);
  10645. }
  10646. return newPromise;
  10647. };
  10648. InternalPromise.race = function (promises) {
  10649. var newPromise = new InternalPromise();
  10650. if (promises.length) {
  10651. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10652. var promise = promises_1[_i];
  10653. promise.then(function (value) {
  10654. if (newPromise) {
  10655. newPromise._resolve(value);
  10656. newPromise = null;
  10657. }
  10658. return null;
  10659. }, function (reason) {
  10660. if (newPromise) {
  10661. newPromise._reject(reason);
  10662. newPromise = null;
  10663. }
  10664. });
  10665. }
  10666. }
  10667. return newPromise;
  10668. };
  10669. return InternalPromise;
  10670. }());
  10671. /**
  10672. * Helper class that provides a small promise polyfill
  10673. */
  10674. var PromisePolyfill = /** @class */ (function () {
  10675. function PromisePolyfill() {
  10676. }
  10677. /**
  10678. * Static function used to check if the polyfill is required
  10679. * If this is the case then the function will inject the polyfill to window.Promise
  10680. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10681. */
  10682. PromisePolyfill.Apply = function (force) {
  10683. if (force === void 0) { force = false; }
  10684. if (force || typeof Promise === 'undefined') {
  10685. var root = window;
  10686. root.Promise = InternalPromise;
  10687. }
  10688. };
  10689. return PromisePolyfill;
  10690. }());
  10691. BABYLON.PromisePolyfill = PromisePolyfill;
  10692. })(BABYLON || (BABYLON = {}));
  10693. //# sourceMappingURL=babylon.promise.js.map
  10694. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10695. var BABYLON;
  10696. (function (BABYLON) {
  10697. /**
  10698. * Helper class to push actions to a pool of workers.
  10699. */
  10700. var WorkerPool = /** @class */ (function () {
  10701. /**
  10702. * Constructor
  10703. * @param workers Array of workers to use for actions
  10704. */
  10705. function WorkerPool(workers) {
  10706. this._pendingActions = new Array();
  10707. this._workerInfos = workers.map(function (worker) { return ({
  10708. worker: worker,
  10709. active: false
  10710. }); });
  10711. }
  10712. /**
  10713. * Terminates all workers and clears any pending actions.
  10714. */
  10715. WorkerPool.prototype.dispose = function () {
  10716. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10717. var workerInfo = _a[_i];
  10718. workerInfo.worker.terminate();
  10719. }
  10720. delete this._workerInfos;
  10721. delete this._pendingActions;
  10722. };
  10723. /**
  10724. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10725. * pended until a worker has completed its action.
  10726. * @param action The action to perform. Call onComplete when the action is complete.
  10727. */
  10728. WorkerPool.prototype.push = function (action) {
  10729. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10730. var workerInfo = _a[_i];
  10731. if (!workerInfo.active) {
  10732. this._execute(workerInfo, action);
  10733. return;
  10734. }
  10735. }
  10736. this._pendingActions.push(action);
  10737. };
  10738. WorkerPool.prototype._execute = function (workerInfo, action) {
  10739. var _this = this;
  10740. workerInfo.active = true;
  10741. action(workerInfo.worker, function () {
  10742. workerInfo.active = false;
  10743. var nextAction = _this._pendingActions.shift();
  10744. if (nextAction) {
  10745. _this._execute(workerInfo, nextAction);
  10746. }
  10747. });
  10748. };
  10749. return WorkerPool;
  10750. }());
  10751. BABYLON.WorkerPool = WorkerPool;
  10752. })(BABYLON || (BABYLON = {}));
  10753. //# sourceMappingURL=babylon.workerPool.js.map
  10754. var BABYLON;
  10755. (function (BABYLON) {
  10756. /**
  10757. * @hidden
  10758. **/
  10759. var _AlphaState = /** @class */ (function () {
  10760. /**
  10761. * Initializes the state.
  10762. */
  10763. function _AlphaState() {
  10764. this._isAlphaBlendDirty = false;
  10765. this._isBlendFunctionParametersDirty = false;
  10766. this._isBlendEquationParametersDirty = false;
  10767. this._isBlendConstantsDirty = false;
  10768. this._alphaBlend = false;
  10769. this._blendFunctionParameters = new Array(4);
  10770. this._blendEquationParameters = new Array(2);
  10771. this._blendConstants = new Array(4);
  10772. this.reset();
  10773. }
  10774. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10775. get: function () {
  10776. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10782. get: function () {
  10783. return this._alphaBlend;
  10784. },
  10785. set: function (value) {
  10786. if (this._alphaBlend === value) {
  10787. return;
  10788. }
  10789. this._alphaBlend = value;
  10790. this._isAlphaBlendDirty = true;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10796. if (this._blendConstants[0] === r &&
  10797. this._blendConstants[1] === g &&
  10798. this._blendConstants[2] === b &&
  10799. this._blendConstants[3] === a) {
  10800. return;
  10801. }
  10802. this._blendConstants[0] = r;
  10803. this._blendConstants[1] = g;
  10804. this._blendConstants[2] = b;
  10805. this._blendConstants[3] = a;
  10806. this._isBlendConstantsDirty = true;
  10807. };
  10808. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10809. if (this._blendFunctionParameters[0] === value0 &&
  10810. this._blendFunctionParameters[1] === value1 &&
  10811. this._blendFunctionParameters[2] === value2 &&
  10812. this._blendFunctionParameters[3] === value3) {
  10813. return;
  10814. }
  10815. this._blendFunctionParameters[0] = value0;
  10816. this._blendFunctionParameters[1] = value1;
  10817. this._blendFunctionParameters[2] = value2;
  10818. this._blendFunctionParameters[3] = value3;
  10819. this._isBlendFunctionParametersDirty = true;
  10820. };
  10821. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10822. if (this._blendEquationParameters[0] === rgb &&
  10823. this._blendEquationParameters[1] === alpha) {
  10824. return;
  10825. }
  10826. this._blendEquationParameters[0] = rgb;
  10827. this._blendEquationParameters[1] = alpha;
  10828. this._isBlendEquationParametersDirty = true;
  10829. };
  10830. _AlphaState.prototype.reset = function () {
  10831. this._alphaBlend = false;
  10832. this._blendFunctionParameters[0] = null;
  10833. this._blendFunctionParameters[1] = null;
  10834. this._blendFunctionParameters[2] = null;
  10835. this._blendFunctionParameters[3] = null;
  10836. this._blendEquationParameters[0] = null;
  10837. this._blendEquationParameters[1] = null;
  10838. this._blendConstants[0] = null;
  10839. this._blendConstants[1] = null;
  10840. this._blendConstants[2] = null;
  10841. this._blendConstants[3] = null;
  10842. this._isAlphaBlendDirty = true;
  10843. this._isBlendFunctionParametersDirty = false;
  10844. this._isBlendEquationParametersDirty = false;
  10845. this._isBlendConstantsDirty = false;
  10846. };
  10847. _AlphaState.prototype.apply = function (gl) {
  10848. if (!this.isDirty) {
  10849. return;
  10850. }
  10851. // Alpha blend
  10852. if (this._isAlphaBlendDirty) {
  10853. if (this._alphaBlend) {
  10854. gl.enable(gl.BLEND);
  10855. }
  10856. else {
  10857. gl.disable(gl.BLEND);
  10858. }
  10859. this._isAlphaBlendDirty = false;
  10860. }
  10861. // Alpha function
  10862. if (this._isBlendFunctionParametersDirty) {
  10863. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10864. this._isBlendFunctionParametersDirty = false;
  10865. }
  10866. // Alpha equation
  10867. if (this._isBlendEquationParametersDirty) {
  10868. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10869. this._isBlendEquationParametersDirty = false;
  10870. }
  10871. // Constants
  10872. if (this._isBlendConstantsDirty) {
  10873. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10874. this._isBlendConstantsDirty = false;
  10875. }
  10876. };
  10877. return _AlphaState;
  10878. }());
  10879. BABYLON._AlphaState = _AlphaState;
  10880. })(BABYLON || (BABYLON = {}));
  10881. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10882. var BABYLON;
  10883. (function (BABYLON) {
  10884. /**
  10885. * @hidden
  10886. **/
  10887. var _DepthCullingState = /** @class */ (function () {
  10888. /**
  10889. * Initializes the state.
  10890. */
  10891. function _DepthCullingState() {
  10892. this._isDepthTestDirty = false;
  10893. this._isDepthMaskDirty = false;
  10894. this._isDepthFuncDirty = false;
  10895. this._isCullFaceDirty = false;
  10896. this._isCullDirty = false;
  10897. this._isZOffsetDirty = false;
  10898. this._isFrontFaceDirty = false;
  10899. this.reset();
  10900. }
  10901. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10902. get: function () {
  10903. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10904. },
  10905. enumerable: true,
  10906. configurable: true
  10907. });
  10908. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10909. get: function () {
  10910. return this._zOffset;
  10911. },
  10912. set: function (value) {
  10913. if (this._zOffset === value) {
  10914. return;
  10915. }
  10916. this._zOffset = value;
  10917. this._isZOffsetDirty = true;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10923. get: function () {
  10924. return this._cullFace;
  10925. },
  10926. set: function (value) {
  10927. if (this._cullFace === value) {
  10928. return;
  10929. }
  10930. this._cullFace = value;
  10931. this._isCullFaceDirty = true;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10937. get: function () {
  10938. return this._cull;
  10939. },
  10940. set: function (value) {
  10941. if (this._cull === value) {
  10942. return;
  10943. }
  10944. this._cull = value;
  10945. this._isCullDirty = true;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10951. get: function () {
  10952. return this._depthFunc;
  10953. },
  10954. set: function (value) {
  10955. if (this._depthFunc === value) {
  10956. return;
  10957. }
  10958. this._depthFunc = value;
  10959. this._isDepthFuncDirty = true;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10965. get: function () {
  10966. return this._depthMask;
  10967. },
  10968. set: function (value) {
  10969. if (this._depthMask === value) {
  10970. return;
  10971. }
  10972. this._depthMask = value;
  10973. this._isDepthMaskDirty = true;
  10974. },
  10975. enumerable: true,
  10976. configurable: true
  10977. });
  10978. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10979. get: function () {
  10980. return this._depthTest;
  10981. },
  10982. set: function (value) {
  10983. if (this._depthTest === value) {
  10984. return;
  10985. }
  10986. this._depthTest = value;
  10987. this._isDepthTestDirty = true;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10993. get: function () {
  10994. return this._frontFace;
  10995. },
  10996. set: function (value) {
  10997. if (this._frontFace === value) {
  10998. return;
  10999. }
  11000. this._frontFace = value;
  11001. this._isFrontFaceDirty = true;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. _DepthCullingState.prototype.reset = function () {
  11007. this._depthMask = true;
  11008. this._depthTest = true;
  11009. this._depthFunc = null;
  11010. this._cullFace = null;
  11011. this._cull = null;
  11012. this._zOffset = 0;
  11013. this._frontFace = null;
  11014. this._isDepthTestDirty = true;
  11015. this._isDepthMaskDirty = true;
  11016. this._isDepthFuncDirty = false;
  11017. this._isCullFaceDirty = false;
  11018. this._isCullDirty = false;
  11019. this._isZOffsetDirty = false;
  11020. this._isFrontFaceDirty = false;
  11021. };
  11022. _DepthCullingState.prototype.apply = function (gl) {
  11023. if (!this.isDirty) {
  11024. return;
  11025. }
  11026. // Cull
  11027. if (this._isCullDirty) {
  11028. if (this.cull) {
  11029. gl.enable(gl.CULL_FACE);
  11030. }
  11031. else {
  11032. gl.disable(gl.CULL_FACE);
  11033. }
  11034. this._isCullDirty = false;
  11035. }
  11036. // Cull face
  11037. if (this._isCullFaceDirty) {
  11038. gl.cullFace(this.cullFace);
  11039. this._isCullFaceDirty = false;
  11040. }
  11041. // Depth mask
  11042. if (this._isDepthMaskDirty) {
  11043. gl.depthMask(this.depthMask);
  11044. this._isDepthMaskDirty = false;
  11045. }
  11046. // Depth test
  11047. if (this._isDepthTestDirty) {
  11048. if (this.depthTest) {
  11049. gl.enable(gl.DEPTH_TEST);
  11050. }
  11051. else {
  11052. gl.disable(gl.DEPTH_TEST);
  11053. }
  11054. this._isDepthTestDirty = false;
  11055. }
  11056. // Depth func
  11057. if (this._isDepthFuncDirty) {
  11058. gl.depthFunc(this.depthFunc);
  11059. this._isDepthFuncDirty = false;
  11060. }
  11061. // zOffset
  11062. if (this._isZOffsetDirty) {
  11063. if (this.zOffset) {
  11064. gl.enable(gl.POLYGON_OFFSET_FILL);
  11065. gl.polygonOffset(this.zOffset, 0);
  11066. }
  11067. else {
  11068. gl.disable(gl.POLYGON_OFFSET_FILL);
  11069. }
  11070. this._isZOffsetDirty = false;
  11071. }
  11072. // Front face
  11073. if (this._isFrontFaceDirty) {
  11074. gl.frontFace(this.frontFace);
  11075. this._isFrontFaceDirty = false;
  11076. }
  11077. };
  11078. return _DepthCullingState;
  11079. }());
  11080. BABYLON._DepthCullingState = _DepthCullingState;
  11081. })(BABYLON || (BABYLON = {}));
  11082. //# sourceMappingURL=babylon.depthCullingState.js.map
  11083. var BABYLON;
  11084. (function (BABYLON) {
  11085. /**
  11086. * @hidden
  11087. **/
  11088. var _StencilState = /** @class */ (function () {
  11089. function _StencilState() {
  11090. this._isStencilTestDirty = false;
  11091. this._isStencilMaskDirty = false;
  11092. this._isStencilFuncDirty = false;
  11093. this._isStencilOpDirty = false;
  11094. this.reset();
  11095. }
  11096. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11097. get: function () {
  11098. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11099. },
  11100. enumerable: true,
  11101. configurable: true
  11102. });
  11103. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11104. get: function () {
  11105. return this._stencilFunc;
  11106. },
  11107. set: function (value) {
  11108. if (this._stencilFunc === value) {
  11109. return;
  11110. }
  11111. this._stencilFunc = value;
  11112. this._isStencilFuncDirty = true;
  11113. },
  11114. enumerable: true,
  11115. configurable: true
  11116. });
  11117. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11118. get: function () {
  11119. return this._stencilFuncRef;
  11120. },
  11121. set: function (value) {
  11122. if (this._stencilFuncRef === value) {
  11123. return;
  11124. }
  11125. this._stencilFuncRef = value;
  11126. this._isStencilFuncDirty = true;
  11127. },
  11128. enumerable: true,
  11129. configurable: true
  11130. });
  11131. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11132. get: function () {
  11133. return this._stencilFuncMask;
  11134. },
  11135. set: function (value) {
  11136. if (this._stencilFuncMask === value) {
  11137. return;
  11138. }
  11139. this._stencilFuncMask = value;
  11140. this._isStencilFuncDirty = true;
  11141. },
  11142. enumerable: true,
  11143. configurable: true
  11144. });
  11145. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11146. get: function () {
  11147. return this._stencilOpStencilFail;
  11148. },
  11149. set: function (value) {
  11150. if (this._stencilOpStencilFail === value) {
  11151. return;
  11152. }
  11153. this._stencilOpStencilFail = value;
  11154. this._isStencilOpDirty = true;
  11155. },
  11156. enumerable: true,
  11157. configurable: true
  11158. });
  11159. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11160. get: function () {
  11161. return this._stencilOpDepthFail;
  11162. },
  11163. set: function (value) {
  11164. if (this._stencilOpDepthFail === value) {
  11165. return;
  11166. }
  11167. this._stencilOpDepthFail = value;
  11168. this._isStencilOpDirty = true;
  11169. },
  11170. enumerable: true,
  11171. configurable: true
  11172. });
  11173. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11174. get: function () {
  11175. return this._stencilOpStencilDepthPass;
  11176. },
  11177. set: function (value) {
  11178. if (this._stencilOpStencilDepthPass === value) {
  11179. return;
  11180. }
  11181. this._stencilOpStencilDepthPass = value;
  11182. this._isStencilOpDirty = true;
  11183. },
  11184. enumerable: true,
  11185. configurable: true
  11186. });
  11187. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11188. get: function () {
  11189. return this._stencilMask;
  11190. },
  11191. set: function (value) {
  11192. if (this._stencilMask === value) {
  11193. return;
  11194. }
  11195. this._stencilMask = value;
  11196. this._isStencilMaskDirty = true;
  11197. },
  11198. enumerable: true,
  11199. configurable: true
  11200. });
  11201. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11202. get: function () {
  11203. return this._stencilTest;
  11204. },
  11205. set: function (value) {
  11206. if (this._stencilTest === value) {
  11207. return;
  11208. }
  11209. this._stencilTest = value;
  11210. this._isStencilTestDirty = true;
  11211. },
  11212. enumerable: true,
  11213. configurable: true
  11214. });
  11215. _StencilState.prototype.reset = function () {
  11216. this._stencilTest = false;
  11217. this._stencilMask = 0xFF;
  11218. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11219. this._stencilFuncRef = 1;
  11220. this._stencilFuncMask = 0xFF;
  11221. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11222. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11223. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11224. this._isStencilTestDirty = true;
  11225. this._isStencilMaskDirty = true;
  11226. this._isStencilFuncDirty = true;
  11227. this._isStencilOpDirty = true;
  11228. };
  11229. _StencilState.prototype.apply = function (gl) {
  11230. if (!this.isDirty) {
  11231. return;
  11232. }
  11233. // Stencil test
  11234. if (this._isStencilTestDirty) {
  11235. if (this.stencilTest) {
  11236. gl.enable(gl.STENCIL_TEST);
  11237. }
  11238. else {
  11239. gl.disable(gl.STENCIL_TEST);
  11240. }
  11241. this._isStencilTestDirty = false;
  11242. }
  11243. // Stencil mask
  11244. if (this._isStencilMaskDirty) {
  11245. gl.stencilMask(this.stencilMask);
  11246. this._isStencilMaskDirty = false;
  11247. }
  11248. // Stencil func
  11249. if (this._isStencilFuncDirty) {
  11250. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11251. this._isStencilFuncDirty = false;
  11252. }
  11253. // Stencil op
  11254. if (this._isStencilOpDirty) {
  11255. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11256. this._isStencilOpDirty = false;
  11257. }
  11258. };
  11259. return _StencilState;
  11260. }());
  11261. BABYLON._StencilState = _StencilState;
  11262. })(BABYLON || (BABYLON = {}));
  11263. //# sourceMappingURL=babylon.stencilState.js.map
  11264. var __assign = (this && this.__assign) || function () {
  11265. __assign = Object.assign || function(t) {
  11266. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11267. s = arguments[i];
  11268. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11269. t[p] = s[p];
  11270. }
  11271. return t;
  11272. };
  11273. return __assign.apply(this, arguments);
  11274. };
  11275. var BABYLON;
  11276. (function (BABYLON) {
  11277. /**
  11278. * Keeps track of all the buffer info used in engine.
  11279. */
  11280. var BufferPointer = /** @class */ (function () {
  11281. function BufferPointer() {
  11282. }
  11283. return BufferPointer;
  11284. }());
  11285. /**
  11286. * Interface for attribute information associated with buffer instanciation
  11287. */
  11288. var InstancingAttributeInfo = /** @class */ (function () {
  11289. function InstancingAttributeInfo() {
  11290. }
  11291. return InstancingAttributeInfo;
  11292. }());
  11293. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11294. /**
  11295. * Define options used to create a render target texture
  11296. */
  11297. var RenderTargetCreationOptions = /** @class */ (function () {
  11298. function RenderTargetCreationOptions() {
  11299. }
  11300. return RenderTargetCreationOptions;
  11301. }());
  11302. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11303. /**
  11304. * Define options used to create a depth texture
  11305. */
  11306. var DepthTextureCreationOptions = /** @class */ (function () {
  11307. function DepthTextureCreationOptions() {
  11308. }
  11309. return DepthTextureCreationOptions;
  11310. }());
  11311. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11312. /**
  11313. * Class used to describe the capabilities of the engine relatively to the current browser
  11314. */
  11315. var EngineCapabilities = /** @class */ (function () {
  11316. function EngineCapabilities() {
  11317. }
  11318. return EngineCapabilities;
  11319. }());
  11320. BABYLON.EngineCapabilities = EngineCapabilities;
  11321. /**
  11322. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11323. */
  11324. var Engine = /** @class */ (function () {
  11325. /**
  11326. * Creates a new engine
  11327. * @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
  11328. * @param antialias defines enable antialiasing (default: false)
  11329. * @param options defines further options to be sent to the getContext() function
  11330. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11331. */
  11332. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11333. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11334. var _this = this;
  11335. // Public members
  11336. /**
  11337. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11338. */
  11339. this.forcePOTTextures = false;
  11340. /**
  11341. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11342. */
  11343. this.isFullscreen = false;
  11344. /**
  11345. * Gets a boolean indicating if the pointer is currently locked
  11346. */
  11347. this.isPointerLock = false;
  11348. /**
  11349. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11350. */
  11351. this.cullBackFaces = true;
  11352. /**
  11353. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11354. */
  11355. this.renderEvenInBackground = true;
  11356. /**
  11357. * Gets or sets a boolean indicating that cache can be kept between frames
  11358. */
  11359. this.preventCacheWipeBetweenFrames = false;
  11360. /**
  11361. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11362. **/
  11363. this.enableOfflineSupport = false;
  11364. /**
  11365. * 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)
  11366. **/
  11367. this.disableManifestCheck = false;
  11368. /**
  11369. * Gets the list of created scenes
  11370. */
  11371. this.scenes = new Array();
  11372. /**
  11373. * Gets the list of created postprocesses
  11374. */
  11375. this.postProcesses = new Array();
  11376. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11377. this.validateShaderPrograms = false;
  11378. // Observables
  11379. /**
  11380. * Observable event triggered each time the rendering canvas is resized
  11381. */
  11382. this.onResizeObservable = new BABYLON.Observable();
  11383. /**
  11384. * Observable event triggered each time the canvas loses focus
  11385. */
  11386. this.onCanvasBlurObservable = new BABYLON.Observable();
  11387. /**
  11388. * Observable event triggered each time the canvas gains focus
  11389. */
  11390. this.onCanvasFocusObservable = new BABYLON.Observable();
  11391. /**
  11392. * Observable event triggered each time the canvas receives pointerout event
  11393. */
  11394. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11395. /**
  11396. * Observable event triggered before each texture is initialized
  11397. */
  11398. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11399. //WebVR
  11400. this._vrDisplay = undefined;
  11401. this._vrSupported = false;
  11402. this._vrExclusivePointerMode = false;
  11403. // Uniform buffers list
  11404. /**
  11405. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11406. */
  11407. this.disableUniformBuffers = false;
  11408. /** @hidden */
  11409. this._uniformBuffers = new Array();
  11410. // Observables
  11411. /**
  11412. * Observable raised when the engine begins a new frame
  11413. */
  11414. this.onBeginFrameObservable = new BABYLON.Observable();
  11415. /**
  11416. * Observable raised when the engine ends the current frame
  11417. */
  11418. this.onEndFrameObservable = new BABYLON.Observable();
  11419. /**
  11420. * Observable raised when the engine is about to compile a shader
  11421. */
  11422. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11423. /**
  11424. * Observable raised when the engine has jsut compiled a shader
  11425. */
  11426. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11427. this._windowIsBackground = false;
  11428. this._webGLVersion = 1.0;
  11429. /** @hidden */
  11430. this._badOS = false;
  11431. /** @hidden */
  11432. this._badDesktopOS = false;
  11433. /**
  11434. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11435. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11436. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11437. */
  11438. this.disableTextureBindingOptimization = false;
  11439. /**
  11440. * Observable signaled when VR display mode changes
  11441. */
  11442. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11443. /**
  11444. * Observable signaled when VR request present is complete
  11445. */
  11446. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11447. /**
  11448. * Observable signaled when VR request present starts
  11449. */
  11450. this.onVRRequestPresentStart = new BABYLON.Observable();
  11451. this._colorWrite = true;
  11452. /** @hidden */
  11453. this._drawCalls = new BABYLON.PerfCounter();
  11454. /** @hidden */
  11455. this._textureCollisions = new BABYLON.PerfCounter();
  11456. this._renderingQueueLaunched = false;
  11457. this._activeRenderLoops = new Array();
  11458. // Deterministic lockstepMaxSteps
  11459. this._deterministicLockstep = false;
  11460. this._lockstepMaxSteps = 4;
  11461. // Lost context
  11462. /**
  11463. * Observable signaled when a context lost event is raised
  11464. */
  11465. this.onContextLostObservable = new BABYLON.Observable();
  11466. /**
  11467. * Observable signaled when a context restored event is raised
  11468. */
  11469. this.onContextRestoredObservable = new BABYLON.Observable();
  11470. this._contextWasLost = false;
  11471. this._doNotHandleContextLost = false;
  11472. // FPS
  11473. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11474. this._fps = 60;
  11475. this._deltaTime = 0;
  11476. /**
  11477. * Turn this value on if you want to pause FPS computation when in background
  11478. */
  11479. this.disablePerformanceMonitorInBackground = false;
  11480. // States
  11481. /** @hidden */
  11482. this._depthCullingState = new BABYLON._DepthCullingState();
  11483. /** @hidden */
  11484. this._stencilState = new BABYLON._StencilState();
  11485. /** @hidden */
  11486. this._alphaState = new BABYLON._AlphaState();
  11487. /** @hidden */
  11488. this._alphaMode = Engine.ALPHA_DISABLE;
  11489. // Cache
  11490. this._internalTexturesCache = new Array();
  11491. /** @hidden */
  11492. this._activeChannel = 0;
  11493. this._currentTextureChannel = -1;
  11494. /** @hidden */
  11495. this._boundTexturesCache = {};
  11496. this._compiledEffects = {};
  11497. this._vertexAttribArraysEnabled = [];
  11498. this._uintIndicesCurrentlySet = false;
  11499. this._currentBoundBuffer = new Array();
  11500. /** @hidden */
  11501. this._currentFramebuffer = null;
  11502. this._currentBufferPointers = new Array();
  11503. this._currentInstanceLocations = new Array();
  11504. this._currentInstanceBuffers = new Array();
  11505. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11506. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11507. this._vaoRecordInProgress = false;
  11508. this._mustWipeVertexAttributes = false;
  11509. this._nextFreeTextureSlots = new Array();
  11510. this._maxSimultaneousTextures = 0;
  11511. this._activeRequests = new Array();
  11512. // Hardware supported Compressed Textures
  11513. this._texturesSupported = new Array();
  11514. /**
  11515. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11516. */
  11517. this.premultipliedAlpha = true;
  11518. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11519. this._onVRFullScreenTriggered = function () {
  11520. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11521. //get the old size before we change
  11522. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11523. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11524. //get the width and height, change the render size
  11525. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11526. _this.setHardwareScalingLevel(1);
  11527. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11528. }
  11529. else {
  11530. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11531. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11532. }
  11533. };
  11534. this._unpackFlipYCached = null;
  11535. /**
  11536. * In case you are sharing the context with other applications, it might
  11537. * be interested to not cache the unpack flip y state to ensure a consistent
  11538. * value would be set.
  11539. */
  11540. this.enableUnpackFlipYCached = true;
  11541. this._boundUniforms = {};
  11542. // Register promises
  11543. BABYLON.PromisePolyfill.Apply();
  11544. var canvas = null;
  11545. Engine.Instances.push(this);
  11546. if (!canvasOrContext) {
  11547. return;
  11548. }
  11549. options = options || {};
  11550. if (canvasOrContext.getContext) {
  11551. canvas = canvasOrContext;
  11552. this._renderingCanvas = canvas;
  11553. if (antialias != null) {
  11554. options.antialias = antialias;
  11555. }
  11556. if (options.deterministicLockstep === undefined) {
  11557. options.deterministicLockstep = false;
  11558. }
  11559. if (options.lockstepMaxSteps === undefined) {
  11560. options.lockstepMaxSteps = 4;
  11561. }
  11562. if (options.preserveDrawingBuffer === undefined) {
  11563. options.preserveDrawingBuffer = false;
  11564. }
  11565. if (options.audioEngine === undefined) {
  11566. options.audioEngine = true;
  11567. }
  11568. if (options.stencil === undefined) {
  11569. options.stencil = true;
  11570. }
  11571. if (options.premultipliedAlpha === false) {
  11572. this.premultipliedAlpha = false;
  11573. }
  11574. this._deterministicLockstep = options.deterministicLockstep;
  11575. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11576. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11577. // Exceptions
  11578. if (navigator && navigator.userAgent) {
  11579. var ua = navigator.userAgent;
  11580. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11581. var exception = _a[_i];
  11582. var key = exception.key;
  11583. var targets = exception.targets;
  11584. if (ua.indexOf(key) > -1) {
  11585. if (exception.capture && exception.captureConstraint) {
  11586. var capture = exception.capture;
  11587. var constraint = exception.captureConstraint;
  11588. var regex = new RegExp(capture);
  11589. var matches = regex.exec(ua);
  11590. if (matches && matches.length > 0) {
  11591. var capturedValue = parseInt(matches[matches.length - 1]);
  11592. if (capturedValue >= constraint) {
  11593. continue;
  11594. }
  11595. }
  11596. }
  11597. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11598. var target = targets_1[_b];
  11599. switch (target) {
  11600. case "uniformBuffer":
  11601. this.disableUniformBuffers = true;
  11602. break;
  11603. case "textureBindingOptimization":
  11604. this.disableTextureBindingOptimization = true;
  11605. break;
  11606. }
  11607. }
  11608. }
  11609. }
  11610. }
  11611. // GL
  11612. if (!options.disableWebGL2Support) {
  11613. try {
  11614. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11615. if (this._gl) {
  11616. this._webGLVersion = 2.0;
  11617. }
  11618. }
  11619. catch (e) {
  11620. // Do nothing
  11621. }
  11622. }
  11623. if (!this._gl) {
  11624. if (!canvas) {
  11625. throw new Error("The provided canvas is null or undefined.");
  11626. }
  11627. try {
  11628. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11629. }
  11630. catch (e) {
  11631. throw new Error("WebGL not supported");
  11632. }
  11633. }
  11634. if (!this._gl) {
  11635. throw new Error("WebGL not supported");
  11636. }
  11637. this._onCanvasFocus = function () {
  11638. _this.onCanvasFocusObservable.notifyObservers(_this);
  11639. };
  11640. this._onCanvasBlur = function () {
  11641. _this.onCanvasBlurObservable.notifyObservers(_this);
  11642. };
  11643. canvas.addEventListener("focus", this._onCanvasFocus);
  11644. canvas.addEventListener("blur", this._onCanvasBlur);
  11645. this._onBlur = function () {
  11646. if (_this.disablePerformanceMonitorInBackground) {
  11647. _this._performanceMonitor.disable();
  11648. }
  11649. _this._windowIsBackground = true;
  11650. };
  11651. this._onFocus = function () {
  11652. if (_this.disablePerformanceMonitorInBackground) {
  11653. _this._performanceMonitor.enable();
  11654. }
  11655. _this._windowIsBackground = false;
  11656. };
  11657. this._onCanvasPointerOut = function (ev) {
  11658. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11659. };
  11660. window.addEventListener("blur", this._onBlur);
  11661. window.addEventListener("focus", this._onFocus);
  11662. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11663. // Context lost
  11664. if (!this._doNotHandleContextLost) {
  11665. this._onContextLost = function (evt) {
  11666. evt.preventDefault();
  11667. _this._contextWasLost = true;
  11668. BABYLON.Tools.Warn("WebGL context lost.");
  11669. _this.onContextLostObservable.notifyObservers(_this);
  11670. };
  11671. this._onContextRestored = function (evt) {
  11672. // Adding a timeout to avoid race condition at browser level
  11673. setTimeout(function () {
  11674. // Rebuild gl context
  11675. _this._initGLContext();
  11676. // Rebuild effects
  11677. _this._rebuildEffects();
  11678. // Rebuild textures
  11679. _this._rebuildInternalTextures();
  11680. // Rebuild buffers
  11681. _this._rebuildBuffers();
  11682. // Cache
  11683. _this.wipeCaches(true);
  11684. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11685. _this.onContextRestoredObservable.notifyObservers(_this);
  11686. _this._contextWasLost = false;
  11687. }, 0);
  11688. };
  11689. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11690. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11691. }
  11692. }
  11693. else {
  11694. this._gl = canvasOrContext;
  11695. this._renderingCanvas = this._gl.canvas;
  11696. if (this._gl.renderbufferStorageMultisample) {
  11697. this._webGLVersion = 2.0;
  11698. }
  11699. options.stencil = this._gl.getContextAttributes().stencil;
  11700. }
  11701. // Viewport
  11702. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11703. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11704. this.resize();
  11705. this._isStencilEnable = options.stencil ? true : false;
  11706. this._initGLContext();
  11707. if (canvas) {
  11708. // Fullscreen
  11709. this._onFullscreenChange = function () {
  11710. if (document.fullscreen !== undefined) {
  11711. _this.isFullscreen = document.fullscreen;
  11712. }
  11713. else if (document.mozFullScreen !== undefined) {
  11714. _this.isFullscreen = document.mozFullScreen;
  11715. }
  11716. else if (document.webkitIsFullScreen !== undefined) {
  11717. _this.isFullscreen = document.webkitIsFullScreen;
  11718. }
  11719. else if (document.msIsFullScreen !== undefined) {
  11720. _this.isFullscreen = document.msIsFullScreen;
  11721. }
  11722. // Pointer lock
  11723. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11724. canvas.requestPointerLock = canvas.requestPointerLock ||
  11725. canvas.msRequestPointerLock ||
  11726. canvas.mozRequestPointerLock ||
  11727. canvas.webkitRequestPointerLock;
  11728. if (canvas.requestPointerLock) {
  11729. canvas.requestPointerLock();
  11730. }
  11731. }
  11732. };
  11733. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11734. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11735. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11736. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11737. // Pointer lock
  11738. this._onPointerLockChange = function () {
  11739. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11740. document.webkitPointerLockElement === canvas ||
  11741. document.msPointerLockElement === canvas ||
  11742. document.pointerLockElement === canvas);
  11743. };
  11744. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11745. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11746. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11747. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11748. this._onVRDisplayPointerRestricted = function () {
  11749. if (canvas) {
  11750. canvas.requestPointerLock();
  11751. }
  11752. };
  11753. this._onVRDisplayPointerUnrestricted = function () {
  11754. document.exitPointerLock();
  11755. };
  11756. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11757. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11758. }
  11759. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11760. Engine.audioEngine = new BABYLON.AudioEngine();
  11761. }
  11762. // Prepare buffer pointers
  11763. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11764. this._currentBufferPointers[i] = new BufferPointer();
  11765. }
  11766. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11767. // Load WebVR Devices
  11768. if (options.autoEnableWebVR) {
  11769. this.initWebVR();
  11770. }
  11771. // Detect if we are running on a faulty buggy OS.
  11772. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11773. // Detect if we are running on a faulty buggy desktop OS.
  11774. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11775. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11776. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11777. }
  11778. Object.defineProperty(Engine, "LastCreatedEngine", {
  11779. /**
  11780. * Gets the latest created engine
  11781. */
  11782. get: function () {
  11783. if (Engine.Instances.length === 0) {
  11784. return null;
  11785. }
  11786. return Engine.Instances[Engine.Instances.length - 1];
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine, "LastCreatedScene", {
  11792. /**
  11793. * Gets the latest created scene
  11794. */
  11795. get: function () {
  11796. var lastCreatedEngine = Engine.LastCreatedEngine;
  11797. if (!lastCreatedEngine) {
  11798. return null;
  11799. }
  11800. if (lastCreatedEngine.scenes.length === 0) {
  11801. return null;
  11802. }
  11803. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11804. },
  11805. enumerable: true,
  11806. configurable: true
  11807. });
  11808. /**
  11809. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11810. * @param flag defines which part of the materials must be marked as dirty
  11811. * @param predicate defines a predicate used to filter which materials should be affected
  11812. */
  11813. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11814. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11815. var engine = Engine.Instances[engineIndex];
  11816. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11817. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11818. }
  11819. }
  11820. };
  11821. Object.defineProperty(Engine, "Version", {
  11822. /**
  11823. * Returns the current version of the framework
  11824. */
  11825. get: function () {
  11826. return "3.3.0-beta.5";
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11832. /**
  11833. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11834. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11835. */
  11836. get: function () {
  11837. return this._vrExclusivePointerMode;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11843. /**
  11844. * Gets a boolean indicating that the engine supports uniform buffers
  11845. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11846. */
  11847. get: function () {
  11848. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11854. /**
  11855. * Gets a boolean indicating that only power of 2 textures are supported
  11856. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11857. */
  11858. get: function () {
  11859. return this._webGLVersion < 2 || this.forcePOTTextures;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11865. /**
  11866. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11867. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11868. */
  11869. get: function () {
  11870. return this._doNotHandleContextLost;
  11871. },
  11872. set: function (value) {
  11873. this._doNotHandleContextLost = value;
  11874. },
  11875. enumerable: true,
  11876. configurable: true
  11877. });
  11878. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11879. /**
  11880. * Gets the performance monitor attached to this engine
  11881. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11882. */
  11883. get: function () {
  11884. return this._performanceMonitor;
  11885. },
  11886. enumerable: true,
  11887. configurable: true
  11888. });
  11889. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11890. /**
  11891. * Gets the list of texture formats supported
  11892. */
  11893. get: function () {
  11894. return this._texturesSupported;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11900. /**
  11901. * Gets the list of texture formats in use
  11902. */
  11903. get: function () {
  11904. return this._textureFormatInUse;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(Engine.prototype, "currentViewport", {
  11910. /**
  11911. * Gets the current viewport
  11912. */
  11913. get: function () {
  11914. return this._cachedViewport;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11920. /**
  11921. * Gets the default empty texture
  11922. */
  11923. get: function () {
  11924. if (!this._emptyTexture) {
  11925. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11926. }
  11927. return this._emptyTexture;
  11928. },
  11929. enumerable: true,
  11930. configurable: true
  11931. });
  11932. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11933. /**
  11934. * Gets the default empty 3D texture
  11935. */
  11936. get: function () {
  11937. if (!this._emptyTexture3D) {
  11938. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11939. }
  11940. return this._emptyTexture3D;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11946. /**
  11947. * Gets the default empty cube texture
  11948. */
  11949. get: function () {
  11950. if (!this._emptyCubeTexture) {
  11951. var faceData = new Uint8Array(4);
  11952. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11953. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11954. }
  11955. return this._emptyCubeTexture;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Engine.prototype._rebuildInternalTextures = function () {
  11961. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11962. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11963. var internalTexture = currentState_1[_i];
  11964. internalTexture._rebuild();
  11965. }
  11966. };
  11967. Engine.prototype._rebuildEffects = function () {
  11968. for (var key in this._compiledEffects) {
  11969. var effect = this._compiledEffects[key];
  11970. effect._prepareEffect();
  11971. }
  11972. BABYLON.Effect.ResetCache();
  11973. };
  11974. Engine.prototype._rebuildBuffers = function () {
  11975. // Index / Vertex
  11976. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11977. var scene = _a[_i];
  11978. scene.resetCachedMaterial();
  11979. scene._rebuildGeometries();
  11980. scene._rebuildTextures();
  11981. }
  11982. // Uniforms
  11983. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11984. var uniformBuffer = _c[_b];
  11985. uniformBuffer._rebuild();
  11986. }
  11987. };
  11988. Engine.prototype._initGLContext = function () {
  11989. // Caps
  11990. this._caps = new EngineCapabilities();
  11991. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11992. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11993. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11994. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11995. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11996. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11997. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11998. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11999. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12000. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12001. // Infos
  12002. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12003. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12004. if (rendererInfo != null) {
  12005. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12006. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12007. }
  12008. if (!this._glVendor) {
  12009. this._glVendor = "Unknown vendor";
  12010. }
  12011. if (!this._glRenderer) {
  12012. this._glRenderer = "Unknown renderer";
  12013. }
  12014. // Constants
  12015. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12016. if (this._gl.RGBA16F !== 0x881A) {
  12017. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12018. }
  12019. if (this._gl.RGBA32F !== 0x8814) {
  12020. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12021. }
  12022. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12023. this._gl.DEPTH24_STENCIL8 = 35056;
  12024. }
  12025. // Extensions
  12026. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12027. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12028. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12029. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12030. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12031. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12032. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12033. 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');
  12034. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12035. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12036. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12037. this._caps.highPrecisionShaderSupported = true;
  12038. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12039. if (this._caps.timerQuery) {
  12040. if (this._webGLVersion === 1) {
  12041. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12042. }
  12043. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12044. }
  12045. // Checks if some of the format renders first to allow the use of webgl inspector.
  12046. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12047. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12048. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12049. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12050. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12051. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12052. if (this._webGLVersion > 1) {
  12053. this._gl.HALF_FLOAT_OES = 0x140B;
  12054. }
  12055. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12056. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12057. // Draw buffers
  12058. if (this._webGLVersion > 1) {
  12059. this._caps.drawBuffersExtension = true;
  12060. }
  12061. else {
  12062. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12063. if (drawBuffersExtension !== null) {
  12064. this._caps.drawBuffersExtension = true;
  12065. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12066. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12067. for (var i = 0; i < 16; i++) {
  12068. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12069. }
  12070. }
  12071. else {
  12072. this._caps.drawBuffersExtension = false;
  12073. }
  12074. }
  12075. // Depth Texture
  12076. if (this._webGLVersion > 1) {
  12077. this._caps.depthTextureExtension = true;
  12078. }
  12079. else {
  12080. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12081. if (depthTextureExtension != null) {
  12082. this._caps.depthTextureExtension = true;
  12083. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12084. }
  12085. }
  12086. // Vertex array object
  12087. if (this._webGLVersion > 1) {
  12088. this._caps.vertexArrayObject = true;
  12089. }
  12090. else {
  12091. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12092. if (vertexArrayObjectExtension != null) {
  12093. this._caps.vertexArrayObject = true;
  12094. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12095. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12096. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12097. }
  12098. else {
  12099. this._caps.vertexArrayObject = false;
  12100. }
  12101. }
  12102. // Instances count
  12103. if (this._webGLVersion > 1) {
  12104. this._caps.instancedArrays = true;
  12105. }
  12106. else {
  12107. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12108. if (instanceExtension != null) {
  12109. this._caps.instancedArrays = true;
  12110. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12111. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12112. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12113. }
  12114. else {
  12115. this._caps.instancedArrays = false;
  12116. }
  12117. }
  12118. // Intelligently add supported compressed formats in order to check for.
  12119. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12120. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12121. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12122. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12123. if (this._caps.astc)
  12124. this.texturesSupported.push('-astc.ktx');
  12125. if (this._caps.s3tc)
  12126. this.texturesSupported.push('-dxt.ktx');
  12127. if (this._caps.pvrtc)
  12128. this.texturesSupported.push('-pvrtc.ktx');
  12129. if (this._caps.etc2)
  12130. this.texturesSupported.push('-etc2.ktx');
  12131. if (this._caps.etc1)
  12132. this.texturesSupported.push('-etc1.ktx');
  12133. if (this._gl.getShaderPrecisionFormat) {
  12134. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12135. if (highp) {
  12136. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12137. }
  12138. }
  12139. // Depth buffer
  12140. this.setDepthBuffer(true);
  12141. this.setDepthFunctionToLessOrEqual();
  12142. this.setDepthWrite(true);
  12143. // Texture maps
  12144. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12145. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12146. this._nextFreeTextureSlots.push(slot);
  12147. }
  12148. };
  12149. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12150. /**
  12151. * Gets version of the current webGL context
  12152. */
  12153. get: function () {
  12154. return this._webGLVersion;
  12155. },
  12156. enumerable: true,
  12157. configurable: true
  12158. });
  12159. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12160. /**
  12161. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12162. */
  12163. get: function () {
  12164. return this._isStencilEnable;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Engine.prototype._prepareWorkingCanvas = function () {
  12170. if (this._workingCanvas) {
  12171. return;
  12172. }
  12173. this._workingCanvas = document.createElement("canvas");
  12174. var context = this._workingCanvas.getContext("2d");
  12175. if (context) {
  12176. this._workingContext = context;
  12177. }
  12178. };
  12179. /**
  12180. * Reset the texture cache to empty state
  12181. */
  12182. Engine.prototype.resetTextureCache = function () {
  12183. for (var key in this._boundTexturesCache) {
  12184. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12185. continue;
  12186. }
  12187. var boundTexture = this._boundTexturesCache[key];
  12188. if (boundTexture) {
  12189. this._removeDesignatedSlot(boundTexture);
  12190. }
  12191. this._boundTexturesCache[key] = null;
  12192. }
  12193. if (!this.disableTextureBindingOptimization) {
  12194. this._nextFreeTextureSlots = [];
  12195. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12196. this._nextFreeTextureSlots.push(slot);
  12197. }
  12198. }
  12199. this._currentTextureChannel = -1;
  12200. };
  12201. /**
  12202. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12203. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12204. * @returns true if engine is in deterministic lock step mode
  12205. */
  12206. Engine.prototype.isDeterministicLockStep = function () {
  12207. return this._deterministicLockstep;
  12208. };
  12209. /**
  12210. * Gets the max steps when engine is running in deterministic lock step
  12211. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12212. * @returns the max steps
  12213. */
  12214. Engine.prototype.getLockstepMaxSteps = function () {
  12215. return this._lockstepMaxSteps;
  12216. };
  12217. /**
  12218. * Gets an object containing information about the current webGL context
  12219. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12220. */
  12221. Engine.prototype.getGlInfo = function () {
  12222. return {
  12223. vendor: this._glVendor,
  12224. renderer: this._glRenderer,
  12225. version: this._glVersion
  12226. };
  12227. };
  12228. /**
  12229. * Gets current aspect ratio
  12230. * @param camera defines the camera to use to get the aspect ratio
  12231. * @param useScreen defines if screen size must be used (or the current render target if any)
  12232. * @returns a number defining the aspect ratio
  12233. */
  12234. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12235. if (useScreen === void 0) { useScreen = false; }
  12236. var viewport = camera.viewport;
  12237. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12238. };
  12239. /**
  12240. * Gets current screen aspect ratio
  12241. * @returns a number defining the aspect ratio
  12242. */
  12243. Engine.prototype.getScreenAspectRatio = function () {
  12244. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12245. };
  12246. /**
  12247. * Gets the current render width
  12248. * @param useScreen defines if screen size must be used (or the current render target if any)
  12249. * @returns a number defining the current render width
  12250. */
  12251. Engine.prototype.getRenderWidth = function (useScreen) {
  12252. if (useScreen === void 0) { useScreen = false; }
  12253. if (!useScreen && this._currentRenderTarget) {
  12254. return this._currentRenderTarget.width;
  12255. }
  12256. return this._gl.drawingBufferWidth;
  12257. };
  12258. /**
  12259. * Gets the current render height
  12260. * @param useScreen defines if screen size must be used (or the current render target if any)
  12261. * @returns a number defining the current render height
  12262. */
  12263. Engine.prototype.getRenderHeight = function (useScreen) {
  12264. if (useScreen === void 0) { useScreen = false; }
  12265. if (!useScreen && this._currentRenderTarget) {
  12266. return this._currentRenderTarget.height;
  12267. }
  12268. return this._gl.drawingBufferHeight;
  12269. };
  12270. /**
  12271. * Gets the HTML canvas attached with the current webGL context
  12272. * @returns a HTML canvas
  12273. */
  12274. Engine.prototype.getRenderingCanvas = function () {
  12275. return this._renderingCanvas;
  12276. };
  12277. /**
  12278. * Gets the client rect of the HTML canvas attached with the current webGL context
  12279. * @returns a client rectanglee
  12280. */
  12281. Engine.prototype.getRenderingCanvasClientRect = function () {
  12282. if (!this._renderingCanvas) {
  12283. return null;
  12284. }
  12285. return this._renderingCanvas.getBoundingClientRect();
  12286. };
  12287. /**
  12288. * Defines the hardware scaling level.
  12289. * By default the hardware scaling level is computed from the window device ratio.
  12290. * 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.
  12291. * @param level defines the level to use
  12292. */
  12293. Engine.prototype.setHardwareScalingLevel = function (level) {
  12294. this._hardwareScalingLevel = level;
  12295. this.resize();
  12296. };
  12297. /**
  12298. * Gets the current hardware scaling level.
  12299. * By default the hardware scaling level is computed from the window device ratio.
  12300. * 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.
  12301. * @returns a number indicating the current hardware scaling level
  12302. */
  12303. Engine.prototype.getHardwareScalingLevel = function () {
  12304. return this._hardwareScalingLevel;
  12305. };
  12306. /**
  12307. * Gets the list of loaded textures
  12308. * @returns an array containing all loaded textures
  12309. */
  12310. Engine.prototype.getLoadedTexturesCache = function () {
  12311. return this._internalTexturesCache;
  12312. };
  12313. /**
  12314. * Gets the object containing all engine capabilities
  12315. * @returns the EngineCapabilities object
  12316. */
  12317. Engine.prototype.getCaps = function () {
  12318. return this._caps;
  12319. };
  12320. Object.defineProperty(Engine.prototype, "drawCalls", {
  12321. /** @hidden */
  12322. get: function () {
  12323. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12324. return 0;
  12325. },
  12326. enumerable: true,
  12327. configurable: true
  12328. });
  12329. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12330. /** @hidden */
  12331. get: function () {
  12332. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12333. return null;
  12334. },
  12335. enumerable: true,
  12336. configurable: true
  12337. });
  12338. /**
  12339. * Gets the current depth function
  12340. * @returns a number defining the depth function
  12341. */
  12342. Engine.prototype.getDepthFunction = function () {
  12343. return this._depthCullingState.depthFunc;
  12344. };
  12345. /**
  12346. * Sets the current depth function
  12347. * @param depthFunc defines the function to use
  12348. */
  12349. Engine.prototype.setDepthFunction = function (depthFunc) {
  12350. this._depthCullingState.depthFunc = depthFunc;
  12351. };
  12352. /**
  12353. * Sets the current depth function to GREATER
  12354. */
  12355. Engine.prototype.setDepthFunctionToGreater = function () {
  12356. this._depthCullingState.depthFunc = this._gl.GREATER;
  12357. };
  12358. /**
  12359. * Sets the current depth function to GEQUAL
  12360. */
  12361. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12362. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12363. };
  12364. /**
  12365. * Sets the current depth function to LESS
  12366. */
  12367. Engine.prototype.setDepthFunctionToLess = function () {
  12368. this._depthCullingState.depthFunc = this._gl.LESS;
  12369. };
  12370. /**
  12371. * Sets the current depth function to LEQUAL
  12372. */
  12373. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12374. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12375. };
  12376. /**
  12377. * Gets a boolean indicating if stencil buffer is enabled
  12378. * @returns the current stencil buffer state
  12379. */
  12380. Engine.prototype.getStencilBuffer = function () {
  12381. return this._stencilState.stencilTest;
  12382. };
  12383. /**
  12384. * Enable or disable the stencil buffer
  12385. * @param enable defines if the stencil buffer must be enabled or disabled
  12386. */
  12387. Engine.prototype.setStencilBuffer = function (enable) {
  12388. this._stencilState.stencilTest = enable;
  12389. };
  12390. /**
  12391. * Gets the current stencil mask
  12392. * @returns a number defining the new stencil mask to use
  12393. */
  12394. Engine.prototype.getStencilMask = function () {
  12395. return this._stencilState.stencilMask;
  12396. };
  12397. /**
  12398. * Sets the current stencil mask
  12399. * @param mask defines the new stencil mask to use
  12400. */
  12401. Engine.prototype.setStencilMask = function (mask) {
  12402. this._stencilState.stencilMask = mask;
  12403. };
  12404. /**
  12405. * Gets the current stencil function
  12406. * @returns a number defining the stencil function to use
  12407. */
  12408. Engine.prototype.getStencilFunction = function () {
  12409. return this._stencilState.stencilFunc;
  12410. };
  12411. /**
  12412. * Gets the current stencil reference value
  12413. * @returns a number defining the stencil reference value to use
  12414. */
  12415. Engine.prototype.getStencilFunctionReference = function () {
  12416. return this._stencilState.stencilFuncRef;
  12417. };
  12418. /**
  12419. * Gets the current stencil mask
  12420. * @returns a number defining the stencil mask to use
  12421. */
  12422. Engine.prototype.getStencilFunctionMask = function () {
  12423. return this._stencilState.stencilFuncMask;
  12424. };
  12425. /**
  12426. * Sets the current stencil function
  12427. * @param stencilFunc defines the new stencil function to use
  12428. */
  12429. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12430. this._stencilState.stencilFunc = stencilFunc;
  12431. };
  12432. /**
  12433. * Sets the current stencil reference
  12434. * @param reference defines the new stencil reference to use
  12435. */
  12436. Engine.prototype.setStencilFunctionReference = function (reference) {
  12437. this._stencilState.stencilFuncRef = reference;
  12438. };
  12439. /**
  12440. * Sets the current stencil mask
  12441. * @param mask defines the new stencil mask to use
  12442. */
  12443. Engine.prototype.setStencilFunctionMask = function (mask) {
  12444. this._stencilState.stencilFuncMask = mask;
  12445. };
  12446. /**
  12447. * Gets the current stencil operation when stencil fails
  12448. * @returns a number defining stencil operation to use when stencil fails
  12449. */
  12450. Engine.prototype.getStencilOperationFail = function () {
  12451. return this._stencilState.stencilOpStencilFail;
  12452. };
  12453. /**
  12454. * Gets the current stencil operation when depth fails
  12455. * @returns a number defining stencil operation to use when depth fails
  12456. */
  12457. Engine.prototype.getStencilOperationDepthFail = function () {
  12458. return this._stencilState.stencilOpDepthFail;
  12459. };
  12460. /**
  12461. * Gets the current stencil operation when stencil passes
  12462. * @returns a number defining stencil operation to use when stencil passes
  12463. */
  12464. Engine.prototype.getStencilOperationPass = function () {
  12465. return this._stencilState.stencilOpStencilDepthPass;
  12466. };
  12467. /**
  12468. * Sets the stencil operation to use when stencil fails
  12469. * @param operation defines the stencil operation to use when stencil fails
  12470. */
  12471. Engine.prototype.setStencilOperationFail = function (operation) {
  12472. this._stencilState.stencilOpStencilFail = operation;
  12473. };
  12474. /**
  12475. * Sets the stencil operation to use when depth fails
  12476. * @param operation defines the stencil operation to use when depth fails
  12477. */
  12478. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12479. this._stencilState.stencilOpDepthFail = operation;
  12480. };
  12481. /**
  12482. * Sets the stencil operation to use when stencil passes
  12483. * @param operation defines the stencil operation to use when stencil passes
  12484. */
  12485. Engine.prototype.setStencilOperationPass = function (operation) {
  12486. this._stencilState.stencilOpStencilDepthPass = operation;
  12487. };
  12488. /**
  12489. * Sets a boolean indicating if the dithering state is enabled or disabled
  12490. * @param value defines the dithering state
  12491. */
  12492. Engine.prototype.setDitheringState = function (value) {
  12493. if (value) {
  12494. this._gl.enable(this._gl.DITHER);
  12495. }
  12496. else {
  12497. this._gl.disable(this._gl.DITHER);
  12498. }
  12499. };
  12500. /**
  12501. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12502. * @param value defines the rasterizer state
  12503. */
  12504. Engine.prototype.setRasterizerState = function (value) {
  12505. if (value) {
  12506. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12507. }
  12508. else {
  12509. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12510. }
  12511. };
  12512. /**
  12513. * stop executing a render loop function and remove it from the execution array
  12514. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12515. */
  12516. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12517. if (!renderFunction) {
  12518. this._activeRenderLoops = [];
  12519. return;
  12520. }
  12521. var index = this._activeRenderLoops.indexOf(renderFunction);
  12522. if (index >= 0) {
  12523. this._activeRenderLoops.splice(index, 1);
  12524. }
  12525. };
  12526. /** @hidden */
  12527. Engine.prototype._renderLoop = function () {
  12528. if (!this._contextWasLost) {
  12529. var shouldRender = true;
  12530. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12531. shouldRender = false;
  12532. }
  12533. if (shouldRender) {
  12534. // Start new frame
  12535. this.beginFrame();
  12536. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12537. var renderFunction = this._activeRenderLoops[index];
  12538. renderFunction();
  12539. }
  12540. // Present
  12541. this.endFrame();
  12542. }
  12543. }
  12544. if (this._activeRenderLoops.length > 0) {
  12545. // Register new frame
  12546. var requester = null;
  12547. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12548. requester = this._vrDisplay;
  12549. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12550. }
  12551. else {
  12552. this._renderingQueueLaunched = false;
  12553. }
  12554. };
  12555. /**
  12556. * Register and execute a render loop. The engine can have more than one render function
  12557. * @param renderFunction defines the function to continuously execute
  12558. */
  12559. Engine.prototype.runRenderLoop = function (renderFunction) {
  12560. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12561. return;
  12562. }
  12563. this._activeRenderLoops.push(renderFunction);
  12564. if (!this._renderingQueueLaunched) {
  12565. this._renderingQueueLaunched = true;
  12566. this._bindedRenderFunction = this._renderLoop.bind(this);
  12567. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12568. }
  12569. };
  12570. /**
  12571. * Toggle full screen mode
  12572. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12573. * @param options defines an option object to be sent to the requestFullscreen function
  12574. */
  12575. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12576. if (this.isFullscreen) {
  12577. BABYLON.Tools.ExitFullscreen();
  12578. }
  12579. else {
  12580. this._pointerLockRequested = requestPointerLock;
  12581. if (this._renderingCanvas) {
  12582. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12583. }
  12584. }
  12585. };
  12586. /**
  12587. * Clear the current render buffer or the current render target (if any is set up)
  12588. * @param color defines the color to use
  12589. * @param backBuffer defines if the back buffer must be cleared
  12590. * @param depth defines if the depth buffer must be cleared
  12591. * @param stencil defines if the stencil buffer must be cleared
  12592. */
  12593. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12594. if (stencil === void 0) { stencil = false; }
  12595. this.applyStates();
  12596. var mode = 0;
  12597. if (backBuffer && color) {
  12598. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12599. mode |= this._gl.COLOR_BUFFER_BIT;
  12600. }
  12601. if (depth) {
  12602. this._gl.clearDepth(1.0);
  12603. mode |= this._gl.DEPTH_BUFFER_BIT;
  12604. }
  12605. if (stencil) {
  12606. this._gl.clearStencil(0);
  12607. mode |= this._gl.STENCIL_BUFFER_BIT;
  12608. }
  12609. this._gl.clear(mode);
  12610. };
  12611. /**
  12612. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12613. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12614. * @param y defines the y-coordinate of the corner of the clear rectangle
  12615. * @param width defines the width of the clear rectangle
  12616. * @param height defines the height of the clear rectangle
  12617. * @param clearColor defines the clear color
  12618. */
  12619. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12620. var gl = this._gl;
  12621. // Save state
  12622. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12623. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12624. // Change state
  12625. gl.enable(gl.SCISSOR_TEST);
  12626. gl.scissor(x, y, width, height);
  12627. // Clear
  12628. this.clear(clearColor, true, true, true);
  12629. // Restore state
  12630. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12631. if (curScissor === true) {
  12632. gl.enable(gl.SCISSOR_TEST);
  12633. }
  12634. else {
  12635. gl.disable(gl.SCISSOR_TEST);
  12636. }
  12637. };
  12638. /** @hidden */
  12639. Engine.prototype._viewport = function (x, y, width, height) {
  12640. if (x !== this._viewportCached.x ||
  12641. y !== this._viewportCached.y ||
  12642. width !== this._viewportCached.z ||
  12643. height !== this._viewportCached.w) {
  12644. this._viewportCached.x = x;
  12645. this._viewportCached.y = y;
  12646. this._viewportCached.z = width;
  12647. this._viewportCached.w = height;
  12648. this._gl.viewport(x, y, width, height);
  12649. }
  12650. };
  12651. /**
  12652. * Set the WebGL's viewport
  12653. * @param viewport defines the viewport element to be used
  12654. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12655. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12656. */
  12657. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12658. var width = requiredWidth || this.getRenderWidth();
  12659. var height = requiredHeight || this.getRenderHeight();
  12660. var x = viewport.x || 0;
  12661. var y = viewport.y || 0;
  12662. this._cachedViewport = viewport;
  12663. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12664. };
  12665. /**
  12666. * Directly set the WebGL Viewport
  12667. * @param x defines the x coordinate of the viewport (in screen space)
  12668. * @param y defines the y coordinate of the viewport (in screen space)
  12669. * @param width defines the width of the viewport (in screen space)
  12670. * @param height defines the height of the viewport (in screen space)
  12671. * @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
  12672. */
  12673. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12674. var currentViewport = this._cachedViewport;
  12675. this._cachedViewport = null;
  12676. this._viewport(x, y, width, height);
  12677. return currentViewport;
  12678. };
  12679. /**
  12680. * Begin a new frame
  12681. */
  12682. Engine.prototype.beginFrame = function () {
  12683. this.onBeginFrameObservable.notifyObservers(this);
  12684. this._measureFps();
  12685. };
  12686. /**
  12687. * Enf the current frame
  12688. */
  12689. Engine.prototype.endFrame = function () {
  12690. // Force a flush in case we are using a bad OS.
  12691. if (this._badOS) {
  12692. this.flushFramebuffer();
  12693. }
  12694. // Submit frame to the vr device, if enabled
  12695. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12696. // TODO: We should only submit the frame if we read frameData successfully.
  12697. this._vrDisplay.submitFrame();
  12698. }
  12699. this.onEndFrameObservable.notifyObservers(this);
  12700. };
  12701. /**
  12702. * Resize the view according to the canvas' size
  12703. */
  12704. Engine.prototype.resize = function () {
  12705. // We're not resizing the size of the canvas while in VR mode & presenting
  12706. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12707. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12708. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12709. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12710. }
  12711. };
  12712. /**
  12713. * Force a specific size of the canvas
  12714. * @param width defines the new canvas' width
  12715. * @param height defines the new canvas' height
  12716. */
  12717. Engine.prototype.setSize = function (width, height) {
  12718. if (!this._renderingCanvas) {
  12719. return;
  12720. }
  12721. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12722. return;
  12723. }
  12724. this._renderingCanvas.width = width;
  12725. this._renderingCanvas.height = height;
  12726. for (var index = 0; index < this.scenes.length; index++) {
  12727. var scene = this.scenes[index];
  12728. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12729. var cam = scene.cameras[camIndex];
  12730. cam._currentRenderId = 0;
  12731. }
  12732. }
  12733. if (this.onResizeObservable.hasObservers) {
  12734. this.onResizeObservable.notifyObservers(this);
  12735. }
  12736. };
  12737. // WebVR functions
  12738. /**
  12739. * Gets a boolean indicating if a webVR device was detected
  12740. * @returns true if a webVR device was detected
  12741. */
  12742. Engine.prototype.isVRDevicePresent = function () {
  12743. return !!this._vrDisplay;
  12744. };
  12745. /**
  12746. * Gets the current webVR device
  12747. * @returns the current webVR device (or null)
  12748. */
  12749. Engine.prototype.getVRDevice = function () {
  12750. return this._vrDisplay;
  12751. };
  12752. /**
  12753. * Initializes a webVR display and starts listening to display change events
  12754. * The onVRDisplayChangedObservable will be notified upon these changes
  12755. * @returns The onVRDisplayChangedObservable
  12756. */
  12757. Engine.prototype.initWebVR = function () {
  12758. this.initWebVRAsync();
  12759. return this.onVRDisplayChangedObservable;
  12760. };
  12761. /**
  12762. * Initializes a webVR display and starts listening to display change events
  12763. * The onVRDisplayChangedObservable will be notified upon these changes
  12764. * @returns A promise containing a VRDisplay and if vr is supported
  12765. */
  12766. Engine.prototype.initWebVRAsync = function () {
  12767. var _this = this;
  12768. var notifyObservers = function () {
  12769. var eventArgs = {
  12770. vrDisplay: _this._vrDisplay,
  12771. vrSupported: _this._vrSupported
  12772. };
  12773. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12774. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12775. };
  12776. if (!this._onVrDisplayConnect) {
  12777. this._onVrDisplayConnect = function (event) {
  12778. _this._vrDisplay = event.display;
  12779. notifyObservers();
  12780. };
  12781. this._onVrDisplayDisconnect = function () {
  12782. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12783. _this._vrDisplay = undefined;
  12784. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12785. notifyObservers();
  12786. };
  12787. this._onVrDisplayPresentChange = function () {
  12788. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12789. };
  12790. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12791. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12792. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12793. }
  12794. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12795. this._webVRInitPromise.then(notifyObservers);
  12796. return this._webVRInitPromise;
  12797. };
  12798. /**
  12799. * Call this function to switch to webVR mode
  12800. * Will do nothing if webVR is not supported or if there is no webVR device
  12801. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12802. */
  12803. Engine.prototype.enableVR = function () {
  12804. var _this = this;
  12805. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12806. var onResolved = function () {
  12807. _this.onVRRequestPresentComplete.notifyObservers(true);
  12808. _this._onVRFullScreenTriggered();
  12809. };
  12810. var onRejected = function () {
  12811. _this.onVRRequestPresentComplete.notifyObservers(false);
  12812. };
  12813. this.onVRRequestPresentStart.notifyObservers(this);
  12814. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12815. }
  12816. };
  12817. /**
  12818. * Call this function to leave webVR mode
  12819. * Will do nothing if webVR is not supported or if there is no webVR device
  12820. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12821. */
  12822. Engine.prototype.disableVR = function () {
  12823. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12824. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12825. }
  12826. };
  12827. Engine.prototype._getVRDisplaysAsync = function () {
  12828. var _this = this;
  12829. return new Promise(function (res, rej) {
  12830. if (navigator.getVRDisplays) {
  12831. navigator.getVRDisplays().then(function (devices) {
  12832. _this._vrSupported = true;
  12833. // note that devices may actually be an empty array. This is fine;
  12834. // we expect this._vrDisplay to be undefined in this case.
  12835. _this._vrDisplay = devices[0];
  12836. res({
  12837. vrDisplay: _this._vrDisplay,
  12838. vrSupported: _this._vrSupported
  12839. });
  12840. });
  12841. }
  12842. else {
  12843. _this._vrDisplay = undefined;
  12844. _this._vrSupported = false;
  12845. res({
  12846. vrDisplay: _this._vrDisplay,
  12847. vrSupported: _this._vrSupported
  12848. });
  12849. }
  12850. });
  12851. };
  12852. /**
  12853. * Binds the frame buffer to the specified texture.
  12854. * @param texture The texture to render to or null for the default canvas
  12855. * @param faceIndex The face of the texture to render to in case of cube texture
  12856. * @param requiredWidth The width of the target to render to
  12857. * @param requiredHeight The height of the target to render to
  12858. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12859. * @param depthStencilTexture The depth stencil texture to use to render
  12860. * @param lodLevel defines le lod level to bind to the frame buffer
  12861. */
  12862. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12863. if (lodLevel === void 0) { lodLevel = 0; }
  12864. if (this._currentRenderTarget) {
  12865. this.unBindFramebuffer(this._currentRenderTarget);
  12866. }
  12867. this._currentRenderTarget = texture;
  12868. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12869. var gl = this._gl;
  12870. if (texture.isCube) {
  12871. if (faceIndex === undefined) {
  12872. faceIndex = 0;
  12873. }
  12874. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12875. if (depthStencilTexture) {
  12876. if (depthStencilTexture._generateStencilBuffer) {
  12877. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12878. }
  12879. else {
  12880. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12881. }
  12882. }
  12883. }
  12884. if (this._cachedViewport && !forceFullscreenViewport) {
  12885. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12886. }
  12887. else {
  12888. if (!requiredWidth) {
  12889. requiredWidth = texture.width;
  12890. if (lodLevel) {
  12891. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12892. }
  12893. }
  12894. if (!requiredHeight) {
  12895. requiredHeight = texture.height;
  12896. if (lodLevel) {
  12897. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12898. }
  12899. }
  12900. this._viewport(0, 0, requiredWidth, requiredHeight);
  12901. }
  12902. this.wipeCaches();
  12903. };
  12904. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12905. if (this._currentFramebuffer !== framebuffer) {
  12906. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12907. this._currentFramebuffer = framebuffer;
  12908. }
  12909. };
  12910. /**
  12911. * Unbind the current render target texture from the webGL context
  12912. * @param texture defines the render target texture to unbind
  12913. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12914. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12915. */
  12916. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12917. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12918. this._currentRenderTarget = null;
  12919. // If MSAA, we need to bitblt back to main texture
  12920. var gl = this._gl;
  12921. if (texture._MSAAFramebuffer) {
  12922. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12923. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12924. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12925. }
  12926. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12927. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12928. gl.generateMipmap(gl.TEXTURE_2D);
  12929. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12930. }
  12931. if (onBeforeUnbind) {
  12932. if (texture._MSAAFramebuffer) {
  12933. // Bind the correct framebuffer
  12934. this.bindUnboundFramebuffer(texture._framebuffer);
  12935. }
  12936. onBeforeUnbind();
  12937. }
  12938. this.bindUnboundFramebuffer(null);
  12939. };
  12940. /**
  12941. * Unbind a list of render target textures from the webGL context
  12942. * This is used only when drawBuffer extension or webGL2 are active
  12943. * @param textures defines the render target textures to unbind
  12944. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12945. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12946. */
  12947. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12948. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12949. this._currentRenderTarget = null;
  12950. // If MSAA, we need to bitblt back to main texture
  12951. var gl = this._gl;
  12952. if (textures[0]._MSAAFramebuffer) {
  12953. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12954. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12955. var attachments = textures[0]._attachments;
  12956. if (!attachments) {
  12957. attachments = new Array(textures.length);
  12958. textures[0]._attachments = attachments;
  12959. }
  12960. for (var i = 0; i < textures.length; i++) {
  12961. var texture = textures[i];
  12962. for (var j = 0; j < attachments.length; j++) {
  12963. attachments[j] = gl.NONE;
  12964. }
  12965. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12966. gl.readBuffer(attachments[i]);
  12967. gl.drawBuffers(attachments);
  12968. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12969. }
  12970. for (var i = 0; i < attachments.length; i++) {
  12971. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12972. }
  12973. gl.drawBuffers(attachments);
  12974. }
  12975. for (var i = 0; i < textures.length; i++) {
  12976. var texture = textures[i];
  12977. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12978. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12979. gl.generateMipmap(gl.TEXTURE_2D);
  12980. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12981. }
  12982. }
  12983. if (onBeforeUnbind) {
  12984. if (textures[0]._MSAAFramebuffer) {
  12985. // Bind the correct framebuffer
  12986. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12987. }
  12988. onBeforeUnbind();
  12989. }
  12990. this.bindUnboundFramebuffer(null);
  12991. };
  12992. /**
  12993. * Force the mipmap generation for the given render target texture
  12994. * @param texture defines the render target texture to use
  12995. */
  12996. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12997. if (texture.generateMipMaps) {
  12998. var gl = this._gl;
  12999. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13000. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13001. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13002. }
  13003. };
  13004. /**
  13005. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13006. */
  13007. Engine.prototype.flushFramebuffer = function () {
  13008. this._gl.flush();
  13009. };
  13010. /**
  13011. * Unbind the current render target and bind the default framebuffer
  13012. */
  13013. Engine.prototype.restoreDefaultFramebuffer = function () {
  13014. if (this._currentRenderTarget) {
  13015. this.unBindFramebuffer(this._currentRenderTarget);
  13016. }
  13017. else {
  13018. this.bindUnboundFramebuffer(null);
  13019. }
  13020. if (this._cachedViewport) {
  13021. this.setViewport(this._cachedViewport);
  13022. }
  13023. this.wipeCaches();
  13024. };
  13025. // UBOs
  13026. /**
  13027. * Create an uniform buffer
  13028. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13029. * @param elements defines the content of the uniform buffer
  13030. * @returns the webGL uniform buffer
  13031. */
  13032. Engine.prototype.createUniformBuffer = function (elements) {
  13033. var ubo = this._gl.createBuffer();
  13034. if (!ubo) {
  13035. throw new Error("Unable to create uniform buffer");
  13036. }
  13037. this.bindUniformBuffer(ubo);
  13038. if (elements instanceof Float32Array) {
  13039. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13040. }
  13041. else {
  13042. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13043. }
  13044. this.bindUniformBuffer(null);
  13045. ubo.references = 1;
  13046. return ubo;
  13047. };
  13048. /**
  13049. * Create a dynamic uniform buffer
  13050. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13051. * @param elements defines the content of the uniform buffer
  13052. * @returns the webGL uniform buffer
  13053. */
  13054. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13055. var ubo = this._gl.createBuffer();
  13056. if (!ubo) {
  13057. throw new Error("Unable to create dynamic uniform buffer");
  13058. }
  13059. this.bindUniformBuffer(ubo);
  13060. if (elements instanceof Float32Array) {
  13061. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13062. }
  13063. else {
  13064. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13065. }
  13066. this.bindUniformBuffer(null);
  13067. ubo.references = 1;
  13068. return ubo;
  13069. };
  13070. /**
  13071. * Update an existing uniform buffer
  13072. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13073. * @param uniformBuffer defines the target uniform buffer
  13074. * @param elements defines the content to update
  13075. * @param offset defines the offset in the uniform buffer where update should start
  13076. * @param count defines the size of the data to update
  13077. */
  13078. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13079. this.bindUniformBuffer(uniformBuffer);
  13080. if (offset === undefined) {
  13081. offset = 0;
  13082. }
  13083. if (count === undefined) {
  13084. if (elements instanceof Float32Array) {
  13085. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13086. }
  13087. else {
  13088. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13089. }
  13090. }
  13091. else {
  13092. if (elements instanceof Float32Array) {
  13093. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13094. }
  13095. else {
  13096. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13097. }
  13098. }
  13099. this.bindUniformBuffer(null);
  13100. };
  13101. // VBOs
  13102. Engine.prototype._resetVertexBufferBinding = function () {
  13103. this.bindArrayBuffer(null);
  13104. this._cachedVertexBuffers = null;
  13105. };
  13106. /**
  13107. * Creates a vertex buffer
  13108. * @param data the data for the vertex buffer
  13109. * @returns the new WebGL static buffer
  13110. */
  13111. Engine.prototype.createVertexBuffer = function (data) {
  13112. var vbo = this._gl.createBuffer();
  13113. if (!vbo) {
  13114. throw new Error("Unable to create vertex buffer");
  13115. }
  13116. this.bindArrayBuffer(vbo);
  13117. if (data instanceof Array) {
  13118. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13119. }
  13120. else {
  13121. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13122. }
  13123. this._resetVertexBufferBinding();
  13124. vbo.references = 1;
  13125. return vbo;
  13126. };
  13127. /**
  13128. * Creates a dynamic vertex buffer
  13129. * @param data the data for the dynamic vertex buffer
  13130. * @returns the new WebGL dynamic buffer
  13131. */
  13132. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13133. var vbo = this._gl.createBuffer();
  13134. if (!vbo) {
  13135. throw new Error("Unable to create dynamic vertex buffer");
  13136. }
  13137. this.bindArrayBuffer(vbo);
  13138. if (data instanceof Array) {
  13139. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13140. }
  13141. else {
  13142. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13143. }
  13144. this._resetVertexBufferBinding();
  13145. vbo.references = 1;
  13146. return vbo;
  13147. };
  13148. /**
  13149. * Update a dynamic index buffer
  13150. * @param indexBuffer defines the target index buffer
  13151. * @param indices defines the data to update
  13152. * @param offset defines the offset in the target index buffer where update should start
  13153. */
  13154. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13155. if (offset === void 0) { offset = 0; }
  13156. // Force cache update
  13157. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13158. this.bindIndexBuffer(indexBuffer);
  13159. var arrayBuffer;
  13160. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13161. arrayBuffer = indices;
  13162. }
  13163. else {
  13164. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13165. }
  13166. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13167. this._resetIndexBufferBinding();
  13168. };
  13169. /**
  13170. * Updates a dynamic vertex buffer.
  13171. * @param vertexBuffer the vertex buffer to update
  13172. * @param data the data used to update the vertex buffer
  13173. * @param byteOffset the byte offset of the data
  13174. * @param byteLength the byte length of the data
  13175. */
  13176. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13177. this.bindArrayBuffer(vertexBuffer);
  13178. if (byteOffset === undefined) {
  13179. byteOffset = 0;
  13180. }
  13181. if (byteLength === undefined) {
  13182. if (data instanceof Array) {
  13183. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13184. }
  13185. else {
  13186. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13187. }
  13188. }
  13189. else {
  13190. if (data instanceof Array) {
  13191. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13192. }
  13193. else {
  13194. if (data instanceof ArrayBuffer) {
  13195. data = new Uint8Array(data, byteOffset, byteLength);
  13196. }
  13197. else {
  13198. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13199. }
  13200. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13201. }
  13202. }
  13203. this._resetVertexBufferBinding();
  13204. };
  13205. Engine.prototype._resetIndexBufferBinding = function () {
  13206. this.bindIndexBuffer(null);
  13207. this._cachedIndexBuffer = null;
  13208. };
  13209. /**
  13210. * Creates a new index buffer
  13211. * @param indices defines the content of the index buffer
  13212. * @param updatable defines if the index buffer must be updatable
  13213. * @returns a new webGL buffer
  13214. */
  13215. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13216. var vbo = this._gl.createBuffer();
  13217. if (!vbo) {
  13218. throw new Error("Unable to create index buffer");
  13219. }
  13220. this.bindIndexBuffer(vbo);
  13221. // Check for 32 bits indices
  13222. var arrayBuffer;
  13223. var need32Bits = false;
  13224. if (indices instanceof Uint16Array) {
  13225. arrayBuffer = indices;
  13226. }
  13227. else {
  13228. //check 32 bit support
  13229. if (this._caps.uintIndices) {
  13230. if (indices instanceof Uint32Array) {
  13231. arrayBuffer = indices;
  13232. need32Bits = true;
  13233. }
  13234. else {
  13235. //number[] or Int32Array, check if 32 bit is necessary
  13236. for (var index = 0; index < indices.length; index++) {
  13237. if (indices[index] > 65535) {
  13238. need32Bits = true;
  13239. break;
  13240. }
  13241. }
  13242. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13243. }
  13244. }
  13245. else {
  13246. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13247. arrayBuffer = new Uint16Array(indices);
  13248. }
  13249. }
  13250. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13251. this._resetIndexBufferBinding();
  13252. vbo.references = 1;
  13253. vbo.is32Bits = need32Bits;
  13254. return vbo;
  13255. };
  13256. /**
  13257. * Bind a webGL buffer to the webGL context
  13258. * @param buffer defines the buffer to bind
  13259. */
  13260. Engine.prototype.bindArrayBuffer = function (buffer) {
  13261. if (!this._vaoRecordInProgress) {
  13262. this._unbindVertexArrayObject();
  13263. }
  13264. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13265. };
  13266. /**
  13267. * Bind an uniform buffer to the current webGL context
  13268. * @param buffer defines the buffer to bind
  13269. */
  13270. Engine.prototype.bindUniformBuffer = function (buffer) {
  13271. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13272. };
  13273. /**
  13274. * Bind a buffer to the current webGL context at a given location
  13275. * @param buffer defines the buffer to bind
  13276. * @param location defines the index where to bind the buffer
  13277. */
  13278. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13279. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13280. };
  13281. /**
  13282. * Bind a specific block at a given index in a specific shader program
  13283. * @param shaderProgram defines the shader program
  13284. * @param blockName defines the block name
  13285. * @param index defines the index where to bind the block
  13286. */
  13287. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13288. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13289. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13290. };
  13291. ;
  13292. Engine.prototype.bindIndexBuffer = function (buffer) {
  13293. if (!this._vaoRecordInProgress) {
  13294. this._unbindVertexArrayObject();
  13295. }
  13296. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13297. };
  13298. Engine.prototype.bindBuffer = function (buffer, target) {
  13299. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13300. this._gl.bindBuffer(target, buffer);
  13301. this._currentBoundBuffer[target] = buffer;
  13302. }
  13303. };
  13304. /**
  13305. * update the bound buffer with the given data
  13306. * @param data defines the data to update
  13307. */
  13308. Engine.prototype.updateArrayBuffer = function (data) {
  13309. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13310. };
  13311. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13312. var pointer = this._currentBufferPointers[indx];
  13313. var changed = false;
  13314. if (!pointer.active) {
  13315. changed = true;
  13316. pointer.active = true;
  13317. pointer.index = indx;
  13318. pointer.size = size;
  13319. pointer.type = type;
  13320. pointer.normalized = normalized;
  13321. pointer.stride = stride;
  13322. pointer.offset = offset;
  13323. pointer.buffer = buffer;
  13324. }
  13325. else {
  13326. if (pointer.buffer !== buffer) {
  13327. pointer.buffer = buffer;
  13328. changed = true;
  13329. }
  13330. if (pointer.size !== size) {
  13331. pointer.size = size;
  13332. changed = true;
  13333. }
  13334. if (pointer.type !== type) {
  13335. pointer.type = type;
  13336. changed = true;
  13337. }
  13338. if (pointer.normalized !== normalized) {
  13339. pointer.normalized = normalized;
  13340. changed = true;
  13341. }
  13342. if (pointer.stride !== stride) {
  13343. pointer.stride = stride;
  13344. changed = true;
  13345. }
  13346. if (pointer.offset !== offset) {
  13347. pointer.offset = offset;
  13348. changed = true;
  13349. }
  13350. }
  13351. if (changed || this._vaoRecordInProgress) {
  13352. this.bindArrayBuffer(buffer);
  13353. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13354. }
  13355. };
  13356. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13357. if (indexBuffer == null) {
  13358. return;
  13359. }
  13360. if (this._cachedIndexBuffer !== indexBuffer) {
  13361. this._cachedIndexBuffer = indexBuffer;
  13362. this.bindIndexBuffer(indexBuffer);
  13363. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13364. }
  13365. };
  13366. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13367. var attributes = effect.getAttributesNames();
  13368. if (!this._vaoRecordInProgress) {
  13369. this._unbindVertexArrayObject();
  13370. }
  13371. this.unbindAllAttributes();
  13372. for (var index = 0; index < attributes.length; index++) {
  13373. var order = effect.getAttributeLocation(index);
  13374. if (order >= 0) {
  13375. var vertexBuffer = vertexBuffers[attributes[index]];
  13376. if (!vertexBuffer) {
  13377. continue;
  13378. }
  13379. this._gl.enableVertexAttribArray(order);
  13380. if (!this._vaoRecordInProgress) {
  13381. this._vertexAttribArraysEnabled[order] = true;
  13382. }
  13383. var buffer = vertexBuffer.getBuffer();
  13384. if (buffer) {
  13385. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13386. if (vertexBuffer.getIsInstanced()) {
  13387. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13388. if (!this._vaoRecordInProgress) {
  13389. this._currentInstanceLocations.push(order);
  13390. this._currentInstanceBuffers.push(buffer);
  13391. }
  13392. }
  13393. }
  13394. }
  13395. }
  13396. };
  13397. /**
  13398. * Records a vertex array object
  13399. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13400. * @param vertexBuffers defines the list of vertex buffers to store
  13401. * @param indexBuffer defines the index buffer to store
  13402. * @param effect defines the effect to store
  13403. * @returns the new vertex array object
  13404. */
  13405. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13406. var vao = this._gl.createVertexArray();
  13407. this._vaoRecordInProgress = true;
  13408. this._gl.bindVertexArray(vao);
  13409. this._mustWipeVertexAttributes = true;
  13410. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13411. this.bindIndexBuffer(indexBuffer);
  13412. this._vaoRecordInProgress = false;
  13413. this._gl.bindVertexArray(null);
  13414. return vao;
  13415. };
  13416. /**
  13417. * Bind a specific vertex array object
  13418. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13419. * @param vertexArrayObject defines the vertex array object to bind
  13420. * @param indexBuffer defines the index buffer to bind
  13421. */
  13422. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13423. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13424. this._cachedVertexArrayObject = vertexArrayObject;
  13425. this._gl.bindVertexArray(vertexArrayObject);
  13426. this._cachedVertexBuffers = null;
  13427. this._cachedIndexBuffer = null;
  13428. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13429. this._mustWipeVertexAttributes = true;
  13430. }
  13431. };
  13432. /**
  13433. * Bind webGl buffers directly to the webGL context
  13434. * @param vertexBuffer defines the vertex buffer to bind
  13435. * @param indexBuffer defines the index buffer to bind
  13436. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13437. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13438. * @param effect defines the effect associated with the vertex buffer
  13439. */
  13440. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13441. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13442. this._cachedVertexBuffers = vertexBuffer;
  13443. this._cachedEffectForVertexBuffers = effect;
  13444. var attributesCount = effect.getAttributesCount();
  13445. this._unbindVertexArrayObject();
  13446. this.unbindAllAttributes();
  13447. var offset = 0;
  13448. for (var index = 0; index < attributesCount; index++) {
  13449. if (index < vertexDeclaration.length) {
  13450. var order = effect.getAttributeLocation(index);
  13451. if (order >= 0) {
  13452. this._gl.enableVertexAttribArray(order);
  13453. this._vertexAttribArraysEnabled[order] = true;
  13454. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13455. }
  13456. offset += vertexDeclaration[index] * 4;
  13457. }
  13458. }
  13459. }
  13460. this._bindIndexBufferWithCache(indexBuffer);
  13461. };
  13462. Engine.prototype._unbindVertexArrayObject = function () {
  13463. if (!this._cachedVertexArrayObject) {
  13464. return;
  13465. }
  13466. this._cachedVertexArrayObject = null;
  13467. this._gl.bindVertexArray(null);
  13468. };
  13469. /**
  13470. * Bind a list of vertex buffers to the webGL context
  13471. * @param vertexBuffers defines the list of vertex buffers to bind
  13472. * @param indexBuffer defines the index buffer to bind
  13473. * @param effect defines the effect associated with the vertex buffers
  13474. */
  13475. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13476. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13477. this._cachedVertexBuffers = vertexBuffers;
  13478. this._cachedEffectForVertexBuffers = effect;
  13479. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13480. }
  13481. this._bindIndexBufferWithCache(indexBuffer);
  13482. };
  13483. /**
  13484. * Unbind all instance attributes
  13485. */
  13486. Engine.prototype.unbindInstanceAttributes = function () {
  13487. var boundBuffer;
  13488. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13489. var instancesBuffer = this._currentInstanceBuffers[i];
  13490. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13491. boundBuffer = instancesBuffer;
  13492. this.bindArrayBuffer(instancesBuffer);
  13493. }
  13494. var offsetLocation = this._currentInstanceLocations[i];
  13495. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13496. }
  13497. this._currentInstanceBuffers.length = 0;
  13498. this._currentInstanceLocations.length = 0;
  13499. };
  13500. /**
  13501. * Release and free the memory of a vertex array object
  13502. * @param vao defines the vertex array object to delete
  13503. */
  13504. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13505. this._gl.deleteVertexArray(vao);
  13506. };
  13507. /** @hidden */
  13508. Engine.prototype._releaseBuffer = function (buffer) {
  13509. buffer.references--;
  13510. if (buffer.references === 0) {
  13511. this._gl.deleteBuffer(buffer);
  13512. return true;
  13513. }
  13514. return false;
  13515. };
  13516. /**
  13517. * Creates a webGL buffer to use with instanciation
  13518. * @param capacity defines the size of the buffer
  13519. * @returns the webGL buffer
  13520. */
  13521. Engine.prototype.createInstancesBuffer = function (capacity) {
  13522. var buffer = this._gl.createBuffer();
  13523. if (!buffer) {
  13524. throw new Error("Unable to create instance buffer");
  13525. }
  13526. buffer.capacity = capacity;
  13527. this.bindArrayBuffer(buffer);
  13528. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13529. return buffer;
  13530. };
  13531. /**
  13532. * Delete a webGL buffer used with instanciation
  13533. * @param buffer defines the webGL buffer to delete
  13534. */
  13535. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13536. this._gl.deleteBuffer(buffer);
  13537. };
  13538. /**
  13539. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13540. * @param instancesBuffer defines the webGL buffer to update and bind
  13541. * @param data defines the data to store in the buffer
  13542. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13543. */
  13544. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13545. this.bindArrayBuffer(instancesBuffer);
  13546. if (data) {
  13547. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13548. }
  13549. if (offsetLocations[0].index !== undefined) {
  13550. var stride = 0;
  13551. for (var i = 0; i < offsetLocations.length; i++) {
  13552. var ai = offsetLocations[i];
  13553. stride += ai.attributeSize * 4;
  13554. }
  13555. for (var i = 0; i < offsetLocations.length; i++) {
  13556. var ai = offsetLocations[i];
  13557. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13558. this._gl.enableVertexAttribArray(ai.index);
  13559. this._vertexAttribArraysEnabled[ai.index] = true;
  13560. }
  13561. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13562. this._gl.vertexAttribDivisor(ai.index, 1);
  13563. this._currentInstanceLocations.push(ai.index);
  13564. this._currentInstanceBuffers.push(instancesBuffer);
  13565. }
  13566. }
  13567. else {
  13568. for (var index = 0; index < 4; index++) {
  13569. var offsetLocation = offsetLocations[index];
  13570. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13571. this._gl.enableVertexAttribArray(offsetLocation);
  13572. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13573. }
  13574. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13575. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13576. this._currentInstanceLocations.push(offsetLocation);
  13577. this._currentInstanceBuffers.push(instancesBuffer);
  13578. }
  13579. }
  13580. };
  13581. /**
  13582. * Apply all cached states (depth, culling, stencil and alpha)
  13583. */
  13584. Engine.prototype.applyStates = function () {
  13585. this._depthCullingState.apply(this._gl);
  13586. this._stencilState.apply(this._gl);
  13587. this._alphaState.apply(this._gl);
  13588. };
  13589. /**
  13590. * Send a draw order
  13591. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13592. * @param indexStart defines the starting index
  13593. * @param indexCount defines the number of index to draw
  13594. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13595. */
  13596. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13597. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13598. };
  13599. /**
  13600. * Draw a list of points
  13601. * @param verticesStart defines the index of first vertex to draw
  13602. * @param verticesCount defines the count of vertices to draw
  13603. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13604. */
  13605. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13606. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13607. };
  13608. /**
  13609. * Draw a list of unindexed primitives
  13610. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13611. * @param verticesStart defines the index of first vertex to draw
  13612. * @param verticesCount defines the count of vertices to draw
  13613. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13614. */
  13615. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13616. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13617. };
  13618. /**
  13619. * Draw a list of indexed primitives
  13620. * @param fillMode defines the primitive to use
  13621. * @param indexStart defines the starting index
  13622. * @param indexCount defines the number of index to draw
  13623. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13624. */
  13625. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13626. // Apply states
  13627. this.applyStates();
  13628. this._drawCalls.addCount(1, false);
  13629. // Render
  13630. var drawMode = this._drawMode(fillMode);
  13631. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13632. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13633. if (instancesCount) {
  13634. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13635. }
  13636. else {
  13637. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13638. }
  13639. };
  13640. /**
  13641. * Draw a list of unindexed primitives
  13642. * @param fillMode defines the primitive to use
  13643. * @param verticesStart defines the index of first vertex to draw
  13644. * @param verticesCount defines the count of vertices to draw
  13645. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13646. */
  13647. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13648. // Apply states
  13649. this.applyStates();
  13650. this._drawCalls.addCount(1, false);
  13651. var drawMode = this._drawMode(fillMode);
  13652. if (instancesCount) {
  13653. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13654. }
  13655. else {
  13656. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13657. }
  13658. };
  13659. Engine.prototype._drawMode = function (fillMode) {
  13660. switch (fillMode) {
  13661. // Triangle views
  13662. case BABYLON.Material.TriangleFillMode:
  13663. return this._gl.TRIANGLES;
  13664. case BABYLON.Material.PointFillMode:
  13665. return this._gl.POINTS;
  13666. case BABYLON.Material.WireFrameFillMode:
  13667. return this._gl.LINES;
  13668. // Draw modes
  13669. case BABYLON.Material.PointListDrawMode:
  13670. return this._gl.POINTS;
  13671. case BABYLON.Material.LineListDrawMode:
  13672. return this._gl.LINES;
  13673. case BABYLON.Material.LineLoopDrawMode:
  13674. return this._gl.LINE_LOOP;
  13675. case BABYLON.Material.LineStripDrawMode:
  13676. return this._gl.LINE_STRIP;
  13677. case BABYLON.Material.TriangleStripDrawMode:
  13678. return this._gl.TRIANGLE_STRIP;
  13679. case BABYLON.Material.TriangleFanDrawMode:
  13680. return this._gl.TRIANGLE_FAN;
  13681. default:
  13682. return this._gl.TRIANGLES;
  13683. }
  13684. };
  13685. // Shaders
  13686. /** @hidden */
  13687. Engine.prototype._releaseEffect = function (effect) {
  13688. if (this._compiledEffects[effect._key]) {
  13689. delete this._compiledEffects[effect._key];
  13690. this._deleteProgram(effect.getProgram());
  13691. }
  13692. };
  13693. /** @hidden */
  13694. Engine.prototype._deleteProgram = function (program) {
  13695. if (program) {
  13696. program.__SPECTOR_rebuildProgram = null;
  13697. if (program.transformFeedback) {
  13698. this.deleteTransformFeedback(program.transformFeedback);
  13699. program.transformFeedback = null;
  13700. }
  13701. this._gl.deleteProgram(program);
  13702. }
  13703. };
  13704. /**
  13705. * Create a new effect (used to store vertex/fragment shaders)
  13706. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13707. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13708. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13709. * @param samplers defines an array of string used to represent textures
  13710. * @param defines defines the string containing the defines to use to compile the shaders
  13711. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13712. * @param onCompiled defines a function to call when the effect creation is successful
  13713. * @param onError defines a function to call when the effect creation has failed
  13714. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13715. * @returns the new Effect
  13716. */
  13717. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13718. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13719. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13720. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13721. if (this._compiledEffects[name]) {
  13722. var compiledEffect = this._compiledEffects[name];
  13723. if (onCompiled && compiledEffect.isReady()) {
  13724. onCompiled(compiledEffect);
  13725. }
  13726. return compiledEffect;
  13727. }
  13728. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13729. effect._key = name;
  13730. this._compiledEffects[name] = effect;
  13731. return effect;
  13732. };
  13733. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13734. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13735. };
  13736. ;
  13737. Engine.prototype._compileRawShader = function (source, type) {
  13738. var gl = this._gl;
  13739. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13740. gl.shaderSource(shader, source);
  13741. gl.compileShader(shader);
  13742. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13743. var log = gl.getShaderInfoLog(shader);
  13744. if (log) {
  13745. throw new Error(log);
  13746. }
  13747. }
  13748. if (!shader) {
  13749. throw new Error("Something went wrong while compile the shader.");
  13750. }
  13751. return shader;
  13752. };
  13753. ;
  13754. /**
  13755. * Directly creates a webGL program
  13756. * @param vertexCode defines the vertex shader code to use
  13757. * @param fragmentCode defines the fragment shader code to use
  13758. * @param context defines the webGL context to use (if not set, the current one will be used)
  13759. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13760. * @returns the new webGL program
  13761. */
  13762. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13763. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13764. context = context || this._gl;
  13765. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13766. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13767. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13768. };
  13769. /**
  13770. * Creates a webGL program
  13771. * @param vertexCode defines the vertex shader code to use
  13772. * @param fragmentCode defines the fragment shader code to use
  13773. * @param defines defines the string containing the defines to use to compile the shaders
  13774. * @param context defines the webGL context to use (if not set, the current one will be used)
  13775. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13776. * @returns the new webGL program
  13777. */
  13778. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13779. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13780. context = context || this._gl;
  13781. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13782. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13783. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13784. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13785. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13786. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13787. return program;
  13788. };
  13789. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13790. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13791. var shaderProgram = context.createProgram();
  13792. if (!shaderProgram) {
  13793. throw new Error("Unable to create program");
  13794. }
  13795. context.attachShader(shaderProgram, vertexShader);
  13796. context.attachShader(shaderProgram, fragmentShader);
  13797. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13798. var transformFeedback = this.createTransformFeedback();
  13799. this.bindTransformFeedback(transformFeedback);
  13800. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13801. shaderProgram.transformFeedback = transformFeedback;
  13802. }
  13803. context.linkProgram(shaderProgram);
  13804. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13805. this.bindTransformFeedback(null);
  13806. }
  13807. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13808. if (!linked) {
  13809. var error = context.getProgramInfoLog(shaderProgram);
  13810. if (error) {
  13811. throw new Error(error);
  13812. }
  13813. }
  13814. if (this.validateShaderPrograms) {
  13815. context.validateProgram(shaderProgram);
  13816. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13817. if (!validated) {
  13818. var error = context.getProgramInfoLog(shaderProgram);
  13819. if (error) {
  13820. throw new Error(error);
  13821. }
  13822. }
  13823. }
  13824. context.deleteShader(vertexShader);
  13825. context.deleteShader(fragmentShader);
  13826. return shaderProgram;
  13827. };
  13828. /**
  13829. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13830. * @param shaderProgram defines the webGL program to use
  13831. * @param uniformsNames defines the list of uniform names
  13832. * @returns an array of webGL uniform locations
  13833. */
  13834. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13835. var results = new Array();
  13836. for (var index = 0; index < uniformsNames.length; index++) {
  13837. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13838. }
  13839. return results;
  13840. };
  13841. /**
  13842. * Gets the lsit of active attributes for a given webGL program
  13843. * @param shaderProgram defines the webGL program to use
  13844. * @param attributesNames defines the list of attribute names to get
  13845. * @returns an array of indices indicating the offset of each attribute
  13846. */
  13847. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13848. var results = [];
  13849. for (var index = 0; index < attributesNames.length; index++) {
  13850. try {
  13851. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13852. }
  13853. catch (e) {
  13854. results.push(-1);
  13855. }
  13856. }
  13857. return results;
  13858. };
  13859. /**
  13860. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13861. * @param effect defines the effect to activate
  13862. */
  13863. Engine.prototype.enableEffect = function (effect) {
  13864. if (!effect || effect === this._currentEffect) {
  13865. return;
  13866. }
  13867. // Use program
  13868. this.bindSamplers(effect);
  13869. this._currentEffect = effect;
  13870. if (effect.onBind) {
  13871. effect.onBind(effect);
  13872. }
  13873. if (effect._onBindObservable) {
  13874. effect._onBindObservable.notifyObservers(effect);
  13875. }
  13876. };
  13877. /**
  13878. * Set the value of an uniform to an array of int32
  13879. * @param uniform defines the webGL uniform location where to store the value
  13880. * @param array defines the array of int32 to store
  13881. */
  13882. Engine.prototype.setIntArray = function (uniform, array) {
  13883. if (!uniform)
  13884. return;
  13885. this._gl.uniform1iv(uniform, array);
  13886. };
  13887. /**
  13888. * Set the value of an uniform to an array of int32 (stored as vec2)
  13889. * @param uniform defines the webGL uniform location where to store the value
  13890. * @param array defines the array of int32 to store
  13891. */
  13892. Engine.prototype.setIntArray2 = function (uniform, array) {
  13893. if (!uniform || array.length % 2 !== 0)
  13894. return;
  13895. this._gl.uniform2iv(uniform, array);
  13896. };
  13897. /**
  13898. * Set the value of an uniform to an array of int32 (stored as vec3)
  13899. * @param uniform defines the webGL uniform location where to store the value
  13900. * @param array defines the array of int32 to store
  13901. */
  13902. Engine.prototype.setIntArray3 = function (uniform, array) {
  13903. if (!uniform || array.length % 3 !== 0)
  13904. return;
  13905. this._gl.uniform3iv(uniform, array);
  13906. };
  13907. /**
  13908. * Set the value of an uniform to an array of int32 (stored as vec4)
  13909. * @param uniform defines the webGL uniform location where to store the value
  13910. * @param array defines the array of int32 to store
  13911. */
  13912. Engine.prototype.setIntArray4 = function (uniform, array) {
  13913. if (!uniform || array.length % 4 !== 0)
  13914. return;
  13915. this._gl.uniform4iv(uniform, array);
  13916. };
  13917. /**
  13918. * Set the value of an uniform to an array of float32
  13919. * @param uniform defines the webGL uniform location where to store the value
  13920. * @param array defines the array of float32 to store
  13921. */
  13922. Engine.prototype.setFloatArray = function (uniform, array) {
  13923. if (!uniform)
  13924. return;
  13925. this._gl.uniform1fv(uniform, array);
  13926. };
  13927. /**
  13928. * Set the value of an uniform to an array of float32 (stored as vec2)
  13929. * @param uniform defines the webGL uniform location where to store the value
  13930. * @param array defines the array of float32 to store
  13931. */
  13932. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13933. if (!uniform || array.length % 2 !== 0)
  13934. return;
  13935. this._gl.uniform2fv(uniform, array);
  13936. };
  13937. /**
  13938. * Set the value of an uniform to an array of float32 (stored as vec3)
  13939. * @param uniform defines the webGL uniform location where to store the value
  13940. * @param array defines the array of float32 to store
  13941. */
  13942. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13943. if (!uniform || array.length % 3 !== 0)
  13944. return;
  13945. this._gl.uniform3fv(uniform, array);
  13946. };
  13947. /**
  13948. * Set the value of an uniform to an array of float32 (stored as vec4)
  13949. * @param uniform defines the webGL uniform location where to store the value
  13950. * @param array defines the array of float32 to store
  13951. */
  13952. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13953. if (!uniform || array.length % 4 !== 0)
  13954. return;
  13955. this._gl.uniform4fv(uniform, array);
  13956. };
  13957. /**
  13958. * Set the value of an uniform to an array of number
  13959. * @param uniform defines the webGL uniform location where to store the value
  13960. * @param array defines the array of number to store
  13961. */
  13962. Engine.prototype.setArray = function (uniform, array) {
  13963. if (!uniform)
  13964. return;
  13965. this._gl.uniform1fv(uniform, array);
  13966. };
  13967. /**
  13968. * Set the value of an uniform to an array of number (stored as vec2)
  13969. * @param uniform defines the webGL uniform location where to store the value
  13970. * @param array defines the array of number to store
  13971. */
  13972. Engine.prototype.setArray2 = function (uniform, array) {
  13973. if (!uniform || array.length % 2 !== 0)
  13974. return;
  13975. this._gl.uniform2fv(uniform, array);
  13976. };
  13977. /**
  13978. * Set the value of an uniform to an array of number (stored as vec3)
  13979. * @param uniform defines the webGL uniform location where to store the value
  13980. * @param array defines the array of number to store
  13981. */
  13982. Engine.prototype.setArray3 = function (uniform, array) {
  13983. if (!uniform || array.length % 3 !== 0)
  13984. return;
  13985. this._gl.uniform3fv(uniform, array);
  13986. };
  13987. /**
  13988. * Set the value of an uniform to an array of number (stored as vec4)
  13989. * @param uniform defines the webGL uniform location where to store the value
  13990. * @param array defines the array of number to store
  13991. */
  13992. Engine.prototype.setArray4 = function (uniform, array) {
  13993. if (!uniform || array.length % 4 !== 0)
  13994. return;
  13995. this._gl.uniform4fv(uniform, array);
  13996. };
  13997. /**
  13998. * Set the value of an uniform to an array of float32 (stored as matrices)
  13999. * @param uniform defines the webGL uniform location where to store the value
  14000. * @param matrices defines the array of float32 to store
  14001. */
  14002. Engine.prototype.setMatrices = function (uniform, matrices) {
  14003. if (!uniform)
  14004. return;
  14005. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14006. };
  14007. /**
  14008. * Set the value of an uniform to a matrix
  14009. * @param uniform defines the webGL uniform location where to store the value
  14010. * @param matrix defines the matrix to store
  14011. */
  14012. Engine.prototype.setMatrix = function (uniform, matrix) {
  14013. if (!uniform)
  14014. return;
  14015. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14016. };
  14017. /**
  14018. * Set the value of an uniform to a matrix (3x3)
  14019. * @param uniform defines the webGL uniform location where to store the value
  14020. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14021. */
  14022. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14023. if (!uniform)
  14024. return;
  14025. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14026. };
  14027. /**
  14028. * Set the value of an uniform to a matrix (2x2)
  14029. * @param uniform defines the webGL uniform location where to store the value
  14030. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14031. */
  14032. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14033. if (!uniform)
  14034. return;
  14035. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14036. };
  14037. /**
  14038. * Set the value of an uniform to a number (int)
  14039. * @param uniform defines the webGL uniform location where to store the value
  14040. * @param value defines the int number to store
  14041. */
  14042. Engine.prototype.setInt = function (uniform, value) {
  14043. if (!uniform)
  14044. return;
  14045. this._gl.uniform1i(uniform, value);
  14046. };
  14047. /**
  14048. * Set the value of an uniform to a number (float)
  14049. * @param uniform defines the webGL uniform location where to store the value
  14050. * @param value defines the float number to store
  14051. */
  14052. Engine.prototype.setFloat = function (uniform, value) {
  14053. if (!uniform)
  14054. return;
  14055. this._gl.uniform1f(uniform, value);
  14056. };
  14057. /**
  14058. * Set the value of an uniform to a vec2
  14059. * @param uniform defines the webGL uniform location where to store the value
  14060. * @param x defines the 1st component of the value
  14061. * @param y defines the 2nd component of the value
  14062. */
  14063. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14064. if (!uniform)
  14065. return;
  14066. this._gl.uniform2f(uniform, x, y);
  14067. };
  14068. /**
  14069. * Set the value of an uniform to a vec3
  14070. * @param uniform defines the webGL uniform location where to store the value
  14071. * @param x defines the 1st component of the value
  14072. * @param y defines the 2nd component of the value
  14073. * @param z defines the 3rd component of the value
  14074. */
  14075. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14076. if (!uniform)
  14077. return;
  14078. this._gl.uniform3f(uniform, x, y, z);
  14079. };
  14080. /**
  14081. * Set the value of an uniform to a boolean
  14082. * @param uniform defines the webGL uniform location where to store the value
  14083. * @param bool defines the boolean to store
  14084. */
  14085. Engine.prototype.setBool = function (uniform, bool) {
  14086. if (!uniform)
  14087. return;
  14088. this._gl.uniform1i(uniform, bool);
  14089. };
  14090. /**
  14091. * Set the value of an uniform to a vec4
  14092. * @param uniform defines the webGL uniform location where to store the value
  14093. * @param x defines the 1st component of the value
  14094. * @param y defines the 2nd component of the value
  14095. * @param z defines the 3rd component of the value
  14096. * @param w defines the 4th component of the value
  14097. */
  14098. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14099. if (!uniform)
  14100. return;
  14101. this._gl.uniform4f(uniform, x, y, z, w);
  14102. };
  14103. /**
  14104. * Set the value of an uniform to a Color3
  14105. * @param uniform defines the webGL uniform location where to store the value
  14106. * @param color3 defines the color to store
  14107. */
  14108. Engine.prototype.setColor3 = function (uniform, color3) {
  14109. if (!uniform)
  14110. return;
  14111. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14112. };
  14113. /**
  14114. * Set the value of an uniform to a Color3 and an alpha value
  14115. * @param uniform defines the webGL uniform location where to store the value
  14116. * @param color3 defines the color to store
  14117. * @param alpha defines the alpha component to store
  14118. */
  14119. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14120. if (!uniform)
  14121. return;
  14122. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14123. };
  14124. /**
  14125. * Sets a Color4 on a uniform variable
  14126. * @param uniform defines the uniform location
  14127. * @param color4 defines the value to be set
  14128. */
  14129. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14130. if (!uniform)
  14131. return;
  14132. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14133. };
  14134. // States
  14135. /**
  14136. * Set various states to the webGL context
  14137. * @param culling defines backface culling state
  14138. * @param zOffset defines the value to apply to zOffset (0 by default)
  14139. * @param force defines if states must be applied even if cache is up to date
  14140. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14141. */
  14142. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14143. if (zOffset === void 0) { zOffset = 0; }
  14144. if (reverseSide === void 0) { reverseSide = false; }
  14145. // Culling
  14146. if (this._depthCullingState.cull !== culling || force) {
  14147. this._depthCullingState.cull = culling;
  14148. }
  14149. // Cull face
  14150. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14151. if (this._depthCullingState.cullFace !== cullFace || force) {
  14152. this._depthCullingState.cullFace = cullFace;
  14153. }
  14154. // Z offset
  14155. this.setZOffset(zOffset);
  14156. // Front face
  14157. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14158. if (this._depthCullingState.frontFace !== frontFace || force) {
  14159. this._depthCullingState.frontFace = frontFace;
  14160. }
  14161. };
  14162. /**
  14163. * Set the z offset to apply to current rendering
  14164. * @param value defines the offset to apply
  14165. */
  14166. Engine.prototype.setZOffset = function (value) {
  14167. this._depthCullingState.zOffset = value;
  14168. };
  14169. /**
  14170. * Gets the current value of the zOffset
  14171. * @returns the current zOffset state
  14172. */
  14173. Engine.prototype.getZOffset = function () {
  14174. return this._depthCullingState.zOffset;
  14175. };
  14176. /**
  14177. * Enable or disable depth buffering
  14178. * @param enable defines the state to set
  14179. */
  14180. Engine.prototype.setDepthBuffer = function (enable) {
  14181. this._depthCullingState.depthTest = enable;
  14182. };
  14183. /**
  14184. * Gets a boolean indicating if depth writing is enabled
  14185. * @returns the current depth writing state
  14186. */
  14187. Engine.prototype.getDepthWrite = function () {
  14188. return this._depthCullingState.depthMask;
  14189. };
  14190. /**
  14191. * Enable or disable depth writing
  14192. * @param enable defines the state to set
  14193. */
  14194. Engine.prototype.setDepthWrite = function (enable) {
  14195. this._depthCullingState.depthMask = enable;
  14196. };
  14197. /**
  14198. * Enable or disable color writing
  14199. * @param enable defines the state to set
  14200. */
  14201. Engine.prototype.setColorWrite = function (enable) {
  14202. this._gl.colorMask(enable, enable, enable, enable);
  14203. this._colorWrite = enable;
  14204. };
  14205. /**
  14206. * Gets a boolean indicating if color writing is enabled
  14207. * @returns the current color writing state
  14208. */
  14209. Engine.prototype.getColorWrite = function () {
  14210. return this._colorWrite;
  14211. };
  14212. /**
  14213. * Sets alpha constants used by some alpha blending modes
  14214. * @param r defines the red component
  14215. * @param g defines the green component
  14216. * @param b defines the blue component
  14217. * @param a defines the alpha component
  14218. */
  14219. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14220. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14221. };
  14222. /**
  14223. * Sets the current alpha mode
  14224. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14225. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14226. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14227. */
  14228. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14229. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14230. if (this._alphaMode === mode) {
  14231. return;
  14232. }
  14233. switch (mode) {
  14234. case Engine.ALPHA_DISABLE:
  14235. this._alphaState.alphaBlend = false;
  14236. break;
  14237. case Engine.ALPHA_PREMULTIPLIED:
  14238. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14239. this._alphaState.alphaBlend = true;
  14240. break;
  14241. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14242. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14243. this._alphaState.alphaBlend = true;
  14244. break;
  14245. case Engine.ALPHA_COMBINE:
  14246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14247. this._alphaState.alphaBlend = true;
  14248. break;
  14249. case Engine.ALPHA_ONEONE:
  14250. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14251. this._alphaState.alphaBlend = true;
  14252. break;
  14253. case Engine.ALPHA_ADD:
  14254. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14255. this._alphaState.alphaBlend = true;
  14256. break;
  14257. case Engine.ALPHA_SUBTRACT:
  14258. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14259. this._alphaState.alphaBlend = true;
  14260. break;
  14261. case Engine.ALPHA_MULTIPLY:
  14262. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14263. this._alphaState.alphaBlend = true;
  14264. break;
  14265. case Engine.ALPHA_MAXIMIZED:
  14266. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14267. this._alphaState.alphaBlend = true;
  14268. break;
  14269. case Engine.ALPHA_INTERPOLATE:
  14270. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14271. this._alphaState.alphaBlend = true;
  14272. break;
  14273. case Engine.ALPHA_SCREENMODE:
  14274. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14275. this._alphaState.alphaBlend = true;
  14276. break;
  14277. }
  14278. if (!noDepthWriteChange) {
  14279. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14280. }
  14281. this._alphaMode = mode;
  14282. };
  14283. /**
  14284. * Gets the current alpha mode
  14285. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14286. * @returns the current alpha mode
  14287. */
  14288. Engine.prototype.getAlphaMode = function () {
  14289. return this._alphaMode;
  14290. };
  14291. // Textures
  14292. /**
  14293. * Clears the list of texture accessible through engine.
  14294. * This can help preventing texture load conflict due to name collision.
  14295. */
  14296. Engine.prototype.clearInternalTexturesCache = function () {
  14297. this._internalTexturesCache = [];
  14298. };
  14299. /**
  14300. * Force the entire cache to be cleared
  14301. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14302. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14303. */
  14304. Engine.prototype.wipeCaches = function (bruteForce) {
  14305. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14306. return;
  14307. }
  14308. this._currentEffect = null;
  14309. this._viewportCached.x = 0;
  14310. this._viewportCached.y = 0;
  14311. this._viewportCached.z = 0;
  14312. this._viewportCached.w = 0;
  14313. if (bruteForce) {
  14314. this.resetTextureCache();
  14315. this._currentProgram = null;
  14316. this._stencilState.reset();
  14317. this._depthCullingState.reset();
  14318. this.setDepthFunctionToLessOrEqual();
  14319. this._alphaState.reset();
  14320. this._unpackFlipYCached = null;
  14321. }
  14322. this._resetVertexBufferBinding();
  14323. this._cachedIndexBuffer = null;
  14324. this._cachedEffectForVertexBuffers = null;
  14325. this._unbindVertexArrayObject();
  14326. this.bindIndexBuffer(null);
  14327. };
  14328. /**
  14329. * Set the compressed texture format to use, based on the formats you have, and the formats
  14330. * supported by the hardware / browser.
  14331. *
  14332. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14333. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14334. * to API arguments needed to compressed textures. This puts the burden on the container
  14335. * generator to house the arcane code for determining these for current & future formats.
  14336. *
  14337. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14338. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14339. *
  14340. * Note: The result of this call is not taken into account when a texture is base64.
  14341. *
  14342. * @param formatsAvailable defines the list of those format families you have created
  14343. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14344. *
  14345. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14346. * @returns The extension selected.
  14347. */
  14348. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14349. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14350. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14351. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14352. return this._textureFormatInUse = this._texturesSupported[i];
  14353. }
  14354. }
  14355. }
  14356. // actively set format to nothing, to allow this to be called more than once
  14357. // and possibly fail the 2nd time
  14358. this._textureFormatInUse = null;
  14359. return null;
  14360. };
  14361. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14362. var gl = this._gl;
  14363. var magFilter = gl.NEAREST;
  14364. var minFilter = gl.NEAREST;
  14365. switch (samplingMode) {
  14366. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14367. magFilter = gl.LINEAR;
  14368. if (generateMipMaps) {
  14369. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14370. }
  14371. else {
  14372. minFilter = gl.LINEAR;
  14373. }
  14374. break;
  14375. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14376. magFilter = gl.LINEAR;
  14377. if (generateMipMaps) {
  14378. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14379. }
  14380. else {
  14381. minFilter = gl.LINEAR;
  14382. }
  14383. break;
  14384. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14385. magFilter = gl.NEAREST;
  14386. if (generateMipMaps) {
  14387. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14388. }
  14389. else {
  14390. minFilter = gl.NEAREST;
  14391. }
  14392. break;
  14393. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14394. magFilter = gl.NEAREST;
  14395. if (generateMipMaps) {
  14396. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14397. }
  14398. else {
  14399. minFilter = gl.NEAREST;
  14400. }
  14401. break;
  14402. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14403. magFilter = gl.NEAREST;
  14404. if (generateMipMaps) {
  14405. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14406. }
  14407. else {
  14408. minFilter = gl.LINEAR;
  14409. }
  14410. break;
  14411. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14412. magFilter = gl.NEAREST;
  14413. if (generateMipMaps) {
  14414. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14415. }
  14416. else {
  14417. minFilter = gl.LINEAR;
  14418. }
  14419. break;
  14420. case Engine.TEXTURE_NEAREST_LINEAR:
  14421. magFilter = gl.NEAREST;
  14422. minFilter = gl.LINEAR;
  14423. break;
  14424. case Engine.TEXTURE_NEAREST_NEAREST:
  14425. magFilter = gl.NEAREST;
  14426. minFilter = gl.NEAREST;
  14427. break;
  14428. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14429. magFilter = gl.LINEAR;
  14430. if (generateMipMaps) {
  14431. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14432. }
  14433. else {
  14434. minFilter = gl.NEAREST;
  14435. }
  14436. break;
  14437. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14438. magFilter = gl.LINEAR;
  14439. if (generateMipMaps) {
  14440. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14441. }
  14442. else {
  14443. minFilter = gl.NEAREST;
  14444. }
  14445. break;
  14446. case Engine.TEXTURE_LINEAR_LINEAR:
  14447. magFilter = gl.LINEAR;
  14448. minFilter = gl.LINEAR;
  14449. break;
  14450. case Engine.TEXTURE_LINEAR_NEAREST:
  14451. magFilter = gl.LINEAR;
  14452. minFilter = gl.NEAREST;
  14453. break;
  14454. }
  14455. return {
  14456. min: minFilter,
  14457. mag: magFilter
  14458. };
  14459. };
  14460. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14461. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14462. var img;
  14463. var onload = function () {
  14464. loadedImages[index] = img;
  14465. loadedImages._internalCount++;
  14466. if (scene) {
  14467. scene._removePendingData(img);
  14468. }
  14469. if (loadedImages._internalCount === 6) {
  14470. onfinish(loadedImages);
  14471. }
  14472. };
  14473. var onerror = function (message, exception) {
  14474. if (scene) {
  14475. scene._removePendingData(img);
  14476. }
  14477. if (onErrorCallBack) {
  14478. onErrorCallBack(message, exception);
  14479. }
  14480. };
  14481. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14482. if (scene) {
  14483. scene._addPendingData(img);
  14484. }
  14485. };
  14486. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14487. if (onError === void 0) { onError = null; }
  14488. var loadedImages = [];
  14489. loadedImages._internalCount = 0;
  14490. for (var index = 0; index < 6; index++) {
  14491. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14492. }
  14493. };
  14494. ;
  14495. /** @hidden */
  14496. Engine.prototype._createTexture = function () {
  14497. var texture = this._gl.createTexture();
  14498. if (!texture) {
  14499. throw new Error("Unable to create texture");
  14500. }
  14501. return texture;
  14502. };
  14503. /**
  14504. * Usually called from BABYLON.Texture.ts.
  14505. * Passed information to create a WebGLTexture
  14506. * @param urlArg defines a value which contains one of the following:
  14507. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14508. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14509. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14510. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14511. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14512. * @param scene needed for loading to the correct scene
  14513. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14514. * @param onLoad optional callback to be called upon successful completion
  14515. * @param onError optional callback to be called upon failure
  14516. * @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
  14517. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14518. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14519. * @param forcedExtension defines the extension to use to pick the right loader
  14520. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14521. */
  14522. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14523. var _this = this;
  14524. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14525. if (onLoad === void 0) { onLoad = null; }
  14526. if (onError === void 0) { onError = null; }
  14527. if (buffer === void 0) { buffer = null; }
  14528. if (fallback === void 0) { fallback = null; }
  14529. if (format === void 0) { format = null; }
  14530. if (forcedExtension === void 0) { forcedExtension = null; }
  14531. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14532. var fromData = url.substr(0, 5) === "data:";
  14533. var fromBlob = url.substr(0, 5) === "blob:";
  14534. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14535. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14536. // establish the file extension, if possible
  14537. var lastDot = url.lastIndexOf('.');
  14538. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14539. var loader = null;
  14540. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14541. var availableLoader = _a[_i];
  14542. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14543. loader = availableLoader;
  14544. break;
  14545. }
  14546. }
  14547. if (loader) {
  14548. url = loader.transformUrl(url, this._textureFormatInUse);
  14549. }
  14550. if (scene) {
  14551. scene._addPendingData(texture);
  14552. }
  14553. texture.url = url;
  14554. texture.generateMipMaps = !noMipmap;
  14555. texture.samplingMode = samplingMode;
  14556. texture.invertY = invertY;
  14557. if (!this._doNotHandleContextLost) {
  14558. // Keep a link to the buffer only if we plan to handle context lost
  14559. texture._buffer = buffer;
  14560. }
  14561. var onLoadObserver = null;
  14562. if (onLoad && !fallback) {
  14563. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14564. }
  14565. if (!fallback)
  14566. this._internalTexturesCache.push(texture);
  14567. var onInternalError = function (message, exception) {
  14568. if (scene) {
  14569. scene._removePendingData(texture);
  14570. }
  14571. var customFallback = false;
  14572. if (loader) {
  14573. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14574. if (fallbackUrl) {
  14575. // Add Back
  14576. customFallback = true;
  14577. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14578. }
  14579. }
  14580. if (!customFallback) {
  14581. if (onLoadObserver) {
  14582. texture.onLoadedObservable.remove(onLoadObserver);
  14583. }
  14584. if (BABYLON.Tools.UseFallbackTexture) {
  14585. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14586. }
  14587. }
  14588. if (onError) {
  14589. onError(message || "Unknown error", exception);
  14590. }
  14591. };
  14592. // processing for non-image formats
  14593. if (loader) {
  14594. var callback = function (data) {
  14595. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14596. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14597. done();
  14598. return false;
  14599. }, samplingMode);
  14600. });
  14601. };
  14602. if (!buffer) {
  14603. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14604. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14605. });
  14606. }
  14607. else {
  14608. callback(buffer);
  14609. }
  14610. }
  14611. else {
  14612. var onload = function (img) {
  14613. if (fromBlob && !_this._doNotHandleContextLost) {
  14614. // We need to store the image if we need to rebuild the texture
  14615. // in case of a webgl context lost
  14616. texture._buffer = img;
  14617. }
  14618. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14619. var gl = _this._gl;
  14620. var isPot = (img.width === potWidth && img.height === potHeight);
  14621. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14622. if (isPot) {
  14623. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14624. return false;
  14625. }
  14626. var maxTextureSize = _this._caps.maxTextureSize;
  14627. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14628. _this._prepareWorkingCanvas();
  14629. if (!_this._workingCanvas || !_this._workingContext) {
  14630. return false;
  14631. }
  14632. _this._workingCanvas.width = potWidth;
  14633. _this._workingCanvas.height = potHeight;
  14634. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14635. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14636. texture.width = potWidth;
  14637. texture.height = potHeight;
  14638. return false;
  14639. }
  14640. else {
  14641. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14642. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14643. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14644. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14649. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14650. _this._releaseTexture(source_1);
  14651. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14652. continuationCallback();
  14653. });
  14654. }
  14655. return true;
  14656. }, samplingMode);
  14657. };
  14658. if (!fromData || isBase64) {
  14659. if (buffer instanceof HTMLImageElement) {
  14660. onload(buffer);
  14661. }
  14662. else {
  14663. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14664. }
  14665. }
  14666. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14667. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14668. }
  14669. else {
  14670. onload(buffer);
  14671. }
  14672. }
  14673. return texture;
  14674. };
  14675. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14676. var _this = this;
  14677. var rtt = this.createRenderTargetTexture({
  14678. width: destination.width,
  14679. height: destination.height,
  14680. }, {
  14681. generateMipMaps: false,
  14682. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14683. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14684. generateDepthBuffer: false,
  14685. generateStencilBuffer: false
  14686. });
  14687. if (!this._rescalePostProcess) {
  14688. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14689. }
  14690. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14691. _this._rescalePostProcess.onApply = function (effect) {
  14692. effect._bindTexture("textureSampler", source);
  14693. };
  14694. var hostingScene = scene;
  14695. if (!hostingScene) {
  14696. hostingScene = _this.scenes[_this.scenes.length - 1];
  14697. }
  14698. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14699. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14700. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14701. _this.unBindFramebuffer(rtt);
  14702. _this._releaseTexture(rtt);
  14703. if (onComplete) {
  14704. onComplete();
  14705. }
  14706. });
  14707. };
  14708. /**
  14709. * Update a raw texture
  14710. * @param texture defines the texture to update
  14711. * @param data defines the data to store in the texture
  14712. * @param format defines the format of the data
  14713. * @param invertY defines if data must be stored with Y axis inverted
  14714. * @param compression defines the compression used (null by default)
  14715. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14716. */
  14717. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14718. if (compression === void 0) { compression = null; }
  14719. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14720. if (!texture) {
  14721. return;
  14722. }
  14723. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14724. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14725. // babylon's internalFormat but gl's texImage2D format
  14726. var internalFormat = this._getInternalFormat(format);
  14727. var textureType = this._getWebGLTextureType(type);
  14728. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14729. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14730. if (!this._doNotHandleContextLost) {
  14731. texture._bufferView = data;
  14732. texture.format = format;
  14733. texture.type = type;
  14734. texture.invertY = invertY;
  14735. texture._compression = compression;
  14736. }
  14737. if (texture.width % 4 !== 0) {
  14738. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14739. }
  14740. if (compression && data) {
  14741. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14742. }
  14743. else {
  14744. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14745. }
  14746. if (texture.generateMipMaps) {
  14747. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14748. }
  14749. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14750. // this.resetTextureCache();
  14751. texture.isReady = true;
  14752. };
  14753. /**
  14754. * Creates a raw texture
  14755. * @param data defines the data to store in the texture
  14756. * @param width defines the width of the texture
  14757. * @param height defines the height of the texture
  14758. * @param format defines the format of the data
  14759. * @param generateMipMaps defines if the engine should generate the mip levels
  14760. * @param invertY defines if data must be stored with Y axis inverted
  14761. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14762. * @param compression defines the compression used (null by default)
  14763. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14764. * @returns the raw texture inside an InternalTexture
  14765. */
  14766. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14767. if (compression === void 0) { compression = null; }
  14768. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14769. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14770. texture.baseWidth = width;
  14771. texture.baseHeight = height;
  14772. texture.width = width;
  14773. texture.height = height;
  14774. texture.format = format;
  14775. texture.generateMipMaps = generateMipMaps;
  14776. texture.samplingMode = samplingMode;
  14777. texture.invertY = invertY;
  14778. texture._compression = compression;
  14779. texture.type = type;
  14780. if (!this._doNotHandleContextLost) {
  14781. texture._bufferView = data;
  14782. }
  14783. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14784. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14785. // Filters
  14786. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14787. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14788. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14789. if (generateMipMaps) {
  14790. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14791. }
  14792. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14793. this._internalTexturesCache.push(texture);
  14794. return texture;
  14795. };
  14796. /** @hidden */
  14797. Engine.prototype._unpackFlipY = function (value) {
  14798. if (this._unpackFlipYCached !== value) {
  14799. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14800. if (this.enableUnpackFlipYCached) {
  14801. this._unpackFlipYCached = value;
  14802. }
  14803. }
  14804. };
  14805. /** @hidden */
  14806. Engine.prototype._getUnpackAlignement = function () {
  14807. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14808. };
  14809. /**
  14810. * Creates a dynamic texture
  14811. * @param width defines the width of the texture
  14812. * @param height defines the height of the texture
  14813. * @param generateMipMaps defines if the engine should generate the mip levels
  14814. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14815. * @returns the dynamic texture inside an InternalTexture
  14816. */
  14817. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14818. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14819. texture.baseWidth = width;
  14820. texture.baseHeight = height;
  14821. if (generateMipMaps) {
  14822. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14823. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14824. }
  14825. // this.resetTextureCache();
  14826. texture.width = width;
  14827. texture.height = height;
  14828. texture.isReady = false;
  14829. texture.generateMipMaps = generateMipMaps;
  14830. texture.samplingMode = samplingMode;
  14831. this.updateTextureSamplingMode(samplingMode, texture);
  14832. this._internalTexturesCache.push(texture);
  14833. return texture;
  14834. };
  14835. /**
  14836. * Update the sampling mode of a given texture
  14837. * @param samplingMode defines the required sampling mode
  14838. * @param texture defines the texture to update
  14839. */
  14840. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14841. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14842. if (texture.isCube) {
  14843. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14844. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14845. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14846. }
  14847. else if (texture.is3D) {
  14848. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14849. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14850. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14851. }
  14852. else {
  14853. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14854. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14855. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14856. }
  14857. texture.samplingMode = samplingMode;
  14858. };
  14859. /**
  14860. * Update the content of a dynamic texture
  14861. * @param texture defines the texture to update
  14862. * @param canvas defines the canvas containing the source
  14863. * @param invertY defines if data must be stored with Y axis inverted
  14864. * @param premulAlpha defines if alpha is stored as premultiplied
  14865. * @param format defines the format of the data
  14866. */
  14867. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14868. if (premulAlpha === void 0) { premulAlpha = false; }
  14869. if (!texture) {
  14870. return;
  14871. }
  14872. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14873. this._unpackFlipY(invertY);
  14874. if (premulAlpha) {
  14875. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14876. }
  14877. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14878. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14879. if (texture.generateMipMaps) {
  14880. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14881. }
  14882. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14883. if (premulAlpha) {
  14884. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14885. }
  14886. texture.isReady = true;
  14887. };
  14888. /**
  14889. * Update a video texture
  14890. * @param texture defines the texture to update
  14891. * @param video defines the video element to use
  14892. * @param invertY defines if data must be stored with Y axis inverted
  14893. */
  14894. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14895. if (!texture || texture._isDisabled) {
  14896. return;
  14897. }
  14898. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14899. this._unpackFlipY(!invertY); // Video are upside down by default
  14900. try {
  14901. // Testing video texture support
  14902. if (this._videoTextureSupported === undefined) {
  14903. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14904. if (this._gl.getError() !== 0) {
  14905. this._videoTextureSupported = false;
  14906. }
  14907. else {
  14908. this._videoTextureSupported = true;
  14909. }
  14910. }
  14911. // Copy video through the current working canvas if video texture is not supported
  14912. if (!this._videoTextureSupported) {
  14913. if (!texture._workingCanvas) {
  14914. texture._workingCanvas = document.createElement("canvas");
  14915. var context = texture._workingCanvas.getContext("2d");
  14916. if (!context) {
  14917. throw new Error("Unable to get 2d context");
  14918. }
  14919. texture._workingContext = context;
  14920. texture._workingCanvas.width = texture.width;
  14921. texture._workingCanvas.height = texture.height;
  14922. }
  14923. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14924. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14925. }
  14926. else {
  14927. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14928. }
  14929. if (texture.generateMipMaps) {
  14930. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14931. }
  14932. if (!wasPreviouslyBound) {
  14933. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14934. }
  14935. // this.resetTextureCache();
  14936. texture.isReady = true;
  14937. }
  14938. catch (ex) {
  14939. // Something unexpected
  14940. // Let's disable the texture
  14941. texture._isDisabled = true;
  14942. }
  14943. };
  14944. /**
  14945. * Updates a depth texture Comparison Mode and Function.
  14946. * If the comparison Function is equal to 0, the mode will be set to none.
  14947. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14948. * @param texture The texture to set the comparison function for
  14949. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14950. */
  14951. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14952. if (this.webGLVersion === 1) {
  14953. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14954. return;
  14955. }
  14956. var gl = this._gl;
  14957. if (texture.isCube) {
  14958. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14959. if (comparisonFunction === 0) {
  14960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14962. }
  14963. else {
  14964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14966. }
  14967. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14968. }
  14969. else {
  14970. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14971. if (comparisonFunction === 0) {
  14972. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14973. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14974. }
  14975. else {
  14976. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14977. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14978. }
  14979. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14980. }
  14981. texture._comparisonFunction = comparisonFunction;
  14982. };
  14983. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14984. var width = size.width || size;
  14985. var height = size.height || size;
  14986. internalTexture.baseWidth = width;
  14987. internalTexture.baseHeight = height;
  14988. internalTexture.width = width;
  14989. internalTexture.height = height;
  14990. internalTexture.isReady = true;
  14991. internalTexture.samples = 1;
  14992. internalTexture.generateMipMaps = false;
  14993. internalTexture._generateDepthBuffer = true;
  14994. internalTexture._generateStencilBuffer = generateStencil;
  14995. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14996. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14997. internalTexture._comparisonFunction = comparisonFunction;
  14998. var gl = this._gl;
  14999. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15000. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15001. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15002. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15003. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15004. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15005. if (comparisonFunction === 0) {
  15006. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15007. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15008. }
  15009. else {
  15010. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15011. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15012. }
  15013. };
  15014. /**
  15015. * Creates a depth stencil texture.
  15016. * This is only available in WebGL 2 or with the depth texture extension available.
  15017. * @param size The size of face edge in the texture.
  15018. * @param options The options defining the texture.
  15019. * @returns The texture
  15020. */
  15021. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15022. if (options.isCube) {
  15023. var width = size.width || size;
  15024. return this._createDepthStencilCubeTexture(width, options);
  15025. }
  15026. else {
  15027. return this._createDepthStencilTexture(size, options);
  15028. }
  15029. };
  15030. /**
  15031. * Creates a depth stencil texture.
  15032. * This is only available in WebGL 2 or with the depth texture extension available.
  15033. * @param size The size of face edge in the texture.
  15034. * @param options The options defining the texture.
  15035. * @returns The texture
  15036. */
  15037. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15038. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15039. if (!this._caps.depthTextureExtension) {
  15040. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15041. return internalTexture;
  15042. }
  15043. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15044. var gl = this._gl;
  15045. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15046. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15047. if (this.webGLVersion > 1) {
  15048. if (internalOptions.generateStencil) {
  15049. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15050. }
  15051. else {
  15052. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15053. }
  15054. }
  15055. else {
  15056. if (internalOptions.generateStencil) {
  15057. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15058. }
  15059. else {
  15060. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15061. }
  15062. }
  15063. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15064. return internalTexture;
  15065. };
  15066. /**
  15067. * Creates a depth stencil cube texture.
  15068. * This is only available in WebGL 2.
  15069. * @param size The size of face edge in the cube texture.
  15070. * @param options The options defining the cube texture.
  15071. * @returns The cube texture
  15072. */
  15073. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15074. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15075. internalTexture.isCube = true;
  15076. if (this.webGLVersion === 1) {
  15077. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15078. return internalTexture;
  15079. }
  15080. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15081. var gl = this._gl;
  15082. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15083. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15084. // Create the depth/stencil buffer
  15085. for (var face = 0; face < 6; face++) {
  15086. if (internalOptions.generateStencil) {
  15087. 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);
  15088. }
  15089. else {
  15090. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15091. }
  15092. }
  15093. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15094. return internalTexture;
  15095. };
  15096. /**
  15097. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15098. * @param renderTarget The render target to set the frame buffer for
  15099. */
  15100. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15101. // Create the framebuffer
  15102. var internalTexture = renderTarget.getInternalTexture();
  15103. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15104. return;
  15105. }
  15106. var gl = this._gl;
  15107. var depthStencilTexture = renderTarget.depthStencilTexture;
  15108. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15109. if (depthStencilTexture.isCube) {
  15110. if (depthStencilTexture._generateStencilBuffer) {
  15111. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15112. }
  15113. else {
  15114. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15115. }
  15116. }
  15117. else {
  15118. if (depthStencilTexture._generateStencilBuffer) {
  15119. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15120. }
  15121. else {
  15122. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15123. }
  15124. }
  15125. this.bindUnboundFramebuffer(null);
  15126. };
  15127. /**
  15128. * Creates a new render target texture
  15129. * @param size defines the size of the texture
  15130. * @param options defines the options used to create the texture
  15131. * @returns a new render target texture stored in an InternalTexture
  15132. */
  15133. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15134. var fullOptions = new RenderTargetCreationOptions();
  15135. if (options !== undefined && typeof options === "object") {
  15136. fullOptions.generateMipMaps = options.generateMipMaps;
  15137. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15138. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15139. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15140. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15141. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15142. }
  15143. else {
  15144. fullOptions.generateMipMaps = options;
  15145. fullOptions.generateDepthBuffer = true;
  15146. fullOptions.generateStencilBuffer = false;
  15147. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15148. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15149. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15150. }
  15151. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15152. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15153. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15154. }
  15155. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15156. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15157. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15158. }
  15159. var gl = this._gl;
  15160. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15161. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15162. var width = size.width || size;
  15163. var height = size.height || size;
  15164. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15165. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15166. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15167. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15168. }
  15169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15170. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15173. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15174. // Create the framebuffer
  15175. var currentFrameBuffer = this._currentFramebuffer;
  15176. var framebuffer = gl.createFramebuffer();
  15177. this.bindUnboundFramebuffer(framebuffer);
  15178. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15179. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15180. if (fullOptions.generateMipMaps) {
  15181. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15182. }
  15183. // Unbind
  15184. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15185. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15186. this.bindUnboundFramebuffer(currentFrameBuffer);
  15187. texture._framebuffer = framebuffer;
  15188. texture.baseWidth = width;
  15189. texture.baseHeight = height;
  15190. texture.width = width;
  15191. texture.height = height;
  15192. texture.isReady = true;
  15193. texture.samples = 1;
  15194. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15195. texture.samplingMode = fullOptions.samplingMode;
  15196. texture.type = fullOptions.type;
  15197. texture.format = fullOptions.format;
  15198. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15199. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15200. // this.resetTextureCache();
  15201. this._internalTexturesCache.push(texture);
  15202. return texture;
  15203. };
  15204. /**
  15205. * Create a multi render target texture
  15206. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15207. * @param size defines the size of the texture
  15208. * @param options defines the creation options
  15209. * @returns the cube texture as an InternalTexture
  15210. */
  15211. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15212. var generateMipMaps = false;
  15213. var generateDepthBuffer = true;
  15214. var generateStencilBuffer = false;
  15215. var generateDepthTexture = false;
  15216. var textureCount = 1;
  15217. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15218. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15219. var types = new Array();
  15220. var samplingModes = new Array();
  15221. if (options !== undefined) {
  15222. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15223. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15224. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15225. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15226. textureCount = options.textureCount || 1;
  15227. if (options.types) {
  15228. types = options.types;
  15229. }
  15230. if (options.samplingModes) {
  15231. samplingModes = options.samplingModes;
  15232. }
  15233. }
  15234. var gl = this._gl;
  15235. // Create the framebuffer
  15236. var framebuffer = gl.createFramebuffer();
  15237. this.bindUnboundFramebuffer(framebuffer);
  15238. var width = size.width || size;
  15239. var height = size.height || size;
  15240. var textures = [];
  15241. var attachments = [];
  15242. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15243. for (var i = 0; i < textureCount; i++) {
  15244. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15245. var type = types[i] || defaultType;
  15246. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15247. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15248. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15249. }
  15250. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15251. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15252. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15253. }
  15254. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15255. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15256. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15257. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15258. }
  15259. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15260. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15261. textures.push(texture);
  15262. attachments.push(attachment);
  15263. gl.activeTexture(gl["TEXTURE" + i]);
  15264. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15269. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15270. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15271. if (generateMipMaps) {
  15272. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15273. }
  15274. // Unbind
  15275. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15276. texture._framebuffer = framebuffer;
  15277. texture._depthStencilBuffer = depthStencilBuffer;
  15278. texture.baseWidth = width;
  15279. texture.baseHeight = height;
  15280. texture.width = width;
  15281. texture.height = height;
  15282. texture.isReady = true;
  15283. texture.samples = 1;
  15284. texture.generateMipMaps = generateMipMaps;
  15285. texture.samplingMode = samplingMode;
  15286. texture.type = type;
  15287. texture._generateDepthBuffer = generateDepthBuffer;
  15288. texture._generateStencilBuffer = generateStencilBuffer;
  15289. texture._attachments = attachments;
  15290. this._internalTexturesCache.push(texture);
  15291. }
  15292. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15293. // Depth texture
  15294. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15295. gl.activeTexture(gl.TEXTURE0);
  15296. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15297. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15301. 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);
  15302. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15303. depthTexture._framebuffer = framebuffer;
  15304. depthTexture.baseWidth = width;
  15305. depthTexture.baseHeight = height;
  15306. depthTexture.width = width;
  15307. depthTexture.height = height;
  15308. depthTexture.isReady = true;
  15309. depthTexture.samples = 1;
  15310. depthTexture.generateMipMaps = generateMipMaps;
  15311. depthTexture.samplingMode = gl.NEAREST;
  15312. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15313. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15314. textures.push(depthTexture);
  15315. this._internalTexturesCache.push(depthTexture);
  15316. }
  15317. gl.drawBuffers(attachments);
  15318. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15319. this.bindUnboundFramebuffer(null);
  15320. this.resetTextureCache();
  15321. return textures;
  15322. };
  15323. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15324. if (samples === void 0) { samples = 1; }
  15325. var depthStencilBuffer = null;
  15326. var gl = this._gl;
  15327. // Create the depth/stencil buffer
  15328. if (generateStencilBuffer) {
  15329. depthStencilBuffer = gl.createRenderbuffer();
  15330. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15331. if (samples > 1) {
  15332. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15333. }
  15334. else {
  15335. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15336. }
  15337. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15338. }
  15339. else if (generateDepthBuffer) {
  15340. depthStencilBuffer = gl.createRenderbuffer();
  15341. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15342. if (samples > 1) {
  15343. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15344. }
  15345. else {
  15346. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15347. }
  15348. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15349. }
  15350. return depthStencilBuffer;
  15351. };
  15352. /**
  15353. * Updates the sample count of a render target texture
  15354. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15355. * @param texture defines the texture to update
  15356. * @param samples defines the sample count to set
  15357. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15358. */
  15359. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15360. if (this.webGLVersion < 2 || !texture) {
  15361. return 1;
  15362. }
  15363. if (texture.samples === samples) {
  15364. return samples;
  15365. }
  15366. var gl = this._gl;
  15367. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15368. // Dispose previous render buffers
  15369. if (texture._depthStencilBuffer) {
  15370. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15371. texture._depthStencilBuffer = null;
  15372. }
  15373. if (texture._MSAAFramebuffer) {
  15374. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15375. texture._MSAAFramebuffer = null;
  15376. }
  15377. if (texture._MSAARenderBuffer) {
  15378. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15379. texture._MSAARenderBuffer = null;
  15380. }
  15381. if (samples > 1) {
  15382. var framebuffer = gl.createFramebuffer();
  15383. if (!framebuffer) {
  15384. throw new Error("Unable to create multi sampled framebuffer");
  15385. }
  15386. texture._MSAAFramebuffer = framebuffer;
  15387. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15388. var colorRenderbuffer = gl.createRenderbuffer();
  15389. if (!colorRenderbuffer) {
  15390. throw new Error("Unable to create multi sampled framebuffer");
  15391. }
  15392. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15393. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15394. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15395. texture._MSAARenderBuffer = colorRenderbuffer;
  15396. }
  15397. else {
  15398. this.bindUnboundFramebuffer(texture._framebuffer);
  15399. }
  15400. texture.samples = samples;
  15401. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15402. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15403. this.bindUnboundFramebuffer(null);
  15404. return samples;
  15405. };
  15406. /**
  15407. * Update the sample count for a given multiple render target texture
  15408. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15409. * @param textures defines the textures to update
  15410. * @param samples defines the sample count to set
  15411. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15412. */
  15413. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15414. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15415. return 1;
  15416. }
  15417. if (textures[0].samples === samples) {
  15418. return samples;
  15419. }
  15420. var gl = this._gl;
  15421. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15422. // Dispose previous render buffers
  15423. if (textures[0]._depthStencilBuffer) {
  15424. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15425. textures[0]._depthStencilBuffer = null;
  15426. }
  15427. if (textures[0]._MSAAFramebuffer) {
  15428. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15429. textures[0]._MSAAFramebuffer = null;
  15430. }
  15431. for (var i = 0; i < textures.length; i++) {
  15432. if (textures[i]._MSAARenderBuffer) {
  15433. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15434. textures[i]._MSAARenderBuffer = null;
  15435. }
  15436. }
  15437. if (samples > 1) {
  15438. var framebuffer = gl.createFramebuffer();
  15439. if (!framebuffer) {
  15440. throw new Error("Unable to create multi sampled framebuffer");
  15441. }
  15442. this.bindUnboundFramebuffer(framebuffer);
  15443. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15444. var attachments = [];
  15445. for (var i = 0; i < textures.length; i++) {
  15446. var texture = textures[i];
  15447. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15448. var colorRenderbuffer = gl.createRenderbuffer();
  15449. if (!colorRenderbuffer) {
  15450. throw new Error("Unable to create multi sampled framebuffer");
  15451. }
  15452. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15453. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15454. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15455. texture._MSAAFramebuffer = framebuffer;
  15456. texture._MSAARenderBuffer = colorRenderbuffer;
  15457. texture.samples = samples;
  15458. texture._depthStencilBuffer = depthStencilBuffer;
  15459. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15460. attachments.push(attachment);
  15461. }
  15462. gl.drawBuffers(attachments);
  15463. }
  15464. else {
  15465. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15466. }
  15467. this.bindUnboundFramebuffer(null);
  15468. return samples;
  15469. };
  15470. /** @hidden */
  15471. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15472. if (faceIndex === void 0) { faceIndex = 0; }
  15473. if (lod === void 0) { lod = 0; }
  15474. var gl = this._gl;
  15475. var target = gl.TEXTURE_2D;
  15476. if (texture.isCube) {
  15477. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15478. }
  15479. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15480. };
  15481. /** @hidden */
  15482. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15483. if (faceIndex === void 0) { faceIndex = 0; }
  15484. if (lod === void 0) { lod = 0; }
  15485. var gl = this._gl;
  15486. var textureType = this._getWebGLTextureType(texture.type);
  15487. var format = this._getInternalFormat(texture.format);
  15488. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15489. this._unpackFlipY(texture.invertY);
  15490. var target = gl.TEXTURE_2D;
  15491. if (texture.isCube) {
  15492. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15493. }
  15494. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15495. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15496. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15497. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15498. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15499. };
  15500. /** @hidden */
  15501. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15502. if (faceIndex === void 0) { faceIndex = 0; }
  15503. if (lod === void 0) { lod = 0; }
  15504. var gl = this._gl;
  15505. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15506. this._bindTextureDirectly(bindTarget, texture, true);
  15507. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15508. this._bindTextureDirectly(bindTarget, null, true);
  15509. };
  15510. /** @hidden */
  15511. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15512. if (faceIndex === void 0) { faceIndex = 0; }
  15513. if (lod === void 0) { lod = 0; }
  15514. var gl = this._gl;
  15515. var textureType = this._getWebGLTextureType(texture.type);
  15516. var format = this._getInternalFormat(texture.format);
  15517. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15518. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15519. this._bindTextureDirectly(bindTarget, texture, true);
  15520. this._unpackFlipY(texture.invertY);
  15521. var target = gl.TEXTURE_2D;
  15522. if (texture.isCube) {
  15523. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15524. }
  15525. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15526. this._bindTextureDirectly(bindTarget, null, true);
  15527. };
  15528. /**
  15529. * Creates a new render target cube texture
  15530. * @param size defines the size of the texture
  15531. * @param options defines the options used to create the texture
  15532. * @returns a new render target cube texture stored in an InternalTexture
  15533. */
  15534. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15535. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15536. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15537. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15538. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15539. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15540. }
  15541. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15542. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15543. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15544. }
  15545. var gl = this._gl;
  15546. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15547. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15548. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15549. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15550. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15551. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15552. }
  15553. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15557. for (var face = 0; face < 6; face++) {
  15558. 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);
  15559. }
  15560. // Create the framebuffer
  15561. var framebuffer = gl.createFramebuffer();
  15562. this.bindUnboundFramebuffer(framebuffer);
  15563. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15564. // MipMaps
  15565. if (fullOptions.generateMipMaps) {
  15566. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15567. }
  15568. // Unbind
  15569. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15570. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15571. this.bindUnboundFramebuffer(null);
  15572. texture._framebuffer = framebuffer;
  15573. texture.width = size;
  15574. texture.height = size;
  15575. texture.isReady = true;
  15576. texture.isCube = true;
  15577. texture.samples = 1;
  15578. texture.generateMipMaps = fullOptions.generateMipMaps;
  15579. texture.samplingMode = fullOptions.samplingMode;
  15580. texture.type = fullOptions.type;
  15581. texture.format = fullOptions.format;
  15582. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15583. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15584. this._internalTexturesCache.push(texture);
  15585. return texture;
  15586. };
  15587. /**
  15588. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15589. * @param rootUrl defines the url where the file to load is located
  15590. * @param scene defines the current scene
  15591. * @param lodScale defines scale to apply to the mip map selection
  15592. * @param lodOffset defines offset to apply to the mip map selection
  15593. * @param onLoad defines an optional callback raised when the texture is loaded
  15594. * @param onError defines an optional callback raised if there is an issue to load the texture
  15595. * @param format defines the format of the data
  15596. * @param forcedExtension defines the extension to use to pick the right loader
  15597. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15598. * @returns the cube texture as an InternalTexture
  15599. */
  15600. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15601. var _this = this;
  15602. if (onLoad === void 0) { onLoad = null; }
  15603. if (onError === void 0) { onError = null; }
  15604. if (forcedExtension === void 0) { forcedExtension = null; }
  15605. if (createPolynomials === void 0) { createPolynomials = true; }
  15606. var callback = function (loadData) {
  15607. if (!loadData) {
  15608. if (onLoad) {
  15609. onLoad(null);
  15610. }
  15611. return;
  15612. }
  15613. var texture = loadData.texture;
  15614. if (!createPolynomials) {
  15615. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15616. }
  15617. else if (loadData.info.sphericalPolynomial) {
  15618. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15619. }
  15620. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15621. if (_this._caps.textureLOD) {
  15622. // Do not add extra process if texture lod is supported.
  15623. if (onLoad) {
  15624. onLoad(texture);
  15625. }
  15626. return;
  15627. }
  15628. var mipSlices = 3;
  15629. var gl = _this._gl;
  15630. var width = loadData.width;
  15631. if (!width) {
  15632. return;
  15633. }
  15634. var textures = [];
  15635. for (var i = 0; i < mipSlices; i++) {
  15636. //compute LOD from even spacing in smoothness (matching shader calculation)
  15637. var smoothness = i / (mipSlices - 1);
  15638. var roughness = 1 - smoothness;
  15639. var minLODIndex = lodOffset; // roughness = 0
  15640. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15641. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15642. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15643. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15644. glTextureFromLod.type = texture.type;
  15645. glTextureFromLod.format = texture.format;
  15646. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15647. glTextureFromLod.height = glTextureFromLod.width;
  15648. glTextureFromLod.isCube = true;
  15649. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15650. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15651. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15654. if (loadData.isDDS) {
  15655. var info = loadData.info;
  15656. var data = loadData.data;
  15657. _this._unpackFlipY(info.isCompressed);
  15658. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15659. }
  15660. else {
  15661. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15662. }
  15663. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15664. // Wrap in a base texture for easy binding.
  15665. var lodTexture = new BABYLON.BaseTexture(scene);
  15666. lodTexture.isCube = true;
  15667. lodTexture._texture = glTextureFromLod;
  15668. glTextureFromLod.isReady = true;
  15669. textures.push(lodTexture);
  15670. }
  15671. texture._lodTextureHigh = textures[2];
  15672. texture._lodTextureMid = textures[1];
  15673. texture._lodTextureLow = textures[0];
  15674. if (onLoad) {
  15675. onLoad(texture);
  15676. }
  15677. };
  15678. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15679. };
  15680. /**
  15681. * Creates a cube texture
  15682. * @param rootUrl defines the url where the files to load is located
  15683. * @param scene defines the current scene
  15684. * @param files defines the list of files to load (1 per face)
  15685. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15686. * @param onLoad defines an optional callback raised when the texture is loaded
  15687. * @param onError defines an optional callback raised if there is an issue to load the texture
  15688. * @param format defines the format of the data
  15689. * @param forcedExtension defines the extension to use to pick the right loader
  15690. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15691. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15692. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15693. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15694. * @returns the cube texture as an InternalTexture
  15695. */
  15696. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15697. var _this = this;
  15698. if (onLoad === void 0) { onLoad = null; }
  15699. if (onError === void 0) { onError = null; }
  15700. if (forcedExtension === void 0) { forcedExtension = null; }
  15701. if (createPolynomials === void 0) { createPolynomials = false; }
  15702. if (lodScale === void 0) { lodScale = 0; }
  15703. if (lodOffset === void 0) { lodOffset = 0; }
  15704. if (fallback === void 0) { fallback = null; }
  15705. var gl = this._gl;
  15706. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15707. texture.isCube = true;
  15708. texture.url = rootUrl;
  15709. texture.generateMipMaps = !noMipmap;
  15710. texture._lodGenerationScale = lodScale;
  15711. texture._lodGenerationOffset = lodOffset;
  15712. if (!this._doNotHandleContextLost) {
  15713. texture._extension = forcedExtension;
  15714. texture._files = files;
  15715. }
  15716. var lastDot = rootUrl.lastIndexOf('.');
  15717. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15718. var loader = null;
  15719. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15720. var availableLoader = _a[_i];
  15721. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15722. loader = availableLoader;
  15723. break;
  15724. }
  15725. }
  15726. var onInternalError = function (request, exception) {
  15727. if (loader) {
  15728. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15729. if (fallbackUrl) {
  15730. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15731. }
  15732. }
  15733. if (onError && request) {
  15734. onError(request.status + " " + request.statusText, exception);
  15735. }
  15736. };
  15737. if (loader) {
  15738. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15739. var onloaddata = function (data) {
  15740. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15741. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15742. };
  15743. if (files && files.length === 6) {
  15744. if (loader.supportCascades) {
  15745. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15746. }
  15747. else if (onError) {
  15748. onError("Textures type does not support cascades.");
  15749. }
  15750. }
  15751. else {
  15752. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15753. }
  15754. }
  15755. else {
  15756. if (!files) {
  15757. throw new Error("Cannot load cubemap because files were not defined");
  15758. }
  15759. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15760. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15761. var height = width;
  15762. _this._prepareWorkingCanvas();
  15763. if (!_this._workingCanvas || !_this._workingContext) {
  15764. return;
  15765. }
  15766. _this._workingCanvas.width = width;
  15767. _this._workingCanvas.height = height;
  15768. var faces = [
  15769. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15770. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15771. ];
  15772. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15773. _this._unpackFlipY(false);
  15774. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15775. for (var index = 0; index < faces.length; index++) {
  15776. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15777. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15778. }
  15779. if (!noMipmap) {
  15780. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15781. }
  15782. _this._setCubeMapTextureParams(!noMipmap);
  15783. texture.width = width;
  15784. texture.height = height;
  15785. texture.isReady = true;
  15786. if (format) {
  15787. texture.format = format;
  15788. }
  15789. texture.onLoadedObservable.notifyObservers(texture);
  15790. texture.onLoadedObservable.clear();
  15791. if (onLoad) {
  15792. onLoad();
  15793. }
  15794. }, files, onError);
  15795. }
  15796. this._internalTexturesCache.push(texture);
  15797. return texture;
  15798. };
  15799. /**
  15800. * @hidden
  15801. */
  15802. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15803. var gl = this._gl;
  15804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15808. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15809. // this.resetTextureCache();
  15810. };
  15811. /**
  15812. * Update a raw cube texture
  15813. * @param texture defines the texture to udpdate
  15814. * @param data defines the data to store
  15815. * @param format defines the data format
  15816. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15817. * @param invertY defines if data must be stored with Y axis inverted
  15818. * @param compression defines the compression used (null by default)
  15819. * @param level defines which level of the texture to update
  15820. */
  15821. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15822. if (compression === void 0) { compression = null; }
  15823. if (level === void 0) { level = 0; }
  15824. texture._bufferViewArray = data;
  15825. texture.format = format;
  15826. texture.type = type;
  15827. texture.invertY = invertY;
  15828. texture._compression = compression;
  15829. var gl = this._gl;
  15830. var textureType = this._getWebGLTextureType(type);
  15831. var internalFormat = this._getInternalFormat(format);
  15832. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15833. var needConversion = false;
  15834. if (internalFormat === gl.RGB) {
  15835. internalFormat = gl.RGBA;
  15836. needConversion = true;
  15837. }
  15838. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15839. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15840. if (texture.width % 4 !== 0) {
  15841. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15842. }
  15843. // Data are known to be in +X +Y +Z -X -Y -Z
  15844. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15845. var faceData = data[faceIndex];
  15846. if (compression) {
  15847. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15848. }
  15849. else {
  15850. if (needConversion) {
  15851. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15852. }
  15853. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15854. }
  15855. }
  15856. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15857. if (isPot && texture.generateMipMaps && level === 0) {
  15858. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15859. }
  15860. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15861. // this.resetTextureCache();
  15862. texture.isReady = true;
  15863. };
  15864. /**
  15865. * Creates a new raw cube texture
  15866. * @param data defines the array of data to use to create each face
  15867. * @param size defines the size of the textures
  15868. * @param format defines the format of the data
  15869. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15870. * @param generateMipMaps defines if the engine should generate the mip levels
  15871. * @param invertY defines if data must be stored with Y axis inverted
  15872. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15873. * @param compression defines the compression used (null by default)
  15874. * @returns the cube texture as an InternalTexture
  15875. */
  15876. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15877. if (compression === void 0) { compression = null; }
  15878. var gl = this._gl;
  15879. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15880. texture.isCube = true;
  15881. texture.format = format;
  15882. texture.type = type;
  15883. if (!this._doNotHandleContextLost) {
  15884. texture._bufferViewArray = data;
  15885. }
  15886. var textureType = this._getWebGLTextureType(type);
  15887. var internalFormat = this._getInternalFormat(format);
  15888. if (internalFormat === gl.RGB) {
  15889. internalFormat = gl.RGBA;
  15890. }
  15891. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15892. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15893. generateMipMaps = false;
  15894. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15895. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15896. }
  15897. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15898. generateMipMaps = false;
  15899. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15900. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15901. }
  15902. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15903. generateMipMaps = false;
  15904. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15905. }
  15906. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15907. generateMipMaps = false;
  15908. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15909. }
  15910. var width = size;
  15911. var height = width;
  15912. texture.width = width;
  15913. texture.height = height;
  15914. // Double check on POT to generate Mips.
  15915. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15916. if (!isPot) {
  15917. generateMipMaps = false;
  15918. }
  15919. // Upload data if needed. The texture won't be ready until then.
  15920. if (data) {
  15921. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15922. }
  15923. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15924. // Filters
  15925. if (data && generateMipMaps) {
  15926. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15927. }
  15928. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15933. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15934. texture.generateMipMaps = generateMipMaps;
  15935. return texture;
  15936. };
  15937. /**
  15938. * Creates a new raw cube texture from a specified url
  15939. * @param url defines the url where the data is located
  15940. * @param scene defines the current scene
  15941. * @param size defines the size of the textures
  15942. * @param format defines the format of the data
  15943. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15944. * @param noMipmap defines if the engine should avoid generating the mip levels
  15945. * @param callback defines a callback used to extract texture data from loaded data
  15946. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15947. * @param onLoad defines a callback called when texture is loaded
  15948. * @param onError defines a callback called if there is an error
  15949. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15950. * @param invertY defines if data must be stored with Y axis inverted
  15951. * @returns the cube texture as an InternalTexture
  15952. */
  15953. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15954. var _this = this;
  15955. if (onLoad === void 0) { onLoad = null; }
  15956. if (onError === void 0) { onError = null; }
  15957. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15958. if (invertY === void 0) { invertY = false; }
  15959. var gl = this._gl;
  15960. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15961. scene._addPendingData(texture);
  15962. texture.url = url;
  15963. this._internalTexturesCache.push(texture);
  15964. var onerror = function (request, exception) {
  15965. scene._removePendingData(texture);
  15966. if (onError && request) {
  15967. onError(request.status + " " + request.statusText, exception);
  15968. }
  15969. };
  15970. var internalCallback = function (data) {
  15971. var width = texture.width;
  15972. var faceDataArrays = callback(data);
  15973. if (!faceDataArrays) {
  15974. return;
  15975. }
  15976. if (mipmapGenerator) {
  15977. var textureType = _this._getWebGLTextureType(type);
  15978. var internalFormat = _this._getInternalFormat(format);
  15979. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15980. var needConversion = false;
  15981. if (internalFormat === gl.RGB) {
  15982. internalFormat = gl.RGBA;
  15983. needConversion = true;
  15984. }
  15985. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15986. _this._unpackFlipY(false);
  15987. var mipData = mipmapGenerator(faceDataArrays);
  15988. for (var level = 0; level < mipData.length; level++) {
  15989. var mipSize = width >> level;
  15990. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15991. var mipFaceData = mipData[level][faceIndex];
  15992. if (needConversion) {
  15993. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15994. }
  15995. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15996. }
  15997. }
  15998. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15999. }
  16000. else {
  16001. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16002. }
  16003. texture.isReady = true;
  16004. // this.resetTextureCache();
  16005. scene._removePendingData(texture);
  16006. if (onLoad) {
  16007. onLoad();
  16008. }
  16009. };
  16010. this._loadFile(url, function (data) {
  16011. internalCallback(data);
  16012. }, undefined, scene.database, true, onerror);
  16013. return texture;
  16014. };
  16015. ;
  16016. /**
  16017. * Update a raw 3D texture
  16018. * @param texture defines the texture to update
  16019. * @param data defines the data to store
  16020. * @param format defines the data format
  16021. * @param invertY defines if data must be stored with Y axis inverted
  16022. * @param compression defines the used compression (can be null)
  16023. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16024. */
  16025. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16026. if (compression === void 0) { compression = null; }
  16027. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16028. var internalType = this._getWebGLTextureType(textureType);
  16029. var internalFormat = this._getInternalFormat(format);
  16030. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16031. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16032. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16033. if (!this._doNotHandleContextLost) {
  16034. texture._bufferView = data;
  16035. texture.format = format;
  16036. texture.invertY = invertY;
  16037. texture._compression = compression;
  16038. }
  16039. if (texture.width % 4 !== 0) {
  16040. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16041. }
  16042. if (compression && data) {
  16043. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16044. }
  16045. else {
  16046. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16047. }
  16048. if (texture.generateMipMaps) {
  16049. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16050. }
  16051. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16052. // this.resetTextureCache();
  16053. texture.isReady = true;
  16054. };
  16055. /**
  16056. * Creates a new raw 3D texture
  16057. * @param data defines the data used to create the texture
  16058. * @param width defines the width of the texture
  16059. * @param height defines the height of the texture
  16060. * @param depth defines the depth of the texture
  16061. * @param format defines the format of the texture
  16062. * @param generateMipMaps defines if the engine must generate mip levels
  16063. * @param invertY defines if data must be stored with Y axis inverted
  16064. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16065. * @param compression defines the compressed used (can be null)
  16066. * @param textureType defines the compressed used (can be null)
  16067. * @returns a new raw 3D texture (stored in an InternalTexture)
  16068. */
  16069. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16070. if (compression === void 0) { compression = null; }
  16071. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16072. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16073. texture.baseWidth = width;
  16074. texture.baseHeight = height;
  16075. texture.baseDepth = depth;
  16076. texture.width = width;
  16077. texture.height = height;
  16078. texture.depth = depth;
  16079. texture.format = format;
  16080. texture.type = textureType;
  16081. texture.generateMipMaps = generateMipMaps;
  16082. texture.samplingMode = samplingMode;
  16083. texture.is3D = true;
  16084. if (!this._doNotHandleContextLost) {
  16085. texture._bufferView = data;
  16086. }
  16087. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16088. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16089. // Filters
  16090. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16091. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16092. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16093. if (generateMipMaps) {
  16094. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16095. }
  16096. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16097. this._internalTexturesCache.push(texture);
  16098. return texture;
  16099. };
  16100. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16101. var gl = this._gl;
  16102. if (!gl) {
  16103. return;
  16104. }
  16105. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16108. if (!noMipmap && !isCompressed) {
  16109. gl.generateMipmap(gl.TEXTURE_2D);
  16110. }
  16111. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16112. // this.resetTextureCache();
  16113. if (scene) {
  16114. scene._removePendingData(texture);
  16115. }
  16116. texture.onLoadedObservable.notifyObservers(texture);
  16117. texture.onLoadedObservable.clear();
  16118. };
  16119. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16120. var _this = this;
  16121. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16122. var maxTextureSize = this.getCaps().maxTextureSize;
  16123. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16124. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16125. var gl = this._gl;
  16126. if (!gl) {
  16127. return;
  16128. }
  16129. if (!texture._webGLTexture) {
  16130. // this.resetTextureCache();
  16131. if (scene) {
  16132. scene._removePendingData(texture);
  16133. }
  16134. return;
  16135. }
  16136. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16137. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16138. texture.baseWidth = width;
  16139. texture.baseHeight = height;
  16140. texture.width = potWidth;
  16141. texture.height = potHeight;
  16142. texture.isReady = true;
  16143. if (processFunction(potWidth, potHeight, function () {
  16144. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16145. })) {
  16146. // Returning as texture needs extra async steps
  16147. return;
  16148. }
  16149. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16150. };
  16151. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16152. // Create new RGBA data container.
  16153. var rgbaData;
  16154. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16155. rgbaData = new Float32Array(width * height * 4);
  16156. }
  16157. else {
  16158. rgbaData = new Uint32Array(width * height * 4);
  16159. }
  16160. // Convert each pixel.
  16161. for (var x = 0; x < width; x++) {
  16162. for (var y = 0; y < height; y++) {
  16163. var index = (y * width + x) * 3;
  16164. var newIndex = (y * width + x) * 4;
  16165. // Map Old Value to new value.
  16166. rgbaData[newIndex + 0] = rgbData[index + 0];
  16167. rgbaData[newIndex + 1] = rgbData[index + 1];
  16168. rgbaData[newIndex + 2] = rgbData[index + 2];
  16169. // Add fully opaque alpha channel.
  16170. rgbaData[newIndex + 3] = 1;
  16171. }
  16172. }
  16173. return rgbaData;
  16174. };
  16175. /** @hidden */
  16176. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16177. var gl = this._gl;
  16178. if (texture._framebuffer) {
  16179. gl.deleteFramebuffer(texture._framebuffer);
  16180. texture._framebuffer = null;
  16181. }
  16182. if (texture._depthStencilBuffer) {
  16183. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16184. texture._depthStencilBuffer = null;
  16185. }
  16186. if (texture._MSAAFramebuffer) {
  16187. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16188. texture._MSAAFramebuffer = null;
  16189. }
  16190. if (texture._MSAARenderBuffer) {
  16191. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16192. texture._MSAARenderBuffer = null;
  16193. }
  16194. };
  16195. /** @hidden */
  16196. Engine.prototype._releaseTexture = function (texture) {
  16197. var gl = this._gl;
  16198. this._releaseFramebufferObjects(texture);
  16199. gl.deleteTexture(texture._webGLTexture);
  16200. // Unbind channels
  16201. this.unbindAllTextures();
  16202. var index = this._internalTexturesCache.indexOf(texture);
  16203. if (index !== -1) {
  16204. this._internalTexturesCache.splice(index, 1);
  16205. }
  16206. // Integrated fixed lod samplers.
  16207. if (texture._lodTextureHigh) {
  16208. texture._lodTextureHigh.dispose();
  16209. }
  16210. if (texture._lodTextureMid) {
  16211. texture._lodTextureMid.dispose();
  16212. }
  16213. if (texture._lodTextureLow) {
  16214. texture._lodTextureLow.dispose();
  16215. }
  16216. // Set output texture of post process to null if the texture has been released/disposed
  16217. this.scenes.forEach(function (scene) {
  16218. scene.postProcesses.forEach(function (postProcess) {
  16219. if (postProcess._outputTexture == texture) {
  16220. postProcess._outputTexture = null;
  16221. }
  16222. });
  16223. scene.cameras.forEach(function (camera) {
  16224. camera._postProcesses.forEach(function (postProcess) {
  16225. if (postProcess) {
  16226. if (postProcess._outputTexture == texture) {
  16227. postProcess._outputTexture = null;
  16228. }
  16229. }
  16230. });
  16231. });
  16232. });
  16233. };
  16234. Engine.prototype.setProgram = function (program) {
  16235. if (this._currentProgram !== program) {
  16236. this._gl.useProgram(program);
  16237. this._currentProgram = program;
  16238. }
  16239. };
  16240. /**
  16241. * Binds an effect to the webGL context
  16242. * @param effect defines the effect to bind
  16243. */
  16244. Engine.prototype.bindSamplers = function (effect) {
  16245. this.setProgram(effect.getProgram());
  16246. var samplers = effect.getSamplers();
  16247. for (var index = 0; index < samplers.length; index++) {
  16248. var uniform = effect.getUniform(samplers[index]);
  16249. if (uniform) {
  16250. this._boundUniforms[index] = uniform;
  16251. }
  16252. }
  16253. this._currentEffect = null;
  16254. };
  16255. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16256. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16257. return;
  16258. }
  16259. // Remove
  16260. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16261. // Bind last to it
  16262. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16263. // Bind to dummy
  16264. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16265. };
  16266. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16267. if (!internalTexture) {
  16268. return -1;
  16269. }
  16270. internalTexture._initialSlot = channel;
  16271. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16272. if (channel !== internalTexture._designatedSlot) {
  16273. this._textureCollisions.addCount(1, false);
  16274. }
  16275. }
  16276. else {
  16277. if (channel !== internalTexture._designatedSlot) {
  16278. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16279. return internalTexture._designatedSlot;
  16280. }
  16281. else {
  16282. // No slot for this texture, let's pick a new one (if we find a free slot)
  16283. if (this._nextFreeTextureSlots.length) {
  16284. return this._nextFreeTextureSlots[0];
  16285. }
  16286. // We need to recycle the oldest bound texture, sorry.
  16287. this._textureCollisions.addCount(1, false);
  16288. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16289. }
  16290. }
  16291. }
  16292. return channel;
  16293. };
  16294. Engine.prototype._linkTrackers = function (previous, next) {
  16295. previous.next = next;
  16296. next.previous = previous;
  16297. };
  16298. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16299. var currentSlot = internalTexture._designatedSlot;
  16300. if (currentSlot === -1) {
  16301. return -1;
  16302. }
  16303. internalTexture._designatedSlot = -1;
  16304. if (this.disableTextureBindingOptimization) {
  16305. return -1;
  16306. }
  16307. // Remove from bound list
  16308. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16309. // Free the slot
  16310. this._boundTexturesCache[currentSlot] = null;
  16311. this._nextFreeTextureSlots.push(currentSlot);
  16312. return currentSlot;
  16313. };
  16314. Engine.prototype._activateCurrentTexture = function () {
  16315. if (this._currentTextureChannel !== this._activeChannel) {
  16316. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16317. this._currentTextureChannel = this._activeChannel;
  16318. }
  16319. };
  16320. /** @hidden */
  16321. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16322. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16323. if (force === void 0) { force = false; }
  16324. var wasPreviouslyBound = false;
  16325. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16326. this._activeChannel = texture._designatedSlot;
  16327. }
  16328. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16329. var isTextureForRendering = texture && texture._initialSlot > -1;
  16330. if (currentTextureBound !== texture || force) {
  16331. if (currentTextureBound) {
  16332. this._removeDesignatedSlot(currentTextureBound);
  16333. }
  16334. this._activateCurrentTexture();
  16335. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16336. this._boundTexturesCache[this._activeChannel] = texture;
  16337. if (texture) {
  16338. if (!this.disableTextureBindingOptimization) {
  16339. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16340. if (slotIndex > -1) {
  16341. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16342. }
  16343. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16344. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16345. }
  16346. texture._designatedSlot = this._activeChannel;
  16347. }
  16348. }
  16349. else if (forTextureDataUpdate) {
  16350. wasPreviouslyBound = true;
  16351. this._activateCurrentTexture();
  16352. }
  16353. if (isTextureForRendering && !forTextureDataUpdate) {
  16354. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16355. }
  16356. return wasPreviouslyBound;
  16357. };
  16358. /** @hidden */
  16359. Engine.prototype._bindTexture = function (channel, texture) {
  16360. if (channel < 0) {
  16361. return;
  16362. }
  16363. if (texture) {
  16364. channel = this._getCorrectTextureChannel(channel, texture);
  16365. }
  16366. this._activeChannel = channel;
  16367. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16368. };
  16369. /**
  16370. * Sets a texture to the webGL context from a postprocess
  16371. * @param channel defines the channel to use
  16372. * @param postProcess defines the source postprocess
  16373. */
  16374. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16375. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16376. };
  16377. /**
  16378. * Binds the output of the passed in post process to the texture channel specified
  16379. * @param channel The channel the texture should be bound to
  16380. * @param postProcess The post process which's output should be bound
  16381. */
  16382. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16383. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16384. };
  16385. /**
  16386. * Unbind all textures from the webGL context
  16387. */
  16388. Engine.prototype.unbindAllTextures = function () {
  16389. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16390. this._activeChannel = channel;
  16391. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16392. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16393. if (this.webGLVersion > 1) {
  16394. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16395. }
  16396. }
  16397. };
  16398. /**
  16399. * Sets a texture to the according uniform.
  16400. * @param channel The texture channel
  16401. * @param uniform The uniform to set
  16402. * @param texture The texture to apply
  16403. */
  16404. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16405. if (channel < 0) {
  16406. return;
  16407. }
  16408. if (uniform) {
  16409. this._boundUniforms[channel] = uniform;
  16410. }
  16411. this._setTexture(channel, texture);
  16412. };
  16413. /**
  16414. * Sets a depth stencil texture from a render target to the according uniform.
  16415. * @param channel The texture channel
  16416. * @param uniform The uniform to set
  16417. * @param texture The render target texture containing the depth stencil texture to apply
  16418. */
  16419. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16420. if (channel < 0) {
  16421. return;
  16422. }
  16423. if (uniform) {
  16424. this._boundUniforms[channel] = uniform;
  16425. }
  16426. if (!texture || !texture.depthStencilTexture) {
  16427. this._setTexture(channel, null);
  16428. }
  16429. else {
  16430. this._setTexture(channel, texture, false, true);
  16431. }
  16432. };
  16433. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16434. var uniform = this._boundUniforms[sourceSlot];
  16435. if (uniform._currentState === destination) {
  16436. return;
  16437. }
  16438. this._gl.uniform1i(uniform, destination);
  16439. uniform._currentState = destination;
  16440. };
  16441. Engine.prototype._getTextureWrapMode = function (mode) {
  16442. switch (mode) {
  16443. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16444. return this._gl.REPEAT;
  16445. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16446. return this._gl.CLAMP_TO_EDGE;
  16447. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16448. return this._gl.MIRRORED_REPEAT;
  16449. }
  16450. return this._gl.REPEAT;
  16451. };
  16452. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16453. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16454. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16455. // Not ready?
  16456. if (!texture) {
  16457. if (this._boundTexturesCache[channel] != null) {
  16458. this._activeChannel = channel;
  16459. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16460. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16461. if (this.webGLVersion > 1) {
  16462. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16463. }
  16464. }
  16465. return false;
  16466. }
  16467. // Video
  16468. if (texture.video) {
  16469. this._activeChannel = channel;
  16470. texture.update();
  16471. }
  16472. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16473. texture.delayLoad();
  16474. return false;
  16475. }
  16476. var internalTexture;
  16477. if (depthStencilTexture) {
  16478. internalTexture = texture.depthStencilTexture;
  16479. }
  16480. else if (texture.isReady()) {
  16481. internalTexture = texture.getInternalTexture();
  16482. }
  16483. else if (texture.isCube) {
  16484. internalTexture = this.emptyCubeTexture;
  16485. }
  16486. else if (texture.is3D) {
  16487. internalTexture = this.emptyTexture3D;
  16488. }
  16489. else {
  16490. internalTexture = this.emptyTexture;
  16491. }
  16492. if (!isPartOfTextureArray) {
  16493. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16494. }
  16495. var needToBind = true;
  16496. if (this._boundTexturesCache[channel] === internalTexture) {
  16497. this._moveBoundTextureOnTop(internalTexture);
  16498. if (!isPartOfTextureArray) {
  16499. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16500. }
  16501. needToBind = false;
  16502. }
  16503. this._activeChannel = channel;
  16504. if (internalTexture && internalTexture.is3D) {
  16505. if (needToBind) {
  16506. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16507. }
  16508. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16509. internalTexture._cachedWrapU = texture.wrapU;
  16510. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16511. }
  16512. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16513. internalTexture._cachedWrapV = texture.wrapV;
  16514. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16515. }
  16516. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16517. internalTexture._cachedWrapR = texture.wrapR;
  16518. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16519. }
  16520. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16521. }
  16522. else if (internalTexture && internalTexture.isCube) {
  16523. if (needToBind) {
  16524. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16525. }
  16526. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16527. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16528. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16529. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16530. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16531. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16532. }
  16533. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16534. }
  16535. else {
  16536. if (needToBind) {
  16537. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16538. }
  16539. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16540. internalTexture._cachedWrapU = texture.wrapU;
  16541. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16542. }
  16543. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16544. internalTexture._cachedWrapV = texture.wrapV;
  16545. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16546. }
  16547. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16548. }
  16549. return true;
  16550. };
  16551. /**
  16552. * Sets an array of texture to the webGL context
  16553. * @param channel defines the channel where the texture array must be set
  16554. * @param uniform defines the associated uniform location
  16555. * @param textures defines the array of textures to bind
  16556. */
  16557. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16558. if (channel < 0 || !uniform) {
  16559. return;
  16560. }
  16561. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16562. this._textureUnits = new Int32Array(textures.length);
  16563. }
  16564. for (var i = 0; i < textures.length; i++) {
  16565. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16566. }
  16567. this._gl.uniform1iv(uniform, this._textureUnits);
  16568. for (var index = 0; index < textures.length; index++) {
  16569. this._setTexture(this._textureUnits[index], textures[index], true);
  16570. }
  16571. };
  16572. /** @hidden */
  16573. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16574. var internalTexture = texture.getInternalTexture();
  16575. if (!internalTexture) {
  16576. return;
  16577. }
  16578. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16579. var value = texture.anisotropicFilteringLevel;
  16580. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16581. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16582. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16583. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16584. }
  16585. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16586. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16587. internalTexture._cachedAnisotropicFilteringLevel = value;
  16588. }
  16589. };
  16590. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16591. this._bindTextureDirectly(target, texture, true, true);
  16592. this._gl.texParameterf(target, parameter, value);
  16593. };
  16594. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16595. if (texture) {
  16596. this._bindTextureDirectly(target, texture, true, true);
  16597. }
  16598. this._gl.texParameteri(target, parameter, value);
  16599. };
  16600. /**
  16601. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16602. * @param x defines the x coordinate of the rectangle where pixels must be read
  16603. * @param y defines the y coordinate of the rectangle where pixels must be read
  16604. * @param width defines the width of the rectangle where pixels must be read
  16605. * @param height defines the height of the rectangle where pixels must be read
  16606. * @returns a Uint8Array containing RGBA colors
  16607. */
  16608. Engine.prototype.readPixels = function (x, y, width, height) {
  16609. var data = new Uint8Array(height * width * 4);
  16610. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16611. return data;
  16612. };
  16613. /**
  16614. * Add an externaly attached data from its key.
  16615. * This method call will fail and return false, if such key already exists.
  16616. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16617. * @param key the unique key that identifies the data
  16618. * @param data the data object to associate to the key for this Engine instance
  16619. * @return true if no such key were already present and the data was added successfully, false otherwise
  16620. */
  16621. Engine.prototype.addExternalData = function (key, data) {
  16622. if (!this._externalData) {
  16623. this._externalData = new BABYLON.StringDictionary();
  16624. }
  16625. return this._externalData.add(key, data);
  16626. };
  16627. /**
  16628. * Get an externaly attached data from its key
  16629. * @param key the unique key that identifies the data
  16630. * @return the associated data, if present (can be null), or undefined if not present
  16631. */
  16632. Engine.prototype.getExternalData = function (key) {
  16633. if (!this._externalData) {
  16634. this._externalData = new BABYLON.StringDictionary();
  16635. }
  16636. return this._externalData.get(key);
  16637. };
  16638. /**
  16639. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16640. * @param key the unique key that identifies the data
  16641. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16642. * @return the associated data, can be null if the factory returned null.
  16643. */
  16644. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16645. if (!this._externalData) {
  16646. this._externalData = new BABYLON.StringDictionary();
  16647. }
  16648. return this._externalData.getOrAddWithFactory(key, factory);
  16649. };
  16650. /**
  16651. * Remove an externaly attached data from the Engine instance
  16652. * @param key the unique key that identifies the data
  16653. * @return true if the data was successfully removed, false if it doesn't exist
  16654. */
  16655. Engine.prototype.removeExternalData = function (key) {
  16656. if (!this._externalData) {
  16657. this._externalData = new BABYLON.StringDictionary();
  16658. }
  16659. return this._externalData.remove(key);
  16660. };
  16661. /**
  16662. * Unbind all vertex attributes from the webGL context
  16663. */
  16664. Engine.prototype.unbindAllAttributes = function () {
  16665. if (this._mustWipeVertexAttributes) {
  16666. this._mustWipeVertexAttributes = false;
  16667. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16668. this._gl.disableVertexAttribArray(i);
  16669. this._vertexAttribArraysEnabled[i] = false;
  16670. this._currentBufferPointers[i].active = false;
  16671. }
  16672. return;
  16673. }
  16674. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16675. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16676. continue;
  16677. }
  16678. this._gl.disableVertexAttribArray(i);
  16679. this._vertexAttribArraysEnabled[i] = false;
  16680. this._currentBufferPointers[i].active = false;
  16681. }
  16682. };
  16683. /**
  16684. * 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
  16685. */
  16686. Engine.prototype.releaseEffects = function () {
  16687. for (var name in this._compiledEffects) {
  16688. this._deleteProgram(this._compiledEffects[name]._program);
  16689. }
  16690. this._compiledEffects = {};
  16691. };
  16692. /**
  16693. * Dispose and release all associated resources
  16694. */
  16695. Engine.prototype.dispose = function () {
  16696. this.hideLoadingUI();
  16697. this.stopRenderLoop();
  16698. // Release postProcesses
  16699. while (this.postProcesses.length) {
  16700. this.postProcesses[0].dispose();
  16701. }
  16702. // Empty texture
  16703. if (this._emptyTexture) {
  16704. this._releaseTexture(this._emptyTexture);
  16705. this._emptyTexture = null;
  16706. }
  16707. if (this._emptyCubeTexture) {
  16708. this._releaseTexture(this._emptyCubeTexture);
  16709. this._emptyCubeTexture = null;
  16710. }
  16711. // Rescale PP
  16712. if (this._rescalePostProcess) {
  16713. this._rescalePostProcess.dispose();
  16714. }
  16715. // Release scenes
  16716. while (this.scenes.length) {
  16717. this.scenes[0].dispose();
  16718. }
  16719. // Release audio engine
  16720. if (Engine.audioEngine) {
  16721. Engine.audioEngine.dispose();
  16722. }
  16723. // Release effects
  16724. this.releaseEffects();
  16725. // Unbind
  16726. this.unbindAllAttributes();
  16727. this._boundUniforms = [];
  16728. if (this._dummyFramebuffer) {
  16729. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16730. }
  16731. //WebVR
  16732. this.disableVR();
  16733. // Events
  16734. if (BABYLON.Tools.IsWindowObjectExist()) {
  16735. window.removeEventListener("blur", this._onBlur);
  16736. window.removeEventListener("focus", this._onFocus);
  16737. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16738. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16739. if (this._renderingCanvas) {
  16740. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16741. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16742. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16743. if (!this._doNotHandleContextLost) {
  16744. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16745. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16746. }
  16747. }
  16748. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16749. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16750. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16751. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16752. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16753. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16754. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16755. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16756. if (this._onVrDisplayConnect) {
  16757. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16758. if (this._onVrDisplayDisconnect) {
  16759. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16760. }
  16761. if (this._onVrDisplayPresentChange) {
  16762. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16763. }
  16764. this._onVrDisplayConnect = null;
  16765. this._onVrDisplayDisconnect = null;
  16766. }
  16767. }
  16768. // Remove from Instances
  16769. var index = Engine.Instances.indexOf(this);
  16770. if (index >= 0) {
  16771. Engine.Instances.splice(index, 1);
  16772. }
  16773. this._workingCanvas = null;
  16774. this._workingContext = null;
  16775. this._currentBufferPointers = [];
  16776. this._renderingCanvas = null;
  16777. this._currentProgram = null;
  16778. this._bindedRenderFunction = null;
  16779. this.onResizeObservable.clear();
  16780. this.onCanvasBlurObservable.clear();
  16781. this.onCanvasFocusObservable.clear();
  16782. this.onCanvasPointerOutObservable.clear();
  16783. this.onBeginFrameObservable.clear();
  16784. this.onEndFrameObservable.clear();
  16785. BABYLON.Effect.ResetCache();
  16786. // Abort active requests
  16787. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16788. var request = _a[_i];
  16789. request.abort();
  16790. }
  16791. };
  16792. // Loading screen
  16793. /**
  16794. * Display the loading screen
  16795. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16796. */
  16797. Engine.prototype.displayLoadingUI = function () {
  16798. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16799. return;
  16800. }
  16801. var loadingScreen = this.loadingScreen;
  16802. if (loadingScreen) {
  16803. loadingScreen.displayLoadingUI();
  16804. }
  16805. };
  16806. /**
  16807. * Hide the loading screen
  16808. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16809. */
  16810. Engine.prototype.hideLoadingUI = function () {
  16811. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16812. return;
  16813. }
  16814. var loadingScreen = this.loadingScreen;
  16815. if (loadingScreen) {
  16816. loadingScreen.hideLoadingUI();
  16817. }
  16818. };
  16819. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16820. /**
  16821. * Gets the current loading screen object
  16822. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16823. */
  16824. get: function () {
  16825. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16826. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16827. return this._loadingScreen;
  16828. },
  16829. /**
  16830. * Sets the current loading screen object
  16831. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16832. */
  16833. set: function (loadingScreen) {
  16834. this._loadingScreen = loadingScreen;
  16835. },
  16836. enumerable: true,
  16837. configurable: true
  16838. });
  16839. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16840. /**
  16841. * Sets the current loading screen text
  16842. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16843. */
  16844. set: function (text) {
  16845. this.loadingScreen.loadingUIText = text;
  16846. },
  16847. enumerable: true,
  16848. configurable: true
  16849. });
  16850. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16851. /**
  16852. * Sets the current loading screen background color
  16853. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16854. */
  16855. set: function (color) {
  16856. this.loadingScreen.loadingUIBackgroundColor = color;
  16857. },
  16858. enumerable: true,
  16859. configurable: true
  16860. });
  16861. /**
  16862. * Attach a new callback raised when context lost event is fired
  16863. * @param callback defines the callback to call
  16864. */
  16865. Engine.prototype.attachContextLostEvent = function (callback) {
  16866. if (this._renderingCanvas) {
  16867. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16868. }
  16869. };
  16870. /**
  16871. * Attach a new callback raised when context restored event is fired
  16872. * @param callback defines the callback to call
  16873. */
  16874. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16875. if (this._renderingCanvas) {
  16876. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16877. }
  16878. };
  16879. /**
  16880. * Gets the source code of the vertex shader associated with a specific webGL program
  16881. * @param program defines the program to use
  16882. * @returns a string containing the source code of the vertex shader associated with the program
  16883. */
  16884. Engine.prototype.getVertexShaderSource = function (program) {
  16885. var shaders = this._gl.getAttachedShaders(program);
  16886. if (!shaders) {
  16887. return null;
  16888. }
  16889. return this._gl.getShaderSource(shaders[0]);
  16890. };
  16891. /**
  16892. * Gets the source code of the fragment shader associated with a specific webGL program
  16893. * @param program defines the program to use
  16894. * @returns a string containing the source code of the fragment shader associated with the program
  16895. */
  16896. Engine.prototype.getFragmentShaderSource = function (program) {
  16897. var shaders = this._gl.getAttachedShaders(program);
  16898. if (!shaders) {
  16899. return null;
  16900. }
  16901. return this._gl.getShaderSource(shaders[1]);
  16902. };
  16903. /**
  16904. * Get the current error code of the webGL context
  16905. * @returns the error code
  16906. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16907. */
  16908. Engine.prototype.getError = function () {
  16909. return this._gl.getError();
  16910. };
  16911. // FPS
  16912. /**
  16913. * Gets the current framerate
  16914. * @returns a number representing the framerate
  16915. */
  16916. Engine.prototype.getFps = function () {
  16917. return this._fps;
  16918. };
  16919. /**
  16920. * Gets the time spent between current and previous frame
  16921. * @returns a number representing the delta time in ms
  16922. */
  16923. Engine.prototype.getDeltaTime = function () {
  16924. return this._deltaTime;
  16925. };
  16926. Engine.prototype._measureFps = function () {
  16927. this._performanceMonitor.sampleFrame();
  16928. this._fps = this._performanceMonitor.averageFPS;
  16929. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16930. };
  16931. /** @hidden */
  16932. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16933. if (faceIndex === void 0) { faceIndex = -1; }
  16934. if (level === void 0) { level = 0; }
  16935. var gl = this._gl;
  16936. if (!this._dummyFramebuffer) {
  16937. var dummy = gl.createFramebuffer();
  16938. if (!dummy) {
  16939. throw new Error("Unable to create dummy framebuffer");
  16940. }
  16941. this._dummyFramebuffer = dummy;
  16942. }
  16943. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16944. if (faceIndex > -1) {
  16945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16946. }
  16947. else {
  16948. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16949. }
  16950. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16951. var buffer;
  16952. switch (readType) {
  16953. case gl.UNSIGNED_BYTE:
  16954. buffer = new Uint8Array(4 * width * height);
  16955. readType = gl.UNSIGNED_BYTE;
  16956. break;
  16957. default:
  16958. buffer = new Float32Array(4 * width * height);
  16959. readType = gl.FLOAT;
  16960. break;
  16961. }
  16962. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16963. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16964. return buffer;
  16965. };
  16966. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16967. if (this._webGLVersion > 1) {
  16968. return this._caps.colorBufferFloat;
  16969. }
  16970. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16971. };
  16972. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16973. if (this._webGLVersion > 1) {
  16974. return this._caps.colorBufferFloat;
  16975. }
  16976. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16977. };
  16978. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16979. Engine.prototype._canRenderToFramebuffer = function (type) {
  16980. var gl = this._gl;
  16981. //clear existing errors
  16982. while (gl.getError() !== gl.NO_ERROR) { }
  16983. var successful = true;
  16984. var texture = gl.createTexture();
  16985. gl.bindTexture(gl.TEXTURE_2D, texture);
  16986. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16987. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16988. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16989. var fb = gl.createFramebuffer();
  16990. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16991. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16992. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16993. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16994. successful = successful && (gl.getError() === gl.NO_ERROR);
  16995. //try render by clearing frame buffer's color buffer
  16996. if (successful) {
  16997. gl.clear(gl.COLOR_BUFFER_BIT);
  16998. successful = successful && (gl.getError() === gl.NO_ERROR);
  16999. }
  17000. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17001. if (successful) {
  17002. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17003. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17004. var readFormat = gl.RGBA;
  17005. var readType = gl.UNSIGNED_BYTE;
  17006. var buffer = new Uint8Array(4);
  17007. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17008. successful = successful && (gl.getError() === gl.NO_ERROR);
  17009. }
  17010. //clean up
  17011. gl.deleteTexture(texture);
  17012. gl.deleteFramebuffer(fb);
  17013. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17014. //clear accumulated errors
  17015. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17016. return successful;
  17017. };
  17018. /** @hidden */
  17019. Engine.prototype._getWebGLTextureType = function (type) {
  17020. if (this._webGLVersion === 1) {
  17021. switch (type) {
  17022. case Engine.TEXTURETYPE_FLOAT:
  17023. return this._gl.FLOAT;
  17024. case Engine.TEXTURETYPE_HALF_FLOAT:
  17025. return this._gl.HALF_FLOAT_OES;
  17026. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17027. return this._gl.UNSIGNED_BYTE;
  17028. }
  17029. return this._gl.UNSIGNED_BYTE;
  17030. }
  17031. switch (type) {
  17032. case Engine.TEXTURETYPE_BYTE:
  17033. return this._gl.BYTE;
  17034. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17035. return this._gl.UNSIGNED_BYTE;
  17036. case Engine.TEXTURETYPE_SHORT:
  17037. return this._gl.SHORT;
  17038. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17039. return this._gl.UNSIGNED_SHORT;
  17040. case Engine.TEXTURETYPE_INT:
  17041. return this._gl.INT;
  17042. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17043. return this._gl.UNSIGNED_INT;
  17044. case Engine.TEXTURETYPE_FLOAT:
  17045. return this._gl.FLOAT;
  17046. case Engine.TEXTURETYPE_HALF_FLOAT:
  17047. return this._gl.HALF_FLOAT;
  17048. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17049. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17050. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17051. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17052. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17053. return this._gl.UNSIGNED_SHORT_5_6_5;
  17054. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17055. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17056. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17057. return this._gl.UNSIGNED_INT_24_8;
  17058. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17059. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17060. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17061. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17062. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17063. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17064. }
  17065. return this._gl.UNSIGNED_BYTE;
  17066. };
  17067. ;
  17068. Engine.prototype._getInternalFormat = function (format) {
  17069. var internalFormat = this._gl.RGBA;
  17070. switch (format) {
  17071. case Engine.TEXTUREFORMAT_ALPHA:
  17072. internalFormat = this._gl.ALPHA;
  17073. break;
  17074. case Engine.TEXTUREFORMAT_LUMINANCE:
  17075. internalFormat = this._gl.LUMINANCE;
  17076. break;
  17077. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17078. internalFormat = this._gl.LUMINANCE_ALPHA;
  17079. break;
  17080. case Engine.TEXTUREFORMAT_RED:
  17081. internalFormat = this._gl.RED;
  17082. break;
  17083. case Engine.TEXTUREFORMAT_RG:
  17084. internalFormat = this._gl.RG;
  17085. break;
  17086. case Engine.TEXTUREFORMAT_RGB:
  17087. internalFormat = this._gl.RGB;
  17088. break;
  17089. case Engine.TEXTUREFORMAT_RGBA:
  17090. internalFormat = this._gl.RGBA;
  17091. break;
  17092. }
  17093. if (this._webGLVersion > 1) {
  17094. switch (format) {
  17095. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17096. internalFormat = this._gl.RED_INTEGER;
  17097. break;
  17098. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17099. internalFormat = this._gl.RG_INTEGER;
  17100. break;
  17101. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17102. internalFormat = this._gl.RGB_INTEGER;
  17103. break;
  17104. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17105. internalFormat = this._gl.RGBA_INTEGER;
  17106. break;
  17107. }
  17108. }
  17109. return internalFormat;
  17110. };
  17111. /** @hidden */
  17112. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17113. if (this._webGLVersion === 1) {
  17114. if (format !== undefined) {
  17115. switch (format) {
  17116. case Engine.TEXTUREFORMAT_ALPHA:
  17117. return this._gl.ALPHA;
  17118. case Engine.TEXTUREFORMAT_LUMINANCE:
  17119. return this._gl.LUMINANCE;
  17120. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17121. return this._gl.LUMINANCE_ALPHA;
  17122. }
  17123. }
  17124. return this._gl.RGBA;
  17125. }
  17126. switch (type) {
  17127. case Engine.TEXTURETYPE_BYTE:
  17128. switch (format) {
  17129. case Engine.TEXTUREFORMAT_RED:
  17130. return this._gl.R8_SNORM;
  17131. case Engine.TEXTUREFORMAT_RG:
  17132. return this._gl.RG8_SNORM;
  17133. case Engine.TEXTUREFORMAT_RGB:
  17134. return this._gl.RGB8_SNORM;
  17135. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17136. return this._gl.R8I;
  17137. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17138. return this._gl.RG8I;
  17139. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17140. return this._gl.RGB8I;
  17141. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17142. return this._gl.RGBA8I;
  17143. default:
  17144. return this._gl.RGBA8_SNORM;
  17145. }
  17146. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17147. switch (format) {
  17148. case Engine.TEXTUREFORMAT_RED:
  17149. return this._gl.R8;
  17150. case Engine.TEXTUREFORMAT_RG:
  17151. return this._gl.RG8;
  17152. case Engine.TEXTUREFORMAT_RGB:
  17153. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17154. case Engine.TEXTUREFORMAT_RGBA:
  17155. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17156. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17157. return this._gl.R8UI;
  17158. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17159. return this._gl.RG8UI;
  17160. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17161. return this._gl.RGB8UI;
  17162. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17163. return this._gl.RGBA8UI;
  17164. default:
  17165. return this._gl.RGBA8;
  17166. }
  17167. case Engine.TEXTURETYPE_SHORT:
  17168. switch (format) {
  17169. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17170. return this._gl.R16I;
  17171. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17172. return this._gl.RG16I;
  17173. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17174. return this._gl.RGB16I;
  17175. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17176. return this._gl.RGBA16I;
  17177. default:
  17178. return this._gl.RGBA16I;
  17179. }
  17180. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17181. switch (format) {
  17182. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17183. return this._gl.R16UI;
  17184. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17185. return this._gl.RG16UI;
  17186. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17187. return this._gl.RGB16UI;
  17188. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17189. return this._gl.RGBA16UI;
  17190. default:
  17191. return this._gl.RGBA16UI;
  17192. }
  17193. case Engine.TEXTURETYPE_INT:
  17194. switch (format) {
  17195. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17196. return this._gl.R32I;
  17197. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17198. return this._gl.RG32I;
  17199. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17200. return this._gl.RGB32I;
  17201. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17202. return this._gl.RGBA32I;
  17203. default:
  17204. return this._gl.RGBA32I;
  17205. }
  17206. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17207. switch (format) {
  17208. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17209. return this._gl.R32UI;
  17210. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17211. return this._gl.RG32UI;
  17212. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17213. return this._gl.RGB32UI;
  17214. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17215. return this._gl.RGBA32UI;
  17216. default:
  17217. return this._gl.RGBA32UI;
  17218. }
  17219. case Engine.TEXTURETYPE_FLOAT:
  17220. switch (format) {
  17221. case Engine.TEXTUREFORMAT_RED:
  17222. return this._gl.R32F; // By default. Other possibility is R16F.
  17223. case Engine.TEXTUREFORMAT_RG:
  17224. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17225. case Engine.TEXTUREFORMAT_RGB:
  17226. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17227. case Engine.TEXTUREFORMAT_RGBA:
  17228. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17229. default:
  17230. return this._gl.RGBA32F;
  17231. }
  17232. case Engine.TEXTURETYPE_HALF_FLOAT:
  17233. switch (format) {
  17234. case Engine.TEXTUREFORMAT_RED:
  17235. return this._gl.R16F;
  17236. case Engine.TEXTUREFORMAT_RG:
  17237. return this._gl.RG16F;
  17238. case Engine.TEXTUREFORMAT_RGB:
  17239. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17240. case Engine.TEXTUREFORMAT_RGBA:
  17241. return this._gl.RGBA16F;
  17242. default:
  17243. return this._gl.RGBA16F;
  17244. }
  17245. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17246. return this._gl.RGB565;
  17247. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17248. return this._gl.R11F_G11F_B10F;
  17249. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17250. return this._gl.RGB9_E5;
  17251. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17252. return this._gl.RGBA4;
  17253. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17254. return this._gl.RGB5_A1;
  17255. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17256. switch (format) {
  17257. case Engine.TEXTUREFORMAT_RGBA:
  17258. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17259. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17260. return this._gl.RGB10_A2UI;
  17261. default:
  17262. return this._gl.RGB10_A2;
  17263. }
  17264. }
  17265. return this._gl.RGBA8;
  17266. };
  17267. ;
  17268. /** @hidden */
  17269. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17270. if (type === Engine.TEXTURETYPE_FLOAT) {
  17271. return this._gl.RGBA32F;
  17272. }
  17273. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17274. return this._gl.RGBA16F;
  17275. }
  17276. return this._gl.RGBA8;
  17277. };
  17278. ;
  17279. /** @hidden */
  17280. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17281. var _this = this;
  17282. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17283. this._activeRequests.push(request);
  17284. request.onCompleteObservable.add(function (request) {
  17285. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17286. });
  17287. return request;
  17288. };
  17289. /** @hidden */
  17290. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17291. var _this = this;
  17292. return new Promise(function (resolve, reject) {
  17293. _this._loadFile(url, function (data) {
  17294. resolve(data);
  17295. }, undefined, database, useArrayBuffer, function (request, exception) {
  17296. reject(exception);
  17297. });
  17298. });
  17299. };
  17300. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17301. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17302. var onload = function (data) {
  17303. loadedFiles[index] = data;
  17304. loadedFiles._internalCount++;
  17305. if (loadedFiles._internalCount === 6) {
  17306. onfinish(loadedFiles);
  17307. }
  17308. };
  17309. var onerror = function (request, exception) {
  17310. if (onErrorCallBack && request) {
  17311. onErrorCallBack(request.status + " " + request.statusText, exception);
  17312. }
  17313. };
  17314. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17315. };
  17316. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17317. if (onError === void 0) { onError = null; }
  17318. var loadedFiles = [];
  17319. loadedFiles._internalCount = 0;
  17320. for (var index = 0; index < 6; index++) {
  17321. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17322. }
  17323. };
  17324. // Statics
  17325. /**
  17326. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17327. * @returns true if the engine can be created
  17328. * @ignorenaming
  17329. */
  17330. Engine.isSupported = function () {
  17331. try {
  17332. var tempcanvas = document.createElement("canvas");
  17333. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17334. return gl != null && !!window.WebGLRenderingContext;
  17335. }
  17336. catch (e) {
  17337. return false;
  17338. }
  17339. };
  17340. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17341. Engine.ExceptionList = [
  17342. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17343. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17344. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17345. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17346. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17347. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17348. ];
  17349. /** Gets the list of created engines */
  17350. Engine.Instances = new Array();
  17351. /**
  17352. * Hidden
  17353. */
  17354. Engine._TextureLoaders = [];
  17355. // Const statics
  17356. /** Defines that alpha blending is disabled */
  17357. Engine.ALPHA_DISABLE = 0;
  17358. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17359. Engine.ALPHA_ADD = 1;
  17360. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17361. Engine.ALPHA_COMBINE = 2;
  17362. /** Defines that alpha blending to DEST - SRC * DEST */
  17363. Engine.ALPHA_SUBTRACT = 3;
  17364. /** Defines that alpha blending to SRC * DEST */
  17365. Engine.ALPHA_MULTIPLY = 4;
  17366. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17367. Engine.ALPHA_MAXIMIZED = 5;
  17368. /** Defines that alpha blending to SRC + DEST */
  17369. Engine.ALPHA_ONEONE = 6;
  17370. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17371. Engine.ALPHA_PREMULTIPLIED = 7;
  17372. /**
  17373. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17374. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17375. */
  17376. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17377. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17378. Engine.ALPHA_INTERPOLATE = 9;
  17379. /**
  17380. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17381. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17382. */
  17383. Engine.ALPHA_SCREENMODE = 10;
  17384. /** Defines that the ressource is not delayed*/
  17385. Engine.DELAYLOADSTATE_NONE = 0;
  17386. /** Defines that the ressource was successfully delay loaded */
  17387. Engine.DELAYLOADSTATE_LOADED = 1;
  17388. /** Defines that the ressource is currently delay loading */
  17389. Engine.DELAYLOADSTATE_LOADING = 2;
  17390. /** Defines that the ressource is delayed and has not started loading */
  17391. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17392. // Depht or Stencil test Constants.
  17393. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17394. Engine.NEVER = 0x0200;
  17395. /** 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 */
  17396. Engine.ALWAYS = 0x0207;
  17397. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17398. Engine.LESS = 0x0201;
  17399. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17400. Engine.EQUAL = 0x0202;
  17401. /** 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 */
  17402. Engine.LEQUAL = 0x0203;
  17403. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17404. Engine.GREATER = 0x0204;
  17405. /** 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 */
  17406. Engine.GEQUAL = 0x0206;
  17407. /** 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 */
  17408. Engine.NOTEQUAL = 0x0205;
  17409. // Stencil Actions Constants.
  17410. /** Passed to stencilOperation to specify that stencil value must be kept */
  17411. Engine.KEEP = 0x1E00;
  17412. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17413. Engine.REPLACE = 0x1E01;
  17414. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17415. Engine.INCR = 0x1E02;
  17416. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17417. Engine.DECR = 0x1E03;
  17418. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17419. Engine.INVERT = 0x150A;
  17420. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17421. Engine.INCR_WRAP = 0x8507;
  17422. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17423. Engine.DECR_WRAP = 0x8508;
  17424. /** Texture is not repeating outside of 0..1 UVs */
  17425. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17426. /** Texture is repeating outside of 0..1 UVs */
  17427. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17428. /** Texture is repeating and mirrored */
  17429. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17430. /** ALPHA */
  17431. Engine.TEXTUREFORMAT_ALPHA = 0;
  17432. /** LUMINANCE */
  17433. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17434. /** LUMINANCE_ALPHA */
  17435. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17436. /** RGB */
  17437. Engine.TEXTUREFORMAT_RGB = 4;
  17438. /** RGBA */
  17439. Engine.TEXTUREFORMAT_RGBA = 5;
  17440. /** RED */
  17441. Engine.TEXTUREFORMAT_RED = 6;
  17442. /** RED (2nd reference) */
  17443. Engine.TEXTUREFORMAT_R = 6;
  17444. /** RG */
  17445. Engine.TEXTUREFORMAT_RG = 7;
  17446. /** RED_INTEGER */
  17447. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17448. /** RED_INTEGER (2nd reference) */
  17449. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17450. /** RG_INTEGER */
  17451. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17452. /** RGB_INTEGER */
  17453. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17454. /** RGBA_INTEGER */
  17455. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17456. /** UNSIGNED_BYTE */
  17457. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17458. /** UNSIGNED_BYTE (2nd reference) */
  17459. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17460. /** FLOAT */
  17461. Engine.TEXTURETYPE_FLOAT = 1;
  17462. /** HALF_FLOAT */
  17463. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17464. /** BYTE */
  17465. Engine.TEXTURETYPE_BYTE = 3;
  17466. /** SHORT */
  17467. Engine.TEXTURETYPE_SHORT = 4;
  17468. /** UNSIGNED_SHORT */
  17469. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17470. /** INT */
  17471. Engine.TEXTURETYPE_INT = 6;
  17472. /** UNSIGNED_INT */
  17473. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17474. /** UNSIGNED_SHORT_4_4_4_4 */
  17475. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17476. /** UNSIGNED_SHORT_5_5_5_1 */
  17477. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17478. /** UNSIGNED_SHORT_5_6_5 */
  17479. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17480. /** UNSIGNED_INT_2_10_10_10_REV */
  17481. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17482. /** UNSIGNED_INT_24_8 */
  17483. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17484. /** UNSIGNED_INT_10F_11F_11F_REV */
  17485. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17486. /** UNSIGNED_INT_5_9_9_9_REV */
  17487. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17488. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17489. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17490. /** nearest is mag = nearest and min = nearest and mip = linear */
  17491. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17492. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17493. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17494. /** Trilinear is mag = linear and min = linear and mip = linear */
  17495. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17496. /** nearest is mag = nearest and min = nearest and mip = linear */
  17497. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17498. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17499. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17500. /** Trilinear is mag = linear and min = linear and mip = linear */
  17501. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17502. /** mag = nearest and min = nearest and mip = nearest */
  17503. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17504. /** mag = nearest and min = linear and mip = nearest */
  17505. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17506. /** mag = nearest and min = linear and mip = linear */
  17507. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17508. /** mag = nearest and min = linear and mip = none */
  17509. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17510. /** mag = nearest and min = nearest and mip = none */
  17511. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17512. /** mag = linear and min = nearest and mip = nearest */
  17513. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17514. /** mag = linear and min = nearest and mip = linear */
  17515. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17516. /** mag = linear and min = linear and mip = none */
  17517. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17518. /** mag = linear and min = nearest and mip = none */
  17519. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17520. /** Explicit coordinates mode */
  17521. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17522. /** Spherical coordinates mode */
  17523. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17524. /** Planar coordinates mode */
  17525. Engine.TEXTURE_PLANAR_MODE = 2;
  17526. /** Cubic coordinates mode */
  17527. Engine.TEXTURE_CUBIC_MODE = 3;
  17528. /** Projection coordinates mode */
  17529. Engine.TEXTURE_PROJECTION_MODE = 4;
  17530. /** Skybox coordinates mode */
  17531. Engine.TEXTURE_SKYBOX_MODE = 5;
  17532. /** Inverse Cubic coordinates mode */
  17533. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17534. /** Equirectangular coordinates mode */
  17535. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17536. /** Equirectangular Fixed coordinates mode */
  17537. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17538. /** Equirectangular Fixed Mirrored coordinates mode */
  17539. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17540. // Texture rescaling mode
  17541. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17542. Engine.SCALEMODE_FLOOR = 1;
  17543. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17544. Engine.SCALEMODE_NEAREST = 2;
  17545. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17546. Engine.SCALEMODE_CEILING = 3;
  17547. // Updatable statics so stick with vars here
  17548. /**
  17549. * Gets or sets the epsilon value used by collision engine
  17550. */
  17551. Engine.CollisionsEpsilon = 0.001;
  17552. /**
  17553. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17554. */
  17555. Engine.CodeRepository = "src/";
  17556. /**
  17557. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17558. */
  17559. Engine.ShadersRepository = "src/Shaders/";
  17560. return Engine;
  17561. }());
  17562. BABYLON.Engine = Engine;
  17563. })(BABYLON || (BABYLON = {}));
  17564. //# sourceMappingURL=babylon.engine.js.map
  17565. var BABYLON;
  17566. (function (BABYLON) {
  17567. /**
  17568. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17569. */
  17570. var Node = /** @class */ (function () {
  17571. /**
  17572. * Creates a new Node
  17573. * @param {string} name - the name and id to be given to this node
  17574. * @param {BABYLON.Scene} the scene this node will be added to
  17575. */
  17576. function Node(name, scene) {
  17577. if (scene === void 0) { scene = null; }
  17578. /**
  17579. * Gets or sets a string used to store user defined state for the node
  17580. */
  17581. this.state = "";
  17582. /**
  17583. * Gets or sets an object used to store user defined information for the node
  17584. */
  17585. this.metadata = null;
  17586. /**
  17587. * Gets or sets a boolean used to define if the node must be serialized
  17588. */
  17589. this.doNotSerialize = false;
  17590. /** @hidden */
  17591. this._isDisposed = false;
  17592. /**
  17593. * Gets a list of Animations associated with the node
  17594. */
  17595. this.animations = new Array();
  17596. this._ranges = {};
  17597. this._isEnabled = true;
  17598. this._isReady = true;
  17599. /** @hidden */
  17600. this._currentRenderId = -1;
  17601. this._parentRenderId = -1;
  17602. this._childRenderId = -1;
  17603. this._animationPropertiesOverride = null;
  17604. /**
  17605. * An event triggered when the mesh is disposed
  17606. */
  17607. this.onDisposeObservable = new BABYLON.Observable();
  17608. // Behaviors
  17609. this._behaviors = new Array();
  17610. this.name = name;
  17611. this.id = name;
  17612. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17613. this.uniqueId = this._scene.getUniqueId();
  17614. this._initCache();
  17615. this._scene.rootNodes.push(this);
  17616. }
  17617. /**
  17618. * Add a new node constructor
  17619. * @param type defines the type name of the node to construct
  17620. * @param constructorFunc defines the constructor function
  17621. */
  17622. Node.AddNodeConstructor = function (type, constructorFunc) {
  17623. this._NodeConstructors[type] = constructorFunc;
  17624. };
  17625. /**
  17626. * Returns a node constructor based on type name
  17627. * @param type defines the type name
  17628. * @param name defines the new node name
  17629. * @param scene defines the hosting scene
  17630. * @param options defines optional options to transmit to constructors
  17631. * @returns the new constructor or null
  17632. */
  17633. Node.Construct = function (type, name, scene, options) {
  17634. var constructorFunc = this._NodeConstructors[type];
  17635. if (!constructorFunc) {
  17636. return null;
  17637. }
  17638. return constructorFunc(name, scene, options);
  17639. };
  17640. /**
  17641. * Gets a boolean indicating if the node has been disposed
  17642. * @returns true if the node was disposed
  17643. */
  17644. Node.prototype.isDisposed = function () {
  17645. return this._isDisposed;
  17646. };
  17647. Object.defineProperty(Node.prototype, "parent", {
  17648. get: function () {
  17649. return this._parentNode;
  17650. },
  17651. /**
  17652. * Gets or sets the parent of the node
  17653. */
  17654. set: function (parent) {
  17655. if (this._parentNode === parent) {
  17656. return;
  17657. }
  17658. var previousParentNode = this._parentNode;
  17659. // Remove self from list of children of parent
  17660. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17661. var index = this._parentNode._children.indexOf(this);
  17662. if (index !== -1) {
  17663. this._parentNode._children.splice(index, 1);
  17664. }
  17665. if (!parent) {
  17666. // Need to add this node to the rootNodes
  17667. this._scene.rootNodes.push(this);
  17668. }
  17669. }
  17670. // Store new parent
  17671. this._parentNode = parent;
  17672. // Add as child to new parent
  17673. if (this._parentNode) {
  17674. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17675. this._parentNode._children = new Array();
  17676. }
  17677. this._parentNode._children.push(this);
  17678. if (!previousParentNode) {
  17679. // Need to remove from rootNodes
  17680. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17681. if (rootNodeIndex > -1) {
  17682. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17683. }
  17684. }
  17685. }
  17686. },
  17687. enumerable: true,
  17688. configurable: true
  17689. });
  17690. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17691. /**
  17692. * Gets or sets the animation properties override
  17693. */
  17694. get: function () {
  17695. if (!this._animationPropertiesOverride) {
  17696. return this._scene.animationPropertiesOverride;
  17697. }
  17698. return this._animationPropertiesOverride;
  17699. },
  17700. set: function (value) {
  17701. this._animationPropertiesOverride = value;
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. /**
  17707. * Gets a string idenfifying the name of the class
  17708. * @returns "Node" string
  17709. */
  17710. Node.prototype.getClassName = function () {
  17711. return "Node";
  17712. };
  17713. Object.defineProperty(Node.prototype, "onDispose", {
  17714. /**
  17715. * Sets a callback that will be raised when the node will be disposed
  17716. */
  17717. set: function (callback) {
  17718. if (this._onDisposeObserver) {
  17719. this.onDisposeObservable.remove(this._onDisposeObserver);
  17720. }
  17721. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. /**
  17727. * Gets the scene of the node
  17728. * @returns a {BABYLON.Scene}
  17729. */
  17730. Node.prototype.getScene = function () {
  17731. return this._scene;
  17732. };
  17733. /**
  17734. * Gets the engine of the node
  17735. * @returns a {BABYLON.Engine}
  17736. */
  17737. Node.prototype.getEngine = function () {
  17738. return this._scene.getEngine();
  17739. };
  17740. /**
  17741. * Attach a behavior to the node
  17742. * @see http://doc.babylonjs.com/features/behaviour
  17743. * @param behavior defines the behavior to attach
  17744. * @returns the current Node
  17745. */
  17746. Node.prototype.addBehavior = function (behavior) {
  17747. var _this = this;
  17748. var index = this._behaviors.indexOf(behavior);
  17749. if (index !== -1) {
  17750. return this;
  17751. }
  17752. behavior.init();
  17753. if (this._scene.isLoading) {
  17754. // We defer the attach when the scene will be loaded
  17755. this._scene.onDataLoadedObservable.addOnce(function () {
  17756. behavior.attach(_this);
  17757. });
  17758. }
  17759. else {
  17760. behavior.attach(this);
  17761. }
  17762. this._behaviors.push(behavior);
  17763. return this;
  17764. };
  17765. /**
  17766. * Remove an attached behavior
  17767. * @see http://doc.babylonjs.com/features/behaviour
  17768. * @param behavior defines the behavior to attach
  17769. * @returns the current Node
  17770. */
  17771. Node.prototype.removeBehavior = function (behavior) {
  17772. var index = this._behaviors.indexOf(behavior);
  17773. if (index === -1) {
  17774. return this;
  17775. }
  17776. this._behaviors[index].detach();
  17777. this._behaviors.splice(index, 1);
  17778. return this;
  17779. };
  17780. Object.defineProperty(Node.prototype, "behaviors", {
  17781. /**
  17782. * Gets the list of attached behaviors
  17783. * @see http://doc.babylonjs.com/features/behaviour
  17784. */
  17785. get: function () {
  17786. return this._behaviors;
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. /**
  17792. * Gets an attached behavior by name
  17793. * @param name defines the name of the behavior to look for
  17794. * @see http://doc.babylonjs.com/features/behaviour
  17795. * @returns null if behavior was not found else the requested behavior
  17796. */
  17797. Node.prototype.getBehaviorByName = function (name) {
  17798. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17799. var behavior = _a[_i];
  17800. if (behavior.name === name) {
  17801. return behavior;
  17802. }
  17803. }
  17804. return null;
  17805. };
  17806. /**
  17807. * Returns the world matrix of the node
  17808. * @returns a matrix containing the node's world matrix
  17809. */
  17810. Node.prototype.getWorldMatrix = function () {
  17811. return BABYLON.Matrix.Identity();
  17812. };
  17813. /** @hidden */
  17814. Node.prototype._getWorldMatrixDeterminant = function () {
  17815. return 1;
  17816. };
  17817. // override it in derived class if you add new variables to the cache
  17818. // and call the parent class method
  17819. /** @hidden */
  17820. Node.prototype._initCache = function () {
  17821. this._cache = {};
  17822. this._cache.parent = undefined;
  17823. };
  17824. /** @hidden */
  17825. Node.prototype.updateCache = function (force) {
  17826. if (!force && this.isSynchronized())
  17827. return;
  17828. this._cache.parent = this.parent;
  17829. this._updateCache();
  17830. };
  17831. // override it in derived class if you add new variables to the cache
  17832. // and call the parent class method if !ignoreParentClass
  17833. /** @hidden */
  17834. Node.prototype._updateCache = function (ignoreParentClass) {
  17835. };
  17836. // override it in derived class if you add new variables to the cache
  17837. /** @hidden */
  17838. Node.prototype._isSynchronized = function () {
  17839. return true;
  17840. };
  17841. /** @hidden */
  17842. Node.prototype._markSyncedWithParent = function () {
  17843. if (this.parent) {
  17844. this._parentRenderId = this.parent._childRenderId;
  17845. }
  17846. };
  17847. /** @hidden */
  17848. Node.prototype.isSynchronizedWithParent = function () {
  17849. if (!this.parent) {
  17850. return true;
  17851. }
  17852. if (this._parentRenderId !== this.parent._childRenderId) {
  17853. return false;
  17854. }
  17855. return this.parent.isSynchronized();
  17856. };
  17857. /** @hidden */
  17858. Node.prototype.isSynchronized = function (updateCache) {
  17859. var check = this.hasNewParent();
  17860. check = check || !this.isSynchronizedWithParent();
  17861. check = check || !this._isSynchronized();
  17862. if (updateCache)
  17863. this.updateCache(true);
  17864. return !check;
  17865. };
  17866. /** @hidden */
  17867. Node.prototype.hasNewParent = function () {
  17868. if (this._cache.parent === this.parent)
  17869. return false;
  17870. this._cache.parent = this.parent;
  17871. return true;
  17872. };
  17873. /**
  17874. * Is this node ready to be used/rendered
  17875. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17876. * @return true if the node is ready
  17877. */
  17878. Node.prototype.isReady = function (completeCheck) {
  17879. if (completeCheck === void 0) { completeCheck = false; }
  17880. return this._isReady;
  17881. };
  17882. /**
  17883. * Is this node enabled?
  17884. * 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
  17885. * @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
  17886. * @return whether this node (and its parent) is enabled
  17887. */
  17888. Node.prototype.isEnabled = function (checkAncestors) {
  17889. if (checkAncestors === void 0) { checkAncestors = true; }
  17890. if (checkAncestors === false) {
  17891. return this._isEnabled;
  17892. }
  17893. if (this._isEnabled === false) {
  17894. return false;
  17895. }
  17896. if (this.parent !== undefined && this.parent !== null) {
  17897. return this.parent.isEnabled(checkAncestors);
  17898. }
  17899. return true;
  17900. };
  17901. /**
  17902. * Set the enabled state of this node
  17903. * @param value defines the new enabled state
  17904. */
  17905. Node.prototype.setEnabled = function (value) {
  17906. this._isEnabled = value;
  17907. };
  17908. /**
  17909. * Is this node a descendant of the given node?
  17910. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17911. * @param ancestor defines the parent node to inspect
  17912. * @returns a boolean indicating if this node is a descendant of the given node
  17913. */
  17914. Node.prototype.isDescendantOf = function (ancestor) {
  17915. if (this.parent) {
  17916. if (this.parent === ancestor) {
  17917. return true;
  17918. }
  17919. return this.parent.isDescendantOf(ancestor);
  17920. }
  17921. return false;
  17922. };
  17923. /** @hidden */
  17924. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17925. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17926. if (!this._children) {
  17927. return;
  17928. }
  17929. for (var index = 0; index < this._children.length; index++) {
  17930. var item = this._children[index];
  17931. if (!predicate || predicate(item)) {
  17932. results.push(item);
  17933. }
  17934. if (!directDescendantsOnly) {
  17935. item._getDescendants(results, false, predicate);
  17936. }
  17937. }
  17938. };
  17939. /**
  17940. * Will return all nodes that have this node as ascendant
  17941. * @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
  17942. * @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
  17943. * @return all children nodes of all types
  17944. */
  17945. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17946. var results = new Array();
  17947. this._getDescendants(results, directDescendantsOnly, predicate);
  17948. return results;
  17949. };
  17950. /**
  17951. * Get all child-meshes of this node
  17952. * @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
  17953. * @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
  17954. * @returns an array of {BABYLON.AbstractMesh}
  17955. */
  17956. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17957. var results = [];
  17958. this._getDescendants(results, directDescendantsOnly, function (node) {
  17959. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17960. });
  17961. return results;
  17962. };
  17963. /**
  17964. * Get all child-transformNodes of this node
  17965. * @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
  17966. * @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
  17967. * @returns an array of {BABYLON.TransformNode}
  17968. */
  17969. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17970. var results = [];
  17971. this._getDescendants(results, directDescendantsOnly, function (node) {
  17972. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17973. });
  17974. return results;
  17975. };
  17976. /**
  17977. * Get all direct children of this node
  17978. * @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
  17979. * @returns an array of {BABYLON.Node}
  17980. */
  17981. Node.prototype.getChildren = function (predicate) {
  17982. if (!predicate) {
  17983. return this._children;
  17984. }
  17985. return this.getDescendants(true, predicate);
  17986. };
  17987. /** @hidden */
  17988. Node.prototype._setReady = function (state) {
  17989. if (state === this._isReady) {
  17990. return;
  17991. }
  17992. if (!state) {
  17993. this._isReady = false;
  17994. return;
  17995. }
  17996. if (this.onReady) {
  17997. this.onReady(this);
  17998. }
  17999. this._isReady = true;
  18000. };
  18001. /**
  18002. * Get an animation by name
  18003. * @param name defines the name of the animation to look for
  18004. * @returns null if not found else the requested animation
  18005. */
  18006. Node.prototype.getAnimationByName = function (name) {
  18007. for (var i = 0; i < this.animations.length; i++) {
  18008. var animation = this.animations[i];
  18009. if (animation.name === name) {
  18010. return animation;
  18011. }
  18012. }
  18013. return null;
  18014. };
  18015. /**
  18016. * Creates an animation range for this node
  18017. * @param name defines the name of the range
  18018. * @param from defines the starting key
  18019. * @param to defines the end key
  18020. */
  18021. Node.prototype.createAnimationRange = function (name, from, to) {
  18022. // check name not already in use
  18023. if (!this._ranges[name]) {
  18024. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18025. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18026. if (this.animations[i]) {
  18027. this.animations[i].createRange(name, from, to);
  18028. }
  18029. }
  18030. }
  18031. };
  18032. /**
  18033. * Delete a specific animation range
  18034. * @param name defines the name of the range to delete
  18035. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18036. */
  18037. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18038. if (deleteFrames === void 0) { deleteFrames = true; }
  18039. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18040. if (this.animations[i]) {
  18041. this.animations[i].deleteRange(name, deleteFrames);
  18042. }
  18043. }
  18044. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18045. };
  18046. /**
  18047. * Get an animation range by name
  18048. * @param name defines the name of the animation range to look for
  18049. * @returns null if not found else the requested animation range
  18050. */
  18051. Node.prototype.getAnimationRange = function (name) {
  18052. return this._ranges[name];
  18053. };
  18054. /**
  18055. * Will start the animation sequence
  18056. * @param name defines the range frames for animation sequence
  18057. * @param loop defines if the animation should loop (false by default)
  18058. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18059. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18060. * @returns the object created for this animation. If range does not exist, it will return null
  18061. */
  18062. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18063. var range = this.getAnimationRange(name);
  18064. if (!range) {
  18065. return null;
  18066. }
  18067. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18068. };
  18069. /**
  18070. * Serialize animation ranges into a JSON compatible object
  18071. * @returns serialization object
  18072. */
  18073. Node.prototype.serializeAnimationRanges = function () {
  18074. var serializationRanges = [];
  18075. for (var name in this._ranges) {
  18076. var localRange = this._ranges[name];
  18077. if (!localRange) {
  18078. continue;
  18079. }
  18080. var range = {};
  18081. range.name = name;
  18082. range.from = localRange.from;
  18083. range.to = localRange.to;
  18084. serializationRanges.push(range);
  18085. }
  18086. return serializationRanges;
  18087. };
  18088. /**
  18089. * Computes the world matrix of the node
  18090. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18091. * @returns the world matrix
  18092. */
  18093. Node.prototype.computeWorldMatrix = function (force) {
  18094. return BABYLON.Matrix.Identity();
  18095. };
  18096. /**
  18097. * Releases resources associated with this node.
  18098. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18099. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18100. */
  18101. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18102. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18103. if (!doNotRecurse) {
  18104. var nodes = this.getDescendants(true);
  18105. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18106. var node = nodes_1[_i];
  18107. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18108. }
  18109. }
  18110. else {
  18111. var transformNodes = this.getChildTransformNodes(true);
  18112. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18113. var transformNode = transformNodes_1[_a];
  18114. transformNode.parent = null;
  18115. transformNode.computeWorldMatrix(true);
  18116. }
  18117. }
  18118. if (!this.parent) {
  18119. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18120. if (rootNodeIndex > -1) {
  18121. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18122. }
  18123. }
  18124. else {
  18125. this.parent = null;
  18126. }
  18127. // Callback
  18128. this.onDisposeObservable.notifyObservers(this);
  18129. this.onDisposeObservable.clear();
  18130. // Behaviors
  18131. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18132. var behavior = _c[_b];
  18133. behavior.detach();
  18134. }
  18135. this._behaviors = [];
  18136. this._isDisposed = true;
  18137. };
  18138. /**
  18139. * Parse animation range data from a serialization object and store them into a given node
  18140. * @param node defines where to store the animation ranges
  18141. * @param parsedNode defines the serialization object to read data from
  18142. * @param scene defines the hosting scene
  18143. */
  18144. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18145. if (parsedNode.ranges) {
  18146. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18147. var data = parsedNode.ranges[index];
  18148. node.createAnimationRange(data.name, data.from, data.to);
  18149. }
  18150. }
  18151. };
  18152. Node._NodeConstructors = {};
  18153. __decorate([
  18154. BABYLON.serialize()
  18155. ], Node.prototype, "name", void 0);
  18156. __decorate([
  18157. BABYLON.serialize()
  18158. ], Node.prototype, "id", void 0);
  18159. __decorate([
  18160. BABYLON.serialize()
  18161. ], Node.prototype, "uniqueId", void 0);
  18162. __decorate([
  18163. BABYLON.serialize()
  18164. ], Node.prototype, "state", void 0);
  18165. __decorate([
  18166. BABYLON.serialize()
  18167. ], Node.prototype, "metadata", void 0);
  18168. return Node;
  18169. }());
  18170. BABYLON.Node = Node;
  18171. })(BABYLON || (BABYLON = {}));
  18172. //# sourceMappingURL=babylon.node.js.map
  18173. var BABYLON;
  18174. (function (BABYLON) {
  18175. // This matrix is used as a value to reset the bounding box.
  18176. var _identityMatrix = BABYLON.Matrix.Identity();
  18177. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18178. var BoundingSphere = /** @class */ (function () {
  18179. /**
  18180. * Creates a new bounding sphere
  18181. * @param min defines the minimum vector (in local space)
  18182. * @param max defines the maximum vector (in local space)
  18183. */
  18184. function BoundingSphere(min, max) {
  18185. this.center = BABYLON.Vector3.Zero();
  18186. this.centerWorld = BABYLON.Vector3.Zero();
  18187. this.reConstruct(min, max);
  18188. }
  18189. /**
  18190. * Recreates the entire bounding sphere from scratch
  18191. * @param min defines the new minimum vector (in local space)
  18192. * @param max defines the new maximum vector (in local space)
  18193. */
  18194. BoundingSphere.prototype.reConstruct = function (min, max) {
  18195. this.minimum = min.clone();
  18196. this.maximum = max.clone();
  18197. var distance = BABYLON.Vector3.Distance(min, max);
  18198. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18199. this.radius = distance * 0.5;
  18200. this.centerWorld.set(0, 0, 0);
  18201. this._update(_identityMatrix);
  18202. };
  18203. /**
  18204. * Scale the current bounding sphere by applying a scale factor
  18205. * @param factor defines the scale factor to apply
  18206. * @returns the current bounding box
  18207. */
  18208. BoundingSphere.prototype.scale = function (factor) {
  18209. var newRadius = this.radius * factor;
  18210. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18211. var min = this.center.subtract(_tempRadiusVector);
  18212. var max = this.center.add(_tempRadiusVector);
  18213. this.reConstruct(min, max);
  18214. return this;
  18215. };
  18216. // Methods
  18217. /** @hidden */
  18218. BoundingSphere.prototype._update = function (world) {
  18219. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18220. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18221. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18222. };
  18223. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18224. for (var i = 0; i < 6; i++) {
  18225. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18226. return false;
  18227. }
  18228. return true;
  18229. };
  18230. BoundingSphere.prototype.intersectsPoint = function (point) {
  18231. var x = this.centerWorld.x - point.x;
  18232. var y = this.centerWorld.y - point.y;
  18233. var z = this.centerWorld.z - point.z;
  18234. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18235. if (this.radiusWorld < distance)
  18236. return false;
  18237. return true;
  18238. };
  18239. // Statics
  18240. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18241. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18242. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18243. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18244. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18245. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18246. return false;
  18247. return true;
  18248. };
  18249. return BoundingSphere;
  18250. }());
  18251. BABYLON.BoundingSphere = BoundingSphere;
  18252. })(BABYLON || (BABYLON = {}));
  18253. //# sourceMappingURL=babylon.boundingSphere.js.map
  18254. var BABYLON;
  18255. (function (BABYLON) {
  18256. var BoundingBox = /** @class */ (function () {
  18257. /**
  18258. * Creates a new bounding box
  18259. * @param min defines the minimum vector (in local space)
  18260. * @param max defines the maximum vector (in local space)
  18261. */
  18262. function BoundingBox(min, max) {
  18263. this.vectorsWorld = new Array();
  18264. this.reConstruct(min, max);
  18265. }
  18266. // Methods
  18267. /**
  18268. * Recreates the entire bounding box from scratch
  18269. * @param min defines the new minimum vector (in local space)
  18270. * @param max defines the new maximum vector (in local space)
  18271. */
  18272. BoundingBox.prototype.reConstruct = function (min, max) {
  18273. this.minimum = min.clone();
  18274. this.maximum = max.clone();
  18275. // Bounding vectors
  18276. this.vectors = [
  18277. this.minimum.clone(),
  18278. this.maximum.clone(),
  18279. this.minimum.clone(),
  18280. this.minimum.clone(),
  18281. this.minimum.clone(),
  18282. this.maximum.clone(),
  18283. this.maximum.clone(),
  18284. this.maximum.clone()
  18285. ];
  18286. this.vectors[2].x = this.maximum.x;
  18287. this.vectors[3].y = this.maximum.y;
  18288. this.vectors[4].z = this.maximum.z;
  18289. this.vectors[5].z = this.minimum.z;
  18290. this.vectors[6].x = this.minimum.x;
  18291. this.vectors[7].y = this.minimum.y;
  18292. // OBB
  18293. this.center = this.maximum.add(this.minimum).scale(0.5);
  18294. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18295. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18296. // World
  18297. for (var index = 0; index < this.vectors.length; index++) {
  18298. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18299. }
  18300. this.minimumWorld = BABYLON.Vector3.Zero();
  18301. this.maximumWorld = BABYLON.Vector3.Zero();
  18302. this.centerWorld = BABYLON.Vector3.Zero();
  18303. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18304. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18305. };
  18306. /**
  18307. * Scale the current bounding box by applying a scale factor
  18308. * @param factor defines the scale factor to apply
  18309. * @returns the current bounding box
  18310. */
  18311. BoundingBox.prototype.scale = function (factor) {
  18312. var diff = this.maximum.subtract(this.minimum);
  18313. var distance = diff.length() * factor;
  18314. diff.normalize();
  18315. var newRadius = diff.scale(distance / 2);
  18316. var min = this.center.subtract(newRadius);
  18317. var max = this.center.add(newRadius);
  18318. this.reConstruct(min, max);
  18319. return this;
  18320. };
  18321. BoundingBox.prototype.getWorldMatrix = function () {
  18322. return this._worldMatrix;
  18323. };
  18324. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18325. this._worldMatrix.copyFrom(matrix);
  18326. return this;
  18327. };
  18328. /** @hidden */
  18329. BoundingBox.prototype._update = function (world) {
  18330. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18331. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18332. for (var index = 0; index < this.vectors.length; index++) {
  18333. var v = this.vectorsWorld[index];
  18334. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18335. if (v.x < this.minimumWorld.x)
  18336. this.minimumWorld.x = v.x;
  18337. if (v.y < this.minimumWorld.y)
  18338. this.minimumWorld.y = v.y;
  18339. if (v.z < this.minimumWorld.z)
  18340. this.minimumWorld.z = v.z;
  18341. if (v.x > this.maximumWorld.x)
  18342. this.maximumWorld.x = v.x;
  18343. if (v.y > this.maximumWorld.y)
  18344. this.maximumWorld.y = v.y;
  18345. if (v.z > this.maximumWorld.z)
  18346. this.maximumWorld.z = v.z;
  18347. }
  18348. // Extend
  18349. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18350. this.extendSizeWorld.scaleInPlace(0.5);
  18351. // OBB
  18352. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18353. this.centerWorld.scaleInPlace(0.5);
  18354. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18355. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18356. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18357. this._worldMatrix = world;
  18358. };
  18359. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18360. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18361. };
  18362. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18363. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18364. };
  18365. BoundingBox.prototype.intersectsPoint = function (point) {
  18366. var delta = -BABYLON.Epsilon;
  18367. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18368. return false;
  18369. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18370. return false;
  18371. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18372. return false;
  18373. return true;
  18374. };
  18375. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18376. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18377. };
  18378. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18379. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18380. return false;
  18381. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18382. return false;
  18383. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18384. return false;
  18385. return true;
  18386. };
  18387. // Statics
  18388. BoundingBox.Intersects = function (box0, box1) {
  18389. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18390. return false;
  18391. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18392. return false;
  18393. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18394. return false;
  18395. return true;
  18396. };
  18397. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18398. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18399. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18400. return (num <= (sphereRadius * sphereRadius));
  18401. };
  18402. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18403. for (var p = 0; p < 6; p++) {
  18404. for (var i = 0; i < 8; i++) {
  18405. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18406. return false;
  18407. }
  18408. }
  18409. }
  18410. return true;
  18411. };
  18412. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18413. for (var p = 0; p < 6; p++) {
  18414. var inCount = 8;
  18415. for (var i = 0; i < 8; i++) {
  18416. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18417. --inCount;
  18418. }
  18419. else {
  18420. break;
  18421. }
  18422. }
  18423. if (inCount === 0)
  18424. return false;
  18425. }
  18426. return true;
  18427. };
  18428. return BoundingBox;
  18429. }());
  18430. BABYLON.BoundingBox = BoundingBox;
  18431. })(BABYLON || (BABYLON = {}));
  18432. //# sourceMappingURL=babylon.boundingBox.js.map
  18433. var BABYLON;
  18434. (function (BABYLON) {
  18435. var computeBoxExtents = function (axis, box) {
  18436. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18437. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18438. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18439. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18440. var r = r0 + r1 + r2;
  18441. return {
  18442. min: p - r,
  18443. max: p + r
  18444. };
  18445. };
  18446. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18447. var axisOverlap = function (axis, box0, box1) {
  18448. var result0 = computeBoxExtents(axis, box0);
  18449. var result1 = computeBoxExtents(axis, box1);
  18450. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18451. };
  18452. var BoundingInfo = /** @class */ (function () {
  18453. function BoundingInfo(minimum, maximum) {
  18454. this.minimum = minimum;
  18455. this.maximum = maximum;
  18456. this._isLocked = false;
  18457. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18458. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18459. }
  18460. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18461. get: function () {
  18462. return this._isLocked;
  18463. },
  18464. set: function (value) {
  18465. this._isLocked = value;
  18466. },
  18467. enumerable: true,
  18468. configurable: true
  18469. });
  18470. // Methods
  18471. BoundingInfo.prototype.update = function (world) {
  18472. if (this._isLocked) {
  18473. return;
  18474. }
  18475. this.boundingBox._update(world);
  18476. this.boundingSphere._update(world);
  18477. };
  18478. /**
  18479. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18480. * @param center New center of the bounding info
  18481. * @param extend New extend of the bounding info
  18482. */
  18483. BoundingInfo.prototype.centerOn = function (center, extend) {
  18484. this.minimum = center.subtract(extend);
  18485. this.maximum = center.add(extend);
  18486. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18487. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18488. return this;
  18489. };
  18490. /**
  18491. * Scale the current bounding info by applying a scale factor
  18492. * @param factor defines the scale factor to apply
  18493. * @returns the current bounding info
  18494. */
  18495. BoundingInfo.prototype.scale = function (factor) {
  18496. this.boundingBox.scale(factor);
  18497. this.boundingSphere.scale(factor);
  18498. return this;
  18499. };
  18500. /**
  18501. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18502. * @param frustumPlanes defines the frustum to test
  18503. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18504. * @returns true if the bounding info is in the frustum planes
  18505. */
  18506. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18507. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18508. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18509. return false;
  18510. }
  18511. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18512. return true;
  18513. }
  18514. return this.boundingBox.isInFrustum(frustumPlanes);
  18515. };
  18516. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18517. /**
  18518. * Gets the world distance between the min and max points of the bounding box
  18519. */
  18520. get: function () {
  18521. var boundingBox = this.boundingBox;
  18522. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18523. return size.length();
  18524. },
  18525. enumerable: true,
  18526. configurable: true
  18527. });
  18528. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18529. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18530. };
  18531. /** @hidden */
  18532. BoundingInfo.prototype._checkCollision = function (collider) {
  18533. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18534. };
  18535. BoundingInfo.prototype.intersectsPoint = function (point) {
  18536. if (!this.boundingSphere.centerWorld) {
  18537. return false;
  18538. }
  18539. if (!this.boundingSphere.intersectsPoint(point)) {
  18540. return false;
  18541. }
  18542. if (!this.boundingBox.intersectsPoint(point)) {
  18543. return false;
  18544. }
  18545. return true;
  18546. };
  18547. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18548. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18549. return false;
  18550. }
  18551. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18552. return false;
  18553. }
  18554. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18555. return false;
  18556. }
  18557. if (!precise) {
  18558. return true;
  18559. }
  18560. var box0 = this.boundingBox;
  18561. var box1 = boundingInfo.boundingBox;
  18562. if (!axisOverlap(box0.directions[0], box0, box1))
  18563. return false;
  18564. if (!axisOverlap(box0.directions[1], box0, box1))
  18565. return false;
  18566. if (!axisOverlap(box0.directions[2], box0, box1))
  18567. return false;
  18568. if (!axisOverlap(box1.directions[0], box0, box1))
  18569. return false;
  18570. if (!axisOverlap(box1.directions[1], box0, box1))
  18571. return false;
  18572. if (!axisOverlap(box1.directions[2], box0, box1))
  18573. return false;
  18574. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18575. return false;
  18576. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18577. return false;
  18578. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18579. return false;
  18580. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18581. return false;
  18582. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18583. return false;
  18584. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18585. return false;
  18586. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18587. return false;
  18588. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18589. return false;
  18590. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18591. return false;
  18592. return true;
  18593. };
  18594. return BoundingInfo;
  18595. }());
  18596. BABYLON.BoundingInfo = BoundingInfo;
  18597. })(BABYLON || (BABYLON = {}));
  18598. //# sourceMappingURL=babylon.boundingInfo.js.map
  18599. var BABYLON;
  18600. (function (BABYLON) {
  18601. var TransformNode = /** @class */ (function (_super) {
  18602. __extends(TransformNode, _super);
  18603. function TransformNode(name, scene, isPure) {
  18604. if (scene === void 0) { scene = null; }
  18605. if (isPure === void 0) { isPure = true; }
  18606. var _this = _super.call(this, name, scene) || this;
  18607. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18608. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18609. _this._up = new BABYLON.Vector3(0, 1, 0);
  18610. _this._right = new BABYLON.Vector3(1, 0, 0);
  18611. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18612. // Properties
  18613. _this._rotation = BABYLON.Vector3.Zero();
  18614. _this._scaling = BABYLON.Vector3.One();
  18615. _this._isDirty = false;
  18616. /**
  18617. * Set the billboard mode. Default is 0.
  18618. *
  18619. * | Value | Type | Description |
  18620. * | --- | --- | --- |
  18621. * | 0 | BILLBOARDMODE_NONE | |
  18622. * | 1 | BILLBOARDMODE_X | |
  18623. * | 2 | BILLBOARDMODE_Y | |
  18624. * | 4 | BILLBOARDMODE_Z | |
  18625. * | 7 | BILLBOARDMODE_ALL | |
  18626. *
  18627. */
  18628. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18629. _this.scalingDeterminant = 1;
  18630. _this.infiniteDistance = false;
  18631. /**
  18632. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18633. * By default the system will update normals to compensate
  18634. */
  18635. _this.ignoreNonUniformScaling = false;
  18636. _this.position = BABYLON.Vector3.Zero();
  18637. _this._localWorld = BABYLON.Matrix.Zero();
  18638. /** @hidden */
  18639. _this._worldMatrix = BABYLON.Matrix.Zero();
  18640. /** @hidden */
  18641. _this._worldMatrixDeterminant = 0;
  18642. _this._absolutePosition = BABYLON.Vector3.Zero();
  18643. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18644. _this._postMultiplyPivotMatrix = false;
  18645. _this._isWorldMatrixFrozen = false;
  18646. /**
  18647. * An event triggered after the world matrix is updated
  18648. */
  18649. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18650. _this._nonUniformScaling = false;
  18651. if (isPure) {
  18652. _this.getScene().addTransformNode(_this);
  18653. }
  18654. return _this;
  18655. }
  18656. /**
  18657. * Gets a string identifying the name of the class
  18658. * @returns "TransformNode" string
  18659. */
  18660. TransformNode.prototype.getClassName = function () {
  18661. return "TransformNode";
  18662. };
  18663. Object.defineProperty(TransformNode.prototype, "rotation", {
  18664. /**
  18665. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18666. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18667. * Default : (0.0, 0.0, 0.0)
  18668. */
  18669. get: function () {
  18670. return this._rotation;
  18671. },
  18672. set: function (newRotation) {
  18673. this._rotation = newRotation;
  18674. },
  18675. enumerable: true,
  18676. configurable: true
  18677. });
  18678. Object.defineProperty(TransformNode.prototype, "scaling", {
  18679. /**
  18680. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18681. * Default : (1.0, 1.0, 1.0)
  18682. */
  18683. get: function () {
  18684. return this._scaling;
  18685. },
  18686. /**
  18687. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18688. * Default : (1.0, 1.0, 1.0)
  18689. */
  18690. set: function (newScaling) {
  18691. this._scaling = newScaling;
  18692. },
  18693. enumerable: true,
  18694. configurable: true
  18695. });
  18696. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18697. /**
  18698. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18699. * It's null by default.
  18700. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18701. */
  18702. get: function () {
  18703. return this._rotationQuaternion;
  18704. },
  18705. set: function (quaternion) {
  18706. this._rotationQuaternion = quaternion;
  18707. //reset the rotation vector.
  18708. if (quaternion && this.rotation.length()) {
  18709. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18710. }
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. Object.defineProperty(TransformNode.prototype, "forward", {
  18716. /**
  18717. * The forward direction of that transform in world space.
  18718. */
  18719. get: function () {
  18720. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18721. },
  18722. enumerable: true,
  18723. configurable: true
  18724. });
  18725. Object.defineProperty(TransformNode.prototype, "up", {
  18726. /**
  18727. * The up direction of that transform in world space.
  18728. */
  18729. get: function () {
  18730. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18731. },
  18732. enumerable: true,
  18733. configurable: true
  18734. });
  18735. Object.defineProperty(TransformNode.prototype, "right", {
  18736. /**
  18737. * The right direction of that transform in world space.
  18738. */
  18739. get: function () {
  18740. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. /**
  18746. * Returns the latest update of the World matrix
  18747. * Returns a Matrix.
  18748. */
  18749. TransformNode.prototype.getWorldMatrix = function () {
  18750. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18751. this.computeWorldMatrix();
  18752. }
  18753. return this._worldMatrix;
  18754. };
  18755. /** @hidden */
  18756. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18757. return this._worldMatrixDeterminant;
  18758. };
  18759. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18760. /**
  18761. * Returns directly the latest state of the mesh World matrix.
  18762. * A Matrix is returned.
  18763. */
  18764. get: function () {
  18765. return this._worldMatrix;
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. /**
  18771. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18772. * Returns the TransformNode.
  18773. */
  18774. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18775. this._poseMatrix.copyFrom(matrix);
  18776. return this;
  18777. };
  18778. /**
  18779. * Returns the mesh Pose matrix.
  18780. * Returned object : Matrix
  18781. */
  18782. TransformNode.prototype.getPoseMatrix = function () {
  18783. return this._poseMatrix;
  18784. };
  18785. /** @hidden */
  18786. TransformNode.prototype._isSynchronized = function () {
  18787. if (this._isDirty) {
  18788. return false;
  18789. }
  18790. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18791. return false;
  18792. if (this._cache.pivotMatrixUpdated) {
  18793. return false;
  18794. }
  18795. if (this.infiniteDistance) {
  18796. return false;
  18797. }
  18798. if (!this._cache.position.equals(this.position))
  18799. return false;
  18800. if (this._rotationQuaternion) {
  18801. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18802. return false;
  18803. }
  18804. if (!this._cache.rotation.equals(this.rotation))
  18805. return false;
  18806. if (!this._cache.scaling.equals(this.scaling))
  18807. return false;
  18808. return true;
  18809. };
  18810. /** @hidden */
  18811. TransformNode.prototype._initCache = function () {
  18812. _super.prototype._initCache.call(this);
  18813. this._cache.localMatrixUpdated = false;
  18814. this._cache.position = BABYLON.Vector3.Zero();
  18815. this._cache.scaling = BABYLON.Vector3.Zero();
  18816. this._cache.rotation = BABYLON.Vector3.Zero();
  18817. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18818. this._cache.billboardMode = -1;
  18819. };
  18820. TransformNode.prototype.markAsDirty = function (property) {
  18821. if (property === "rotation") {
  18822. this.rotationQuaternion = null;
  18823. }
  18824. this._currentRenderId = Number.MAX_VALUE;
  18825. this._isDirty = true;
  18826. return this;
  18827. };
  18828. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18829. /**
  18830. * Returns the current mesh absolute position.
  18831. * Returns a Vector3.
  18832. */
  18833. get: function () {
  18834. return this._absolutePosition;
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. /**
  18840. * Sets a new matrix to apply before all other transformation
  18841. * @param matrix defines the transform matrix
  18842. * @returns the current TransformNode
  18843. */
  18844. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18845. return this.setPivotMatrix(matrix, false);
  18846. };
  18847. /**
  18848. * Sets a new pivot matrix to the current node
  18849. * @param matrix defines the new pivot matrix to use
  18850. * @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
  18851. * @returns the current TransformNode
  18852. */
  18853. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18854. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18855. this._pivotMatrix = matrix.clone();
  18856. this._cache.pivotMatrixUpdated = true;
  18857. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18858. if (this._postMultiplyPivotMatrix) {
  18859. if (!this._pivotMatrixInverse) {
  18860. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18861. }
  18862. else {
  18863. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18864. }
  18865. }
  18866. return this;
  18867. };
  18868. /**
  18869. * Returns the mesh pivot matrix.
  18870. * Default : Identity.
  18871. * A Matrix is returned.
  18872. */
  18873. TransformNode.prototype.getPivotMatrix = function () {
  18874. return this._pivotMatrix;
  18875. };
  18876. /**
  18877. * Prevents the World matrix to be computed any longer.
  18878. * Returns the TransformNode.
  18879. */
  18880. TransformNode.prototype.freezeWorldMatrix = function () {
  18881. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18882. this.computeWorldMatrix(true);
  18883. this._isWorldMatrixFrozen = true;
  18884. return this;
  18885. };
  18886. /**
  18887. * Allows back the World matrix computation.
  18888. * Returns the TransformNode.
  18889. */
  18890. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18891. this._isWorldMatrixFrozen = false;
  18892. this.computeWorldMatrix(true);
  18893. return this;
  18894. };
  18895. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18896. /**
  18897. * True if the World matrix has been frozen.
  18898. * Returns a boolean.
  18899. */
  18900. get: function () {
  18901. return this._isWorldMatrixFrozen;
  18902. },
  18903. enumerable: true,
  18904. configurable: true
  18905. });
  18906. /**
  18907. * Retuns the mesh absolute position in the World.
  18908. * Returns a Vector3.
  18909. */
  18910. TransformNode.prototype.getAbsolutePosition = function () {
  18911. this.computeWorldMatrix();
  18912. return this._absolutePosition;
  18913. };
  18914. /**
  18915. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18916. * Returns the TransformNode.
  18917. */
  18918. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18919. if (!absolutePosition) {
  18920. return this;
  18921. }
  18922. var absolutePositionX;
  18923. var absolutePositionY;
  18924. var absolutePositionZ;
  18925. if (absolutePosition.x === undefined) {
  18926. if (arguments.length < 3) {
  18927. return this;
  18928. }
  18929. absolutePositionX = arguments[0];
  18930. absolutePositionY = arguments[1];
  18931. absolutePositionZ = arguments[2];
  18932. }
  18933. else {
  18934. absolutePositionX = absolutePosition.x;
  18935. absolutePositionY = absolutePosition.y;
  18936. absolutePositionZ = absolutePosition.z;
  18937. }
  18938. if (this.parent) {
  18939. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18940. invertParentWorldMatrix.invert();
  18941. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18942. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18943. }
  18944. else {
  18945. this.position.x = absolutePositionX;
  18946. this.position.y = absolutePositionY;
  18947. this.position.z = absolutePositionZ;
  18948. }
  18949. return this;
  18950. };
  18951. /**
  18952. * Sets the mesh position in its local space.
  18953. * Returns the TransformNode.
  18954. */
  18955. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18956. this.computeWorldMatrix();
  18957. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18958. return this;
  18959. };
  18960. /**
  18961. * Returns the mesh position in the local space from the current World matrix values.
  18962. * Returns a new Vector3.
  18963. */
  18964. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18965. this.computeWorldMatrix();
  18966. var invLocalWorldMatrix = this._localWorld.clone();
  18967. invLocalWorldMatrix.invert();
  18968. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18969. };
  18970. /**
  18971. * Translates the mesh along the passed Vector3 in its local space.
  18972. * Returns the TransformNode.
  18973. */
  18974. TransformNode.prototype.locallyTranslate = function (vector3) {
  18975. this.computeWorldMatrix(true);
  18976. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18977. return this;
  18978. };
  18979. /**
  18980. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18981. * @param targetPoint the position (must be in same space as current mesh) to look at
  18982. * @param yawCor optional yaw (y-axis) correction in radians
  18983. * @param pitchCor optional pitch (x-axis) correction in radians
  18984. * @param rollCor optional roll (z-axis) correction in radians
  18985. * @param space the choosen space of the target
  18986. * @returns the TransformNode.
  18987. */
  18988. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18989. if (yawCor === void 0) { yawCor = 0; }
  18990. if (pitchCor === void 0) { pitchCor = 0; }
  18991. if (rollCor === void 0) { rollCor = 0; }
  18992. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18993. var dv = TransformNode._lookAtVectorCache;
  18994. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18995. targetPoint.subtractToRef(pos, dv);
  18996. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18997. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18998. var pitch = Math.atan2(dv.y, len);
  18999. if (this.rotationQuaternion) {
  19000. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19001. }
  19002. else {
  19003. this.rotation.x = pitch + pitchCor;
  19004. this.rotation.y = yaw + yawCor;
  19005. this.rotation.z = rollCor;
  19006. }
  19007. return this;
  19008. };
  19009. /**
  19010. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19011. * This Vector3 is expressed in the World space.
  19012. */
  19013. TransformNode.prototype.getDirection = function (localAxis) {
  19014. var result = BABYLON.Vector3.Zero();
  19015. this.getDirectionToRef(localAxis, result);
  19016. return result;
  19017. };
  19018. /**
  19019. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19020. * localAxis is expressed in the mesh local space.
  19021. * result is computed in the Wordl space from the mesh World matrix.
  19022. * Returns the TransformNode.
  19023. */
  19024. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19025. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19026. return this;
  19027. };
  19028. /**
  19029. * Sets a new pivot point to the current node
  19030. * @param point defines the new pivot point to use
  19031. * @param space defines if the point is in world or local space (local by default)
  19032. * @returns the current TransformNode
  19033. */
  19034. TransformNode.prototype.setPivotPoint = function (point, space) {
  19035. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19036. if (this.getScene().getRenderId() == 0) {
  19037. this.computeWorldMatrix(true);
  19038. }
  19039. var wm = this.getWorldMatrix();
  19040. if (space == BABYLON.Space.WORLD) {
  19041. var tmat = BABYLON.Tmp.Matrix[0];
  19042. wm.invertToRef(tmat);
  19043. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19044. }
  19045. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19046. };
  19047. /**
  19048. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19049. */
  19050. TransformNode.prototype.getPivotPoint = function () {
  19051. var point = BABYLON.Vector3.Zero();
  19052. this.getPivotPointToRef(point);
  19053. return point;
  19054. };
  19055. /**
  19056. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19057. * Returns the TransformNode.
  19058. */
  19059. TransformNode.prototype.getPivotPointToRef = function (result) {
  19060. result.x = -this._pivotMatrix.m[12];
  19061. result.y = -this._pivotMatrix.m[13];
  19062. result.z = -this._pivotMatrix.m[14];
  19063. return this;
  19064. };
  19065. /**
  19066. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19067. */
  19068. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19069. var point = BABYLON.Vector3.Zero();
  19070. this.getAbsolutePivotPointToRef(point);
  19071. return point;
  19072. };
  19073. /**
  19074. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19075. * Returns the TransformNode.
  19076. */
  19077. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19078. result.x = this._pivotMatrix.m[12];
  19079. result.y = this._pivotMatrix.m[13];
  19080. result.z = this._pivotMatrix.m[14];
  19081. this.getPivotPointToRef(result);
  19082. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19083. return this;
  19084. };
  19085. /**
  19086. * Defines the passed node as the parent of the current node.
  19087. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19088. * Returns the TransformNode.
  19089. */
  19090. TransformNode.prototype.setParent = function (node) {
  19091. if (!node && !this.parent) {
  19092. return this;
  19093. }
  19094. if (!node) {
  19095. var rotation = BABYLON.Tmp.Quaternion[0];
  19096. var position = BABYLON.Tmp.Vector3[0];
  19097. var scale = BABYLON.Tmp.Vector3[1];
  19098. if (this.parent && this.parent.computeWorldMatrix) {
  19099. this.parent.computeWorldMatrix(true);
  19100. }
  19101. this.computeWorldMatrix(true);
  19102. this.getWorldMatrix().decompose(scale, rotation, position);
  19103. if (this.rotationQuaternion) {
  19104. this.rotationQuaternion.copyFrom(rotation);
  19105. }
  19106. else {
  19107. rotation.toEulerAnglesToRef(this.rotation);
  19108. }
  19109. this.scaling.x = scale.x;
  19110. this.scaling.y = scale.y;
  19111. this.scaling.z = scale.z;
  19112. this.position.x = position.x;
  19113. this.position.y = position.y;
  19114. this.position.z = position.z;
  19115. }
  19116. else {
  19117. var rotation = BABYLON.Tmp.Quaternion[0];
  19118. var position = BABYLON.Tmp.Vector3[0];
  19119. var scale = BABYLON.Tmp.Vector3[1];
  19120. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19121. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19122. this.computeWorldMatrix(true);
  19123. node.computeWorldMatrix(true);
  19124. node.getWorldMatrix().invertToRef(invParentMatrix);
  19125. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19126. diffMatrix.decompose(scale, rotation, position);
  19127. if (this.rotationQuaternion) {
  19128. this.rotationQuaternion.copyFrom(rotation);
  19129. }
  19130. else {
  19131. rotation.toEulerAnglesToRef(this.rotation);
  19132. }
  19133. this.position.x = position.x;
  19134. this.position.y = position.y;
  19135. this.position.z = position.z;
  19136. this.scaling.x = scale.x;
  19137. this.scaling.y = scale.y;
  19138. this.scaling.z = scale.z;
  19139. }
  19140. this.parent = node;
  19141. return this;
  19142. };
  19143. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19144. get: function () {
  19145. return this._nonUniformScaling;
  19146. },
  19147. enumerable: true,
  19148. configurable: true
  19149. });
  19150. /** @hidden */
  19151. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19152. if (this._nonUniformScaling === value) {
  19153. return false;
  19154. }
  19155. this._nonUniformScaling = value;
  19156. return true;
  19157. };
  19158. /**
  19159. * Attach the current TransformNode to another TransformNode associated with a bone
  19160. * @param bone Bone affecting the TransformNode
  19161. * @param affectedTransformNode TransformNode associated with the bone
  19162. */
  19163. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19164. this._transformToBoneReferal = affectedTransformNode;
  19165. this.parent = bone;
  19166. if (bone.getWorldMatrix().determinant() < 0) {
  19167. this.scalingDeterminant *= -1;
  19168. }
  19169. return this;
  19170. };
  19171. TransformNode.prototype.detachFromBone = function () {
  19172. if (!this.parent) {
  19173. return this;
  19174. }
  19175. if (this.parent.getWorldMatrix().determinant() < 0) {
  19176. this.scalingDeterminant *= -1;
  19177. }
  19178. this._transformToBoneReferal = null;
  19179. this.parent = null;
  19180. return this;
  19181. };
  19182. /**
  19183. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19184. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19185. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19186. * The passed axis is also normalized.
  19187. * Returns the TransformNode.
  19188. */
  19189. TransformNode.prototype.rotate = function (axis, amount, space) {
  19190. axis.normalize();
  19191. if (!this.rotationQuaternion) {
  19192. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19193. this.rotation = BABYLON.Vector3.Zero();
  19194. }
  19195. var rotationQuaternion;
  19196. if (!space || space === BABYLON.Space.LOCAL) {
  19197. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19198. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19199. }
  19200. else {
  19201. if (this.parent) {
  19202. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19203. invertParentWorldMatrix.invert();
  19204. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19205. }
  19206. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19207. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19208. }
  19209. return this;
  19210. };
  19211. /**
  19212. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19213. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19214. * The passed axis is also normalized.
  19215. * Returns the TransformNode.
  19216. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19217. */
  19218. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19219. axis.normalize();
  19220. if (!this.rotationQuaternion) {
  19221. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19222. this.rotation.copyFromFloats(0, 0, 0);
  19223. }
  19224. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19225. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19226. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19227. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19228. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19229. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19230. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19231. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19232. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19233. return this;
  19234. };
  19235. /**
  19236. * Translates the mesh along the axis vector for the passed distance in the given space.
  19237. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19238. * Returns the TransformNode.
  19239. */
  19240. TransformNode.prototype.translate = function (axis, distance, space) {
  19241. var displacementVector = axis.scale(distance);
  19242. if (!space || space === BABYLON.Space.LOCAL) {
  19243. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19244. this.setPositionWithLocalVector(tempV3);
  19245. }
  19246. else {
  19247. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19248. }
  19249. return this;
  19250. };
  19251. /**
  19252. * Adds a rotation step to the mesh current rotation.
  19253. * x, y, z are Euler angles expressed in radians.
  19254. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19255. * This means this rotation is made in the mesh local space only.
  19256. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19257. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19258. * ```javascript
  19259. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19260. * ```
  19261. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19262. * 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.
  19263. * Returns the TransformNode.
  19264. */
  19265. TransformNode.prototype.addRotation = function (x, y, z) {
  19266. var rotationQuaternion;
  19267. if (this.rotationQuaternion) {
  19268. rotationQuaternion = this.rotationQuaternion;
  19269. }
  19270. else {
  19271. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19272. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19273. }
  19274. var accumulation = BABYLON.Tmp.Quaternion[0];
  19275. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19276. rotationQuaternion.multiplyInPlace(accumulation);
  19277. if (!this.rotationQuaternion) {
  19278. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19279. }
  19280. return this;
  19281. };
  19282. /**
  19283. * Computes the mesh World matrix and returns it.
  19284. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19285. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19286. * If the parameter `force`is set to `true`, the actual computation is done.
  19287. * Returns the mesh World Matrix.
  19288. */
  19289. TransformNode.prototype.computeWorldMatrix = function (force) {
  19290. if (this._isWorldMatrixFrozen) {
  19291. return this._worldMatrix;
  19292. }
  19293. if (!force && this.isSynchronized(true)) {
  19294. this._currentRenderId = this.getScene().getRenderId();
  19295. return this._worldMatrix;
  19296. }
  19297. this._cache.position.copyFrom(this.position);
  19298. this._cache.scaling.copyFrom(this.scaling);
  19299. this._cache.pivotMatrixUpdated = false;
  19300. this._cache.billboardMode = this.billboardMode;
  19301. this._currentRenderId = this.getScene().getRenderId();
  19302. this._childRenderId = this.getScene().getRenderId();
  19303. this._isDirty = false;
  19304. // Scaling
  19305. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19306. // Rotation
  19307. //rotate, if quaternion is set and rotation was used
  19308. if (this.rotationQuaternion) {
  19309. var len = this.rotation.length();
  19310. if (len) {
  19311. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19312. this.rotation.copyFromFloats(0, 0, 0);
  19313. }
  19314. }
  19315. if (this.rotationQuaternion) {
  19316. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19317. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19318. }
  19319. else {
  19320. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19321. this._cache.rotation.copyFrom(this.rotation);
  19322. }
  19323. // Translation
  19324. var camera = this.getScene().activeCamera;
  19325. if (this.infiniteDistance && !this.parent && camera) {
  19326. var cameraWorldMatrix = camera.getWorldMatrix();
  19327. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19328. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19329. }
  19330. else {
  19331. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19332. }
  19333. // Composing transformations
  19334. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19335. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19336. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19337. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19338. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19339. // Need to decompose each rotation here
  19340. var currentPosition = BABYLON.Tmp.Vector3[3];
  19341. if (this.parent && this.parent.getWorldMatrix) {
  19342. if (this._transformToBoneReferal) {
  19343. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19344. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19345. }
  19346. else {
  19347. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19348. }
  19349. }
  19350. else {
  19351. currentPosition.copyFrom(this.position);
  19352. }
  19353. currentPosition.subtractInPlace(camera.globalPosition);
  19354. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19355. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19356. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19357. }
  19358. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19359. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19360. }
  19361. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19362. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19363. }
  19364. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19365. }
  19366. else {
  19367. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19368. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19369. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19370. }
  19371. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19372. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19373. }
  19374. // Post multiply inverse of pivotMatrix
  19375. if (this._postMultiplyPivotMatrix) {
  19376. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19377. }
  19378. // Local world
  19379. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19380. // Parent
  19381. if (this.parent && this.parent.getWorldMatrix) {
  19382. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19383. if (this._transformToBoneReferal) {
  19384. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19385. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19386. }
  19387. else {
  19388. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19389. }
  19390. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19391. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19392. this._worldMatrix.copyFrom(this._localWorld);
  19393. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19394. }
  19395. else {
  19396. if (this._transformToBoneReferal) {
  19397. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19398. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19399. }
  19400. else {
  19401. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19402. }
  19403. }
  19404. this._markSyncedWithParent();
  19405. }
  19406. else {
  19407. this._worldMatrix.copyFrom(this._localWorld);
  19408. }
  19409. // Normal matrix
  19410. if (!this.ignoreNonUniformScaling) {
  19411. if (this.scaling.isNonUniform) {
  19412. this._updateNonUniformScalingState(true);
  19413. }
  19414. else if (this.parent && this.parent._nonUniformScaling) {
  19415. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19416. }
  19417. else {
  19418. this._updateNonUniformScalingState(false);
  19419. }
  19420. }
  19421. else {
  19422. this._updateNonUniformScalingState(false);
  19423. }
  19424. this._afterComputeWorldMatrix();
  19425. // Absolute position
  19426. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19427. // Callbacks
  19428. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19429. if (!this._poseMatrix) {
  19430. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19431. }
  19432. // Cache the determinant
  19433. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19434. return this._worldMatrix;
  19435. };
  19436. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19437. };
  19438. /**
  19439. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19440. * @param func: callback function to add
  19441. *
  19442. * Returns the TransformNode.
  19443. */
  19444. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19445. this.onAfterWorldMatrixUpdateObservable.add(func);
  19446. return this;
  19447. };
  19448. /**
  19449. * Removes a registered callback function.
  19450. * Returns the TransformNode.
  19451. */
  19452. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19453. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19454. return this;
  19455. };
  19456. /**
  19457. * Clone the current transform node
  19458. * Returns the new transform node
  19459. * @param name Name of the new clone
  19460. * @param newParent New parent for the clone
  19461. * @param doNotCloneChildren Do not clone children hierarchy
  19462. */
  19463. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19464. var _this = this;
  19465. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19466. result.name = name;
  19467. result.id = name;
  19468. if (newParent) {
  19469. result.parent = newParent;
  19470. }
  19471. if (!doNotCloneChildren) {
  19472. // Children
  19473. var directDescendants = this.getDescendants(true);
  19474. for (var index = 0; index < directDescendants.length; index++) {
  19475. var child = directDescendants[index];
  19476. if (child.clone) {
  19477. child.clone(name + "." + child.name, result);
  19478. }
  19479. }
  19480. }
  19481. return result;
  19482. };
  19483. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19484. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19485. serializationObject.type = this.getClassName();
  19486. // Parent
  19487. if (this.parent) {
  19488. serializationObject.parentId = this.parent.id;
  19489. }
  19490. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19491. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19492. }
  19493. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19494. serializationObject.isEnabled = this.isEnabled();
  19495. // Parent
  19496. if (this.parent) {
  19497. serializationObject.parentId = this.parent.id;
  19498. }
  19499. return serializationObject;
  19500. };
  19501. // Statics
  19502. /**
  19503. * Returns a new TransformNode object parsed from the source provided.
  19504. * The parameter `parsedMesh` is the source.
  19505. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19506. */
  19507. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19508. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19509. if (BABYLON.Tags) {
  19510. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19511. }
  19512. if (parsedTransformNode.localMatrix) {
  19513. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19514. }
  19515. else if (parsedTransformNode.pivotMatrix) {
  19516. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19517. }
  19518. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19519. // Parent
  19520. if (parsedTransformNode.parentId) {
  19521. transformNode._waitingParentId = parsedTransformNode.parentId;
  19522. }
  19523. return transformNode;
  19524. };
  19525. /**
  19526. * Releases resources associated with this transform node.
  19527. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19528. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19529. */
  19530. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19531. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19532. // Animations
  19533. this.getScene().stopAnimation(this);
  19534. // Remove from scene
  19535. this.getScene().removeTransformNode(this);
  19536. this.onAfterWorldMatrixUpdateObservable.clear();
  19537. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19538. };
  19539. // Statics
  19540. TransformNode.BILLBOARDMODE_NONE = 0;
  19541. TransformNode.BILLBOARDMODE_X = 1;
  19542. TransformNode.BILLBOARDMODE_Y = 2;
  19543. TransformNode.BILLBOARDMODE_Z = 4;
  19544. TransformNode.BILLBOARDMODE_ALL = 7;
  19545. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19546. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19547. __decorate([
  19548. BABYLON.serializeAsVector3()
  19549. ], TransformNode.prototype, "_rotation", void 0);
  19550. __decorate([
  19551. BABYLON.serializeAsQuaternion()
  19552. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19553. __decorate([
  19554. BABYLON.serializeAsVector3()
  19555. ], TransformNode.prototype, "_scaling", void 0);
  19556. __decorate([
  19557. BABYLON.serialize()
  19558. ], TransformNode.prototype, "billboardMode", void 0);
  19559. __decorate([
  19560. BABYLON.serialize()
  19561. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19562. __decorate([
  19563. BABYLON.serialize()
  19564. ], TransformNode.prototype, "infiniteDistance", void 0);
  19565. __decorate([
  19566. BABYLON.serialize()
  19567. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19568. __decorate([
  19569. BABYLON.serializeAsVector3()
  19570. ], TransformNode.prototype, "position", void 0);
  19571. return TransformNode;
  19572. }(BABYLON.Node));
  19573. BABYLON.TransformNode = TransformNode;
  19574. })(BABYLON || (BABYLON = {}));
  19575. //# sourceMappingURL=babylon.transformNode.js.map
  19576. var BABYLON;
  19577. (function (BABYLON) {
  19578. /**
  19579. * Class used to store all common mesh properties
  19580. */
  19581. var AbstractMesh = /** @class */ (function (_super) {
  19582. __extends(AbstractMesh, _super);
  19583. // Constructor
  19584. /**
  19585. * Creates a new AbstractMesh
  19586. * @param name defines the name of the mesh
  19587. * @param scene defines the hosting scene
  19588. */
  19589. function AbstractMesh(name, scene) {
  19590. if (scene === void 0) { scene = null; }
  19591. var _this = _super.call(this, name, scene, false) || this;
  19592. _this._facetNb = 0; // facet number
  19593. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19594. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19595. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19596. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19597. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19598. _this._subDiv = {
  19599. max: 1,
  19600. X: 1,
  19601. Y: 1,
  19602. Z: 1
  19603. };
  19604. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19605. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19606. /** Gets ot sets the culling strategy to use to find visible meshes */
  19607. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19608. // Events
  19609. /**
  19610. * An event triggered when this mesh collides with another one
  19611. */
  19612. _this.onCollideObservable = new BABYLON.Observable();
  19613. /**
  19614. * An event triggered when the collision's position changes
  19615. */
  19616. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19617. /**
  19618. * An event triggered when material is changed
  19619. */
  19620. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19621. // Properties
  19622. /**
  19623. * Gets or sets the orientation for POV movement & rotation
  19624. */
  19625. _this.definedFacingForward = true;
  19626. /**
  19627. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19628. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19629. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19630. * @see http://doc.babylonjs.com/features/occlusionquery
  19631. */
  19632. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19633. /**
  19634. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19635. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19636. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19637. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19638. * @see http://doc.babylonjs.com/features/occlusionquery
  19639. */
  19640. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19641. /**
  19642. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19643. * The default value is -1 which means don't break the query and wait till the result
  19644. * @see http://doc.babylonjs.com/features/occlusionquery
  19645. */
  19646. _this.occlusionRetryCount = -1;
  19647. /** @hidden */
  19648. _this._occlusionInternalRetryCounter = 0;
  19649. /** @hidden */
  19650. _this._isOccluded = false;
  19651. /** @hidden */
  19652. _this._isOcclusionQueryInProgress = false;
  19653. _this._visibility = 1.0;
  19654. /** Gets or sets the alpha index used to sort transparent meshes
  19655. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19656. */
  19657. _this.alphaIndex = Number.MAX_VALUE;
  19658. /**
  19659. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19660. */
  19661. _this.isVisible = true;
  19662. /**
  19663. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19664. */
  19665. _this.isPickable = true;
  19666. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19667. _this.showSubMeshesBoundingBox = false;
  19668. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19669. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19670. */
  19671. _this.isBlocker = false;
  19672. /**
  19673. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19674. */
  19675. _this.enablePointerMoveEvents = false;
  19676. /**
  19677. * Specifies the rendering group id for this mesh (0 by default)
  19678. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19679. */
  19680. _this.renderingGroupId = 0;
  19681. _this._receiveShadows = false;
  19682. /** Defines color to use when rendering outline */
  19683. _this.outlineColor = BABYLON.Color3.Red();
  19684. /** Define width to use when rendering outline */
  19685. _this.outlineWidth = 0.02;
  19686. /** Defines color to use when rendering overlay */
  19687. _this.overlayColor = BABYLON.Color3.Red();
  19688. /** Defines alpha to use when rendering overlay */
  19689. _this.overlayAlpha = 0.5;
  19690. _this._hasVertexAlpha = false;
  19691. _this._useVertexColors = true;
  19692. _this._computeBonesUsingShaders = true;
  19693. _this._numBoneInfluencers = 4;
  19694. _this._applyFog = true;
  19695. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19696. _this.useOctreeForRenderingSelection = true;
  19697. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19698. _this.useOctreeForPicking = true;
  19699. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19700. _this.useOctreeForCollisions = true;
  19701. _this._layerMask = 0x0FFFFFFF;
  19702. /**
  19703. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19704. */
  19705. _this.alwaysSelectAsActiveMesh = false;
  19706. /**
  19707. * Gets or sets the current action manager
  19708. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19709. */
  19710. _this.actionManager = null;
  19711. /**
  19712. * Gets or sets impostor used for physic simulation
  19713. * @see http://doc.babylonjs.com/features/physics_engine
  19714. */
  19715. _this.physicsImpostor = null;
  19716. // Collisions
  19717. _this._checkCollisions = false;
  19718. _this._collisionMask = -1;
  19719. _this._collisionGroup = -1;
  19720. /**
  19721. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19722. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19723. */
  19724. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19725. /**
  19726. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19727. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19728. */
  19729. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19730. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19731. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19732. // Edges
  19733. /**
  19734. * Defines edge width used when edgesRenderer is enabled
  19735. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19736. */
  19737. _this.edgesWidth = 1;
  19738. /**
  19739. * Defines edge color used when edgesRenderer is enabled
  19740. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19741. */
  19742. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19743. // Cache
  19744. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19745. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19746. /** @hidden */
  19747. _this._renderId = 0;
  19748. /** @hidden */
  19749. _this._intersectionsInProgress = new Array();
  19750. /** @hidden */
  19751. _this._unIndexed = false;
  19752. /** @hidden */
  19753. _this._lightSources = new Array();
  19754. /**
  19755. * An event triggered when the mesh is rebuilt.
  19756. */
  19757. _this.onRebuildObservable = new BABYLON.Observable();
  19758. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19759. if (collidedMesh === void 0) { collidedMesh = null; }
  19760. //TODO move this to the collision coordinator!
  19761. if (_this.getScene().workerCollisions)
  19762. newPosition.multiplyInPlace(_this._collider._radius);
  19763. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19764. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19765. _this.position.addInPlace(_this._diffPositionForCollisions);
  19766. }
  19767. if (collidedMesh) {
  19768. _this.onCollideObservable.notifyObservers(collidedMesh);
  19769. }
  19770. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19771. };
  19772. _this.getScene().addMesh(_this);
  19773. _this._resyncLightSources();
  19774. return _this;
  19775. }
  19776. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19777. /**
  19778. * No billboard
  19779. */
  19780. get: function () {
  19781. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19787. /** Billboard on X axis */
  19788. get: function () {
  19789. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19795. /** Billboard on Y axis */
  19796. get: function () {
  19797. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19803. /** Billboard on Z axis */
  19804. get: function () {
  19805. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19806. },
  19807. enumerable: true,
  19808. configurable: true
  19809. });
  19810. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19811. /** Billboard on all axes */
  19812. get: function () {
  19813. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19819. /**
  19820. * Gets the number of facets in the mesh
  19821. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19822. */
  19823. get: function () {
  19824. return this._facetNb;
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19830. /**
  19831. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19832. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19833. */
  19834. get: function () {
  19835. return this._partitioningSubdivisions;
  19836. },
  19837. set: function (nb) {
  19838. this._partitioningSubdivisions = nb;
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19844. /**
  19845. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19846. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19847. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19848. */
  19849. get: function () {
  19850. return this._partitioningBBoxRatio;
  19851. },
  19852. set: function (ratio) {
  19853. this._partitioningBBoxRatio = ratio;
  19854. },
  19855. enumerable: true,
  19856. configurable: true
  19857. });
  19858. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19859. /**
  19860. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19861. * Works only for updatable meshes.
  19862. * Doesn't work with multi-materials
  19863. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19864. */
  19865. get: function () {
  19866. return this._facetDepthSort;
  19867. },
  19868. set: function (sort) {
  19869. this._facetDepthSort = sort;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19875. /**
  19876. * The location (Vector3) where the facet depth sort must be computed from.
  19877. * By default, the active camera position.
  19878. * Used only when facet depth sort is enabled
  19879. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19880. */
  19881. get: function () {
  19882. return this._facetDepthSortFrom;
  19883. },
  19884. set: function (location) {
  19885. this._facetDepthSortFrom = location;
  19886. },
  19887. enumerable: true,
  19888. configurable: true
  19889. });
  19890. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19891. /**
  19892. * gets a boolean indicating if facetData is enabled
  19893. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19894. */
  19895. get: function () {
  19896. return this._facetDataEnabled;
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. /** @hidden */
  19902. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19903. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19904. return false;
  19905. }
  19906. this._markSubMeshesAsMiscDirty();
  19907. return true;
  19908. };
  19909. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19910. /** Set a function to call when this mesh collides with another one */
  19911. set: function (callback) {
  19912. if (this._onCollideObserver) {
  19913. this.onCollideObservable.remove(this._onCollideObserver);
  19914. }
  19915. this._onCollideObserver = this.onCollideObservable.add(callback);
  19916. },
  19917. enumerable: true,
  19918. configurable: true
  19919. });
  19920. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19921. /** Set a function to call when the collision's position changes */
  19922. set: function (callback) {
  19923. if (this._onCollisionPositionChangeObserver) {
  19924. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19925. }
  19926. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19927. },
  19928. enumerable: true,
  19929. configurable: true
  19930. });
  19931. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19932. /**
  19933. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19934. * @see http://doc.babylonjs.com/features/occlusionquery
  19935. */
  19936. get: function () {
  19937. return this._isOccluded;
  19938. },
  19939. set: function (value) {
  19940. this._isOccluded = value;
  19941. },
  19942. enumerable: true,
  19943. configurable: true
  19944. });
  19945. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19946. /**
  19947. * Flag to check the progress status of the query
  19948. * @see http://doc.babylonjs.com/features/occlusionquery
  19949. */
  19950. get: function () {
  19951. return this._isOcclusionQueryInProgress;
  19952. },
  19953. enumerable: true,
  19954. configurable: true
  19955. });
  19956. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19957. /**
  19958. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19959. */
  19960. get: function () {
  19961. return this._visibility;
  19962. },
  19963. /**
  19964. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19965. */
  19966. set: function (value) {
  19967. if (this._visibility === value) {
  19968. return;
  19969. }
  19970. this._visibility = value;
  19971. this._markSubMeshesAsMiscDirty();
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Object.defineProperty(AbstractMesh.prototype, "material", {
  19977. /** Gets or sets current material */
  19978. get: function () {
  19979. return this._material;
  19980. },
  19981. set: function (value) {
  19982. if (this._material === value) {
  19983. return;
  19984. }
  19985. this._material = value;
  19986. if (this.onMaterialChangedObservable.hasObservers) {
  19987. this.onMaterialChangedObservable.notifyObservers(this);
  19988. }
  19989. if (!this.subMeshes) {
  19990. return;
  19991. }
  19992. this._unBindEffect();
  19993. },
  19994. enumerable: true,
  19995. configurable: true
  19996. });
  19997. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19998. /**
  19999. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20000. * @see http://doc.babylonjs.com/babylon101/shadows
  20001. */
  20002. get: function () {
  20003. return this._receiveShadows;
  20004. },
  20005. set: function (value) {
  20006. if (this._receiveShadows === value) {
  20007. return;
  20008. }
  20009. this._receiveShadows = value;
  20010. this._markSubMeshesAsLightDirty();
  20011. },
  20012. enumerable: true,
  20013. configurable: true
  20014. });
  20015. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20016. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20017. get: function () {
  20018. return this._hasVertexAlpha;
  20019. },
  20020. set: function (value) {
  20021. if (this._hasVertexAlpha === value) {
  20022. return;
  20023. }
  20024. this._hasVertexAlpha = value;
  20025. this._markSubMeshesAsAttributesDirty();
  20026. this._markSubMeshesAsMiscDirty();
  20027. },
  20028. enumerable: true,
  20029. configurable: true
  20030. });
  20031. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20032. /** 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) */
  20033. get: function () {
  20034. return this._useVertexColors;
  20035. },
  20036. set: function (value) {
  20037. if (this._useVertexColors === value) {
  20038. return;
  20039. }
  20040. this._useVertexColors = value;
  20041. this._markSubMeshesAsAttributesDirty();
  20042. },
  20043. enumerable: true,
  20044. configurable: true
  20045. });
  20046. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20047. /**
  20048. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20049. */
  20050. get: function () {
  20051. return this._computeBonesUsingShaders;
  20052. },
  20053. set: function (value) {
  20054. if (this._computeBonesUsingShaders === value) {
  20055. return;
  20056. }
  20057. this._computeBonesUsingShaders = value;
  20058. this._markSubMeshesAsAttributesDirty();
  20059. },
  20060. enumerable: true,
  20061. configurable: true
  20062. });
  20063. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20064. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20065. get: function () {
  20066. return this._numBoneInfluencers;
  20067. },
  20068. set: function (value) {
  20069. if (this._numBoneInfluencers === value) {
  20070. return;
  20071. }
  20072. this._numBoneInfluencers = value;
  20073. this._markSubMeshesAsAttributesDirty();
  20074. },
  20075. enumerable: true,
  20076. configurable: true
  20077. });
  20078. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20079. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20080. get: function () {
  20081. return this._applyFog;
  20082. },
  20083. set: function (value) {
  20084. if (this._applyFog === value) {
  20085. return;
  20086. }
  20087. this._applyFog = value;
  20088. this._markSubMeshesAsMiscDirty();
  20089. },
  20090. enumerable: true,
  20091. configurable: true
  20092. });
  20093. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20094. /**
  20095. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20096. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20097. */
  20098. get: function () {
  20099. return this._layerMask;
  20100. },
  20101. set: function (value) {
  20102. if (value === this._layerMask) {
  20103. return;
  20104. }
  20105. this._layerMask = value;
  20106. this._resyncLightSources();
  20107. },
  20108. enumerable: true,
  20109. configurable: true
  20110. });
  20111. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20112. /**
  20113. * Gets or sets a collision mask used to mask collisions (default is -1).
  20114. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20115. */
  20116. get: function () {
  20117. return this._collisionMask;
  20118. },
  20119. set: function (mask) {
  20120. this._collisionMask = !isNaN(mask) ? mask : -1;
  20121. },
  20122. enumerable: true,
  20123. configurable: true
  20124. });
  20125. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20126. /**
  20127. * Gets or sets the current collision group mask (-1 by default).
  20128. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20129. */
  20130. get: function () {
  20131. return this._collisionGroup;
  20132. },
  20133. set: function (mask) {
  20134. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20135. },
  20136. enumerable: true,
  20137. configurable: true
  20138. });
  20139. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20140. /** @hidden */
  20141. get: function () {
  20142. return null;
  20143. },
  20144. enumerable: true,
  20145. configurable: true
  20146. });
  20147. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20148. get: function () {
  20149. return this._skeleton;
  20150. },
  20151. /**
  20152. * Gets or sets a skeleton to apply skining transformations
  20153. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20154. */
  20155. set: function (value) {
  20156. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20157. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20158. }
  20159. if (value && value.needInitialSkinMatrix) {
  20160. value._registerMeshWithPoseMatrix(this);
  20161. }
  20162. this._skeleton = value;
  20163. if (!this._skeleton) {
  20164. this._bonesTransformMatrices = null;
  20165. }
  20166. this._markSubMeshesAsAttributesDirty();
  20167. },
  20168. enumerable: true,
  20169. configurable: true
  20170. });
  20171. /**
  20172. * Returns the string "AbstractMesh"
  20173. * @returns "AbstractMesh"
  20174. */
  20175. AbstractMesh.prototype.getClassName = function () {
  20176. return "AbstractMesh";
  20177. };
  20178. /**
  20179. * Gets a string representation of the current mesh
  20180. * @param fullDetails defines a boolean indicating if full details must be included
  20181. * @returns a string representation of the current mesh
  20182. */
  20183. AbstractMesh.prototype.toString = function (fullDetails) {
  20184. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20185. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20186. if (this._skeleton) {
  20187. ret += ", skeleton: " + this._skeleton.name;
  20188. }
  20189. if (fullDetails) {
  20190. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20191. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20192. }
  20193. return ret;
  20194. };
  20195. /** @hidden */
  20196. AbstractMesh.prototype._rebuild = function () {
  20197. this.onRebuildObservable.notifyObservers(this);
  20198. if (this._occlusionQuery) {
  20199. this._occlusionQuery = null;
  20200. }
  20201. if (!this.subMeshes) {
  20202. return;
  20203. }
  20204. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20205. var subMesh = _a[_i];
  20206. subMesh._rebuild();
  20207. }
  20208. };
  20209. /** @hidden */
  20210. AbstractMesh.prototype._resyncLightSources = function () {
  20211. this._lightSources.length = 0;
  20212. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20213. var light = _a[_i];
  20214. if (!light.isEnabled()) {
  20215. continue;
  20216. }
  20217. if (light.canAffectMesh(this)) {
  20218. this._lightSources.push(light);
  20219. }
  20220. }
  20221. this._markSubMeshesAsLightDirty();
  20222. };
  20223. /** @hidden */
  20224. AbstractMesh.prototype._resyncLighSource = function (light) {
  20225. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20226. var index = this._lightSources.indexOf(light);
  20227. if (index === -1) {
  20228. if (!isIn) {
  20229. return;
  20230. }
  20231. this._lightSources.push(light);
  20232. }
  20233. else {
  20234. if (isIn) {
  20235. return;
  20236. }
  20237. this._lightSources.splice(index, 1);
  20238. }
  20239. this._markSubMeshesAsLightDirty();
  20240. };
  20241. /** @hidden */
  20242. AbstractMesh.prototype._unBindEffect = function () {
  20243. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20244. var subMesh = _a[_i];
  20245. subMesh.setEffect(null);
  20246. }
  20247. };
  20248. /** @hidden */
  20249. AbstractMesh.prototype._removeLightSource = function (light) {
  20250. var index = this._lightSources.indexOf(light);
  20251. if (index === -1) {
  20252. return;
  20253. }
  20254. this._lightSources.splice(index, 1);
  20255. this._markSubMeshesAsLightDirty();
  20256. };
  20257. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20258. if (!this.subMeshes) {
  20259. return;
  20260. }
  20261. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20262. var subMesh = _a[_i];
  20263. if (subMesh._materialDefines) {
  20264. func(subMesh._materialDefines);
  20265. }
  20266. }
  20267. };
  20268. /** @hidden */
  20269. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20270. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20271. };
  20272. /** @hidden */
  20273. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20274. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20275. };
  20276. /** @hidden */
  20277. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20278. if (!this.subMeshes) {
  20279. return;
  20280. }
  20281. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20282. var subMesh = _a[_i];
  20283. var material = subMesh.getMaterial();
  20284. if (material) {
  20285. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20286. }
  20287. }
  20288. };
  20289. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20290. /**
  20291. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20292. */
  20293. get: function () {
  20294. return this._scaling;
  20295. },
  20296. set: function (newScaling) {
  20297. this._scaling = newScaling;
  20298. if (this.physicsImpostor) {
  20299. this.physicsImpostor.forceUpdate();
  20300. }
  20301. },
  20302. enumerable: true,
  20303. configurable: true
  20304. });
  20305. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20306. // Methods
  20307. /**
  20308. * Returns true if the mesh is blocked. Implemented by child classes
  20309. */
  20310. get: function () {
  20311. return false;
  20312. },
  20313. enumerable: true,
  20314. configurable: true
  20315. });
  20316. /**
  20317. * Returns the mesh itself by default. Implemented by child classes
  20318. * @param camera defines the camera to use to pick the right LOD level
  20319. * @returns the currentAbstractMesh
  20320. */
  20321. AbstractMesh.prototype.getLOD = function (camera) {
  20322. return this;
  20323. };
  20324. /**
  20325. * Returns 0 by default. Implemented by child classes
  20326. * @returns an integer
  20327. */
  20328. AbstractMesh.prototype.getTotalVertices = function () {
  20329. return 0;
  20330. };
  20331. /**
  20332. * Returns null by default. Implemented by child classes
  20333. * @returns null
  20334. */
  20335. AbstractMesh.prototype.getIndices = function () {
  20336. return null;
  20337. };
  20338. /**
  20339. * Returns the array of the requested vertex data kind. Implemented by child classes
  20340. * @param kind defines the vertex data kind to use
  20341. * @returns null
  20342. */
  20343. AbstractMesh.prototype.getVerticesData = function (kind) {
  20344. return null;
  20345. };
  20346. /**
  20347. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20348. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20349. * Note that a new underlying VertexBuffer object is created each call.
  20350. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20351. * @param kind defines vertex data kind:
  20352. * * BABYLON.VertexBuffer.PositionKind
  20353. * * BABYLON.VertexBuffer.UVKind
  20354. * * BABYLON.VertexBuffer.UV2Kind
  20355. * * BABYLON.VertexBuffer.UV3Kind
  20356. * * BABYLON.VertexBuffer.UV4Kind
  20357. * * BABYLON.VertexBuffer.UV5Kind
  20358. * * BABYLON.VertexBuffer.UV6Kind
  20359. * * BABYLON.VertexBuffer.ColorKind
  20360. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20361. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20362. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20363. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20364. * @param data defines the data source
  20365. * @param updatable defines if the data must be flagged as updatable (or static)
  20366. * @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
  20367. * @returns the current mesh
  20368. */
  20369. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20370. return this;
  20371. };
  20372. /**
  20373. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20374. * If the mesh has no geometry, it is simply returned as it is.
  20375. * @param kind defines vertex data kind:
  20376. * * BABYLON.VertexBuffer.PositionKind
  20377. * * BABYLON.VertexBuffer.UVKind
  20378. * * BABYLON.VertexBuffer.UV2Kind
  20379. * * BABYLON.VertexBuffer.UV3Kind
  20380. * * BABYLON.VertexBuffer.UV4Kind
  20381. * * BABYLON.VertexBuffer.UV5Kind
  20382. * * BABYLON.VertexBuffer.UV6Kind
  20383. * * BABYLON.VertexBuffer.ColorKind
  20384. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20385. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20386. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20387. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20388. * @param data defines the data source
  20389. * @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
  20390. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20391. * @returns the current mesh
  20392. */
  20393. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20394. return this;
  20395. };
  20396. /**
  20397. * Sets the mesh indices,
  20398. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20399. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20400. * @param totalVertices Defines the total number of vertices
  20401. * @returns the current mesh
  20402. */
  20403. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20404. return this;
  20405. };
  20406. /**
  20407. * Gets a boolean indicating if specific vertex data is present
  20408. * @param kind defines the vertex data kind to use
  20409. * @returns true is data kind is present
  20410. */
  20411. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20412. return false;
  20413. };
  20414. /**
  20415. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20416. * @returns a BoundingInfo
  20417. */
  20418. AbstractMesh.prototype.getBoundingInfo = function () {
  20419. if (this._masterMesh) {
  20420. return this._masterMesh.getBoundingInfo();
  20421. }
  20422. if (!this._boundingInfo) {
  20423. // this._boundingInfo is being created here
  20424. this._updateBoundingInfo();
  20425. }
  20426. // cannot be null.
  20427. return this._boundingInfo;
  20428. };
  20429. /**
  20430. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20431. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20432. * @returns the current mesh
  20433. */
  20434. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20435. if (includeDescendants === void 0) { includeDescendants = true; }
  20436. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20437. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20438. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20439. if (maxDimension === 0) {
  20440. return this;
  20441. }
  20442. var scale = 1 / maxDimension;
  20443. this.scaling.scaleInPlace(scale);
  20444. return this;
  20445. };
  20446. /**
  20447. * Overwrite the current bounding info
  20448. * @param boundingInfo defines the new bounding info
  20449. * @returns the current mesh
  20450. */
  20451. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20452. this._boundingInfo = boundingInfo;
  20453. return this;
  20454. };
  20455. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20456. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20457. get: function () {
  20458. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20459. },
  20460. enumerable: true,
  20461. configurable: true
  20462. });
  20463. /** @hidden */
  20464. AbstractMesh.prototype._preActivate = function () {
  20465. };
  20466. /** @hidden */
  20467. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20468. };
  20469. /** @hidden */
  20470. AbstractMesh.prototype._activate = function (renderId) {
  20471. this._renderId = renderId;
  20472. };
  20473. /**
  20474. * Gets the current world matrix
  20475. * @returns a Matrix
  20476. */
  20477. AbstractMesh.prototype.getWorldMatrix = function () {
  20478. if (this._masterMesh) {
  20479. return this._masterMesh.getWorldMatrix();
  20480. }
  20481. return _super.prototype.getWorldMatrix.call(this);
  20482. };
  20483. /** @hidden */
  20484. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20485. if (this._masterMesh) {
  20486. return this._masterMesh._getWorldMatrixDeterminant();
  20487. }
  20488. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20489. };
  20490. // ================================== Point of View Movement =================================
  20491. /**
  20492. * Perform relative position change from the point of view of behind the front of the mesh.
  20493. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20494. * Supports definition of mesh facing forward or backward
  20495. * @param amountRight defines the distance on the right axis
  20496. * @param amountUp defines the distance on the up axis
  20497. * @param amountForward defines the distance on the forward axis
  20498. * @returns the current mesh
  20499. */
  20500. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20501. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20502. return this;
  20503. };
  20504. /**
  20505. * Calculate relative position change from the point of view of behind the front of the mesh.
  20506. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20507. * Supports definition of mesh facing forward or backward
  20508. * @param amountRight defines the distance on the right axis
  20509. * @param amountUp defines the distance on the up axis
  20510. * @param amountForward defines the distance on the forward axis
  20511. * @returns the new displacement vector
  20512. */
  20513. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20514. var rotMatrix = new BABYLON.Matrix();
  20515. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20516. rotQuaternion.toRotationMatrix(rotMatrix);
  20517. var translationDelta = BABYLON.Vector3.Zero();
  20518. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20519. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20520. return translationDelta;
  20521. };
  20522. // ================================== Point of View Rotation =================================
  20523. /**
  20524. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20525. * Supports definition of mesh facing forward or backward
  20526. * @param flipBack defines the flip
  20527. * @param twirlClockwise defines the twirl
  20528. * @param tiltRight defines the tilt
  20529. * @returns the current mesh
  20530. */
  20531. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20532. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20533. return this;
  20534. };
  20535. /**
  20536. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20537. * Supports definition of mesh facing forward or backward.
  20538. * @param flipBack defines the flip
  20539. * @param twirlClockwise defines the twirl
  20540. * @param tiltRight defines the tilt
  20541. * @returns the new rotation vector
  20542. */
  20543. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20544. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20545. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20546. };
  20547. /**
  20548. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20549. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20550. * @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
  20551. * @returns the new bounding vectors
  20552. */
  20553. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20554. if (includeDescendants === void 0) { includeDescendants = true; }
  20555. if (predicate === void 0) { predicate = null; }
  20556. // Ensures that all world matrix will be recomputed.
  20557. this.getScene().incrementRenderId();
  20558. this.computeWorldMatrix(true);
  20559. var min;
  20560. var max;
  20561. var boundingInfo = this.getBoundingInfo();
  20562. if (!this.subMeshes) {
  20563. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20564. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20565. }
  20566. else {
  20567. min = boundingInfo.boundingBox.minimumWorld;
  20568. max = boundingInfo.boundingBox.maximumWorld;
  20569. }
  20570. if (includeDescendants) {
  20571. var descendants = this.getDescendants(false);
  20572. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20573. var descendant = descendants_1[_i];
  20574. var childMesh = descendant;
  20575. childMesh.computeWorldMatrix(true);
  20576. // Filters meshes based on custom predicate function.
  20577. if (predicate && !predicate(childMesh)) {
  20578. continue;
  20579. }
  20580. //make sure we have the needed params to get mix and max
  20581. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20582. continue;
  20583. }
  20584. var childBoundingInfo = childMesh.getBoundingInfo();
  20585. var boundingBox = childBoundingInfo.boundingBox;
  20586. var minBox = boundingBox.minimumWorld;
  20587. var maxBox = boundingBox.maximumWorld;
  20588. BABYLON.Tools.CheckExtends(minBox, min, max);
  20589. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20590. }
  20591. }
  20592. return {
  20593. min: min,
  20594. max: max
  20595. };
  20596. };
  20597. /** @hidden */
  20598. AbstractMesh.prototype._updateBoundingInfo = function () {
  20599. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20600. this._boundingInfo.update(this.worldMatrixFromCache);
  20601. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20602. return this;
  20603. };
  20604. /** @hidden */
  20605. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20606. if (!this.subMeshes) {
  20607. return this;
  20608. }
  20609. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20610. var subMesh = this.subMeshes[subIndex];
  20611. if (!subMesh.IsGlobal) {
  20612. subMesh.updateBoundingInfo(matrix);
  20613. }
  20614. }
  20615. return this;
  20616. };
  20617. /** @hidden */
  20618. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20619. // Bounding info
  20620. this._updateBoundingInfo();
  20621. };
  20622. /**
  20623. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20624. * A mesh is in the frustum if its bounding box intersects the frustum
  20625. * @param frustumPlanes defines the frustum to test
  20626. * @returns true if the mesh is in the frustum planes
  20627. */
  20628. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20629. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20630. };
  20631. /**
  20632. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20633. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20634. * @param frustumPlanes defines the frustum to test
  20635. * @returns true if the mesh is completely in the frustum planes
  20636. */
  20637. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20638. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20639. };
  20640. /**
  20641. * True if the mesh intersects another mesh or a SolidParticle object
  20642. * @param mesh defines a target mesh or SolidParticle to test
  20643. * @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)
  20644. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20645. * @returns true if there is an intersection
  20646. */
  20647. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20648. if (precise === void 0) { precise = false; }
  20649. if (!this._boundingInfo || !mesh._boundingInfo) {
  20650. return false;
  20651. }
  20652. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20653. return true;
  20654. }
  20655. if (includeDescendants) {
  20656. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20657. var child = _a[_i];
  20658. if (child.intersectsMesh(mesh, precise, true)) {
  20659. return true;
  20660. }
  20661. }
  20662. }
  20663. return false;
  20664. };
  20665. /**
  20666. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20667. * @param point defines the point to test
  20668. * @returns true if there is an intersection
  20669. */
  20670. AbstractMesh.prototype.intersectsPoint = function (point) {
  20671. if (!this._boundingInfo) {
  20672. return false;
  20673. }
  20674. return this._boundingInfo.intersectsPoint(point);
  20675. };
  20676. /**
  20677. * Gets the current physics impostor
  20678. * @see http://doc.babylonjs.com/features/physics_engine
  20679. * @returns a physics impostor or null
  20680. */
  20681. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20682. return this.physicsImpostor;
  20683. };
  20684. /**
  20685. * Gets the position of the current mesh in camera space
  20686. * @param camera defines the camera to use
  20687. * @returns a position
  20688. */
  20689. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20690. if (camera === void 0) { camera = null; }
  20691. if (!camera) {
  20692. camera = this.getScene().activeCamera;
  20693. }
  20694. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20695. };
  20696. /**
  20697. * Returns the distance from the mesh to the active camera
  20698. * @param camera defines the camera to use
  20699. * @returns the distance
  20700. */
  20701. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20702. if (camera === void 0) { camera = null; }
  20703. if (!camera) {
  20704. camera = this.getScene().activeCamera;
  20705. }
  20706. return this.absolutePosition.subtract(camera.position).length();
  20707. };
  20708. /**
  20709. * Apply a physic impulse to the mesh
  20710. * @param force defines the force to apply
  20711. * @param contactPoint defines where to apply the force
  20712. * @returns the current mesh
  20713. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20714. */
  20715. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20716. if (!this.physicsImpostor) {
  20717. return this;
  20718. }
  20719. this.physicsImpostor.applyImpulse(force, contactPoint);
  20720. return this;
  20721. };
  20722. /**
  20723. * Creates a physic joint between two meshes
  20724. * @param otherMesh defines the other mesh to use
  20725. * @param pivot1 defines the pivot to use on this mesh
  20726. * @param pivot2 defines the pivot to use on the other mesh
  20727. * @param options defines additional options (can be plugin dependent)
  20728. * @returns the current mesh
  20729. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20730. */
  20731. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20732. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20733. return this;
  20734. }
  20735. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20736. mainPivot: pivot1,
  20737. connectedPivot: pivot2,
  20738. nativeParams: options
  20739. });
  20740. return this;
  20741. };
  20742. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20743. // Collisions
  20744. /**
  20745. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20746. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20747. */
  20748. get: function () {
  20749. return this._checkCollisions;
  20750. },
  20751. set: function (collisionEnabled) {
  20752. this._checkCollisions = collisionEnabled;
  20753. if (this.getScene().workerCollisions) {
  20754. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20755. }
  20756. },
  20757. enumerable: true,
  20758. configurable: true
  20759. });
  20760. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20761. /**
  20762. * Gets Collider object used to compute collisions (not physics)
  20763. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20764. */
  20765. get: function () {
  20766. return this._collider;
  20767. },
  20768. enumerable: true,
  20769. configurable: true
  20770. });
  20771. /**
  20772. * Move the mesh using collision engine
  20773. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20774. * @param displacement defines the requested displacement vector
  20775. * @returns the current mesh
  20776. */
  20777. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20778. var globalPosition = this.getAbsolutePosition();
  20779. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20780. if (!this._collider) {
  20781. this._collider = new BABYLON.Collider();
  20782. }
  20783. this._collider._radius = this.ellipsoid;
  20784. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20785. return this;
  20786. };
  20787. // Collisions
  20788. /** @hidden */
  20789. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20790. this._generatePointsArray();
  20791. if (!this._positions) {
  20792. return this;
  20793. }
  20794. // Transformation
  20795. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20796. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20797. subMesh._lastColliderWorldVertices = [];
  20798. subMesh._trianglePlanes = [];
  20799. var start = subMesh.verticesStart;
  20800. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20801. for (var i = start; i < end; i++) {
  20802. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20803. }
  20804. }
  20805. // Collide
  20806. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20807. if (collider.collisionFound) {
  20808. collider.collidedMesh = this;
  20809. }
  20810. return this;
  20811. };
  20812. /** @hidden */
  20813. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20814. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20815. var len = subMeshes.length;
  20816. for (var index = 0; index < len; index++) {
  20817. var subMesh = subMeshes.data[index];
  20818. // Bounding test
  20819. if (len > 1 && !subMesh._checkCollision(collider))
  20820. continue;
  20821. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20822. }
  20823. return this;
  20824. };
  20825. /** @hidden */
  20826. AbstractMesh.prototype._checkCollision = function (collider) {
  20827. // Bounding box test
  20828. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20829. return this;
  20830. // Transformation matrix
  20831. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20832. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20833. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20834. return this;
  20835. };
  20836. // Picking
  20837. /** @hidden */
  20838. AbstractMesh.prototype._generatePointsArray = function () {
  20839. return false;
  20840. };
  20841. /**
  20842. * Checks if the passed Ray intersects with the mesh
  20843. * @param ray defines the ray to use
  20844. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20845. * @returns the picking info
  20846. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20847. */
  20848. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20849. var pickingInfo = new BABYLON.PickingInfo();
  20850. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20851. return pickingInfo;
  20852. }
  20853. if (!this._generatePointsArray()) {
  20854. return pickingInfo;
  20855. }
  20856. var intersectInfo = null;
  20857. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20858. var len = subMeshes.length;
  20859. for (var index = 0; index < len; index++) {
  20860. var subMesh = subMeshes.data[index];
  20861. // Bounding test
  20862. if (len > 1 && !subMesh.canIntersects(ray))
  20863. continue;
  20864. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20865. if (currentIntersectInfo) {
  20866. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20867. intersectInfo = currentIntersectInfo;
  20868. intersectInfo.subMeshId = index;
  20869. if (fastCheck) {
  20870. break;
  20871. }
  20872. }
  20873. }
  20874. }
  20875. if (intersectInfo) {
  20876. // Get picked point
  20877. var world = this.getWorldMatrix();
  20878. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20879. var direction = ray.direction.clone();
  20880. direction = direction.scale(intersectInfo.distance);
  20881. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20882. var pickedPoint = worldOrigin.add(worldDirection);
  20883. // Return result
  20884. pickingInfo.hit = true;
  20885. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20886. pickingInfo.pickedPoint = pickedPoint;
  20887. pickingInfo.pickedMesh = this;
  20888. pickingInfo.bu = intersectInfo.bu || 0;
  20889. pickingInfo.bv = intersectInfo.bv || 0;
  20890. pickingInfo.faceId = intersectInfo.faceId;
  20891. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20892. return pickingInfo;
  20893. }
  20894. return pickingInfo;
  20895. };
  20896. /**
  20897. * Clones the current mesh
  20898. * @param name defines the mesh name
  20899. * @param newParent defines the new mesh parent
  20900. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20901. * @returns the new mesh
  20902. */
  20903. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20904. return null;
  20905. };
  20906. /**
  20907. * Disposes all the submeshes of the current meshnp
  20908. * @returns the current mesh
  20909. */
  20910. AbstractMesh.prototype.releaseSubMeshes = function () {
  20911. if (this.subMeshes) {
  20912. while (this.subMeshes.length) {
  20913. this.subMeshes[0].dispose();
  20914. }
  20915. }
  20916. else {
  20917. this.subMeshes = new Array();
  20918. }
  20919. return this;
  20920. };
  20921. /**
  20922. * Releases resources associated with this abstract mesh.
  20923. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20924. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20925. */
  20926. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20927. var _this = this;
  20928. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20929. var index;
  20930. // Smart Array Retainers.
  20931. this.getScene().freeActiveMeshes();
  20932. this.getScene().freeRenderingGroups();
  20933. // Action manager
  20934. if (this.actionManager !== undefined && this.actionManager !== null) {
  20935. this.actionManager.dispose();
  20936. this.actionManager = null;
  20937. }
  20938. // Skeleton
  20939. this._skeleton = null;
  20940. // Physics
  20941. if (this.physicsImpostor) {
  20942. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20943. }
  20944. // Intersections in progress
  20945. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20946. var other = this._intersectionsInProgress[index];
  20947. var pos = other._intersectionsInProgress.indexOf(this);
  20948. other._intersectionsInProgress.splice(pos, 1);
  20949. }
  20950. this._intersectionsInProgress = [];
  20951. // Lights
  20952. var lights = this.getScene().lights;
  20953. lights.forEach(function (light) {
  20954. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20955. if (meshIndex !== -1) {
  20956. light.includedOnlyMeshes.splice(meshIndex, 1);
  20957. }
  20958. meshIndex = light.excludedMeshes.indexOf(_this);
  20959. if (meshIndex !== -1) {
  20960. light.excludedMeshes.splice(meshIndex, 1);
  20961. }
  20962. // Shadow generators
  20963. var generator = light.getShadowGenerator();
  20964. if (generator) {
  20965. var shadowMap = generator.getShadowMap();
  20966. if (shadowMap && shadowMap.renderList) {
  20967. meshIndex = shadowMap.renderList.indexOf(_this);
  20968. if (meshIndex !== -1) {
  20969. shadowMap.renderList.splice(meshIndex, 1);
  20970. }
  20971. }
  20972. }
  20973. });
  20974. // SubMeshes
  20975. if (this.getClassName() !== "InstancedMesh") {
  20976. this.releaseSubMeshes();
  20977. }
  20978. // Query
  20979. var engine = this.getScene().getEngine();
  20980. if (this._occlusionQuery) {
  20981. this._isOcclusionQueryInProgress = false;
  20982. engine.deleteQuery(this._occlusionQuery);
  20983. this._occlusionQuery = null;
  20984. }
  20985. // Engine
  20986. engine.wipeCaches();
  20987. // Remove from scene
  20988. this.getScene().removeMesh(this);
  20989. if (disposeMaterialAndTextures) {
  20990. if (this.material) {
  20991. this.material.dispose(false, true);
  20992. }
  20993. }
  20994. if (!doNotRecurse) {
  20995. // Particles
  20996. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20997. if (this.getScene().particleSystems[index].emitter === this) {
  20998. this.getScene().particleSystems[index].dispose();
  20999. index--;
  21000. }
  21001. }
  21002. }
  21003. // facet data
  21004. if (this._facetDataEnabled) {
  21005. this.disableFacetData();
  21006. }
  21007. this.onAfterWorldMatrixUpdateObservable.clear();
  21008. this.onCollideObservable.clear();
  21009. this.onCollisionPositionChangeObservable.clear();
  21010. this.onRebuildObservable.clear();
  21011. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21012. };
  21013. /**
  21014. * Adds the passed mesh as a child to the current mesh
  21015. * @param mesh defines the child mesh
  21016. * @returns the current mesh
  21017. */
  21018. AbstractMesh.prototype.addChild = function (mesh) {
  21019. mesh.setParent(this);
  21020. return this;
  21021. };
  21022. /**
  21023. * Removes the passed mesh from the current mesh children list
  21024. * @param mesh defines the child mesh
  21025. * @returns the current mesh
  21026. */
  21027. AbstractMesh.prototype.removeChild = function (mesh) {
  21028. mesh.setParent(null);
  21029. return this;
  21030. };
  21031. // Facet data
  21032. /** @hidden */
  21033. AbstractMesh.prototype._initFacetData = function () {
  21034. if (!this._facetNormals) {
  21035. this._facetNormals = new Array();
  21036. }
  21037. if (!this._facetPositions) {
  21038. this._facetPositions = new Array();
  21039. }
  21040. if (!this._facetPartitioning) {
  21041. this._facetPartitioning = new Array();
  21042. }
  21043. this._facetNb = (this.getIndices().length / 3) | 0;
  21044. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21045. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21046. for (var f = 0; f < this._facetNb; f++) {
  21047. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21048. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21049. }
  21050. this._facetDataEnabled = true;
  21051. return this;
  21052. };
  21053. /**
  21054. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21055. * This method can be called within the render loop.
  21056. * 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
  21057. * @returns the current mesh
  21058. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21059. */
  21060. AbstractMesh.prototype.updateFacetData = function () {
  21061. if (!this._facetDataEnabled) {
  21062. this._initFacetData();
  21063. }
  21064. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21065. var indices = this.getIndices();
  21066. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21067. var bInfo = this.getBoundingInfo();
  21068. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21069. // init arrays, matrix and sort function on first call
  21070. this._facetDepthSortEnabled = true;
  21071. if (indices instanceof Uint16Array) {
  21072. this._depthSortedIndices = new Uint16Array(indices);
  21073. }
  21074. else if (indices instanceof Uint32Array) {
  21075. this._depthSortedIndices = new Uint32Array(indices);
  21076. }
  21077. else {
  21078. var needs32bits = false;
  21079. for (var i = 0; i < indices.length; i++) {
  21080. if (indices[i] > 65535) {
  21081. needs32bits = true;
  21082. break;
  21083. }
  21084. }
  21085. if (needs32bits) {
  21086. this._depthSortedIndices = new Uint32Array(indices);
  21087. }
  21088. else {
  21089. this._depthSortedIndices = new Uint16Array(indices);
  21090. }
  21091. }
  21092. this._facetDepthSortFunction = function (f1, f2) {
  21093. return (f2.sqDistance - f1.sqDistance);
  21094. };
  21095. if (!this._facetDepthSortFrom) {
  21096. var camera = this.getScene().activeCamera;
  21097. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21098. }
  21099. this._depthSortedFacets = [];
  21100. for (var f = 0; f < this._facetNb; f++) {
  21101. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21102. this._depthSortedFacets.push(depthSortedFacet);
  21103. }
  21104. this._invertedMatrix = BABYLON.Matrix.Identity();
  21105. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21106. }
  21107. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21108. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21109. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21110. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21111. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21112. this._subDiv.max = this._partitioningSubdivisions;
  21113. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21114. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21115. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21116. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21117. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21118. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21119. // set the parameters for ComputeNormals()
  21120. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21121. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21122. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21123. this._facetParameters.bInfo = bInfo;
  21124. this._facetParameters.bbSize = this._bbSize;
  21125. this._facetParameters.subDiv = this._subDiv;
  21126. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21127. this._facetParameters.depthSort = this._facetDepthSort;
  21128. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21129. this.computeWorldMatrix(true);
  21130. this._worldMatrix.invertToRef(this._invertedMatrix);
  21131. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21132. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21133. }
  21134. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21135. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21136. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21137. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21138. var l = (this._depthSortedIndices.length / 3) | 0;
  21139. for (var f = 0; f < l; f++) {
  21140. var sind = this._depthSortedFacets[f].ind;
  21141. this._depthSortedIndices[f * 3] = indices[sind];
  21142. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21143. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21144. }
  21145. this.updateIndices(this._depthSortedIndices);
  21146. }
  21147. return this;
  21148. };
  21149. /**
  21150. * Returns the facetLocalNormals array.
  21151. * The normals are expressed in the mesh local spac
  21152. * @returns an array of Vector3
  21153. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21154. */
  21155. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21156. if (!this._facetNormals) {
  21157. this.updateFacetData();
  21158. }
  21159. return this._facetNormals;
  21160. };
  21161. /**
  21162. * Returns the facetLocalPositions array.
  21163. * The facet positions are expressed in the mesh local space
  21164. * @returns an array of Vector3
  21165. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21166. */
  21167. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21168. if (!this._facetPositions) {
  21169. this.updateFacetData();
  21170. }
  21171. return this._facetPositions;
  21172. };
  21173. /**
  21174. * Returns the facetLocalPartioning array
  21175. * @returns an array of array of numbers
  21176. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21177. */
  21178. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21179. if (!this._facetPartitioning) {
  21180. this.updateFacetData();
  21181. }
  21182. return this._facetPartitioning;
  21183. };
  21184. /**
  21185. * Returns the i-th facet position in the world system.
  21186. * This method allocates a new Vector3 per call
  21187. * @param i defines the facet index
  21188. * @returns a new Vector3
  21189. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21190. */
  21191. AbstractMesh.prototype.getFacetPosition = function (i) {
  21192. var pos = BABYLON.Vector3.Zero();
  21193. this.getFacetPositionToRef(i, pos);
  21194. return pos;
  21195. };
  21196. /**
  21197. * Sets the reference Vector3 with the i-th facet position in the world system
  21198. * @param i defines the facet index
  21199. * @param ref defines the target vector
  21200. * @returns the current mesh
  21201. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21202. */
  21203. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21204. var localPos = (this.getFacetLocalPositions())[i];
  21205. var world = this.getWorldMatrix();
  21206. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21207. return this;
  21208. };
  21209. /**
  21210. * Returns the i-th facet normal in the world system.
  21211. * This method allocates a new Vector3 per call
  21212. * @param i defines the facet index
  21213. * @returns a new Vector3
  21214. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21215. */
  21216. AbstractMesh.prototype.getFacetNormal = function (i) {
  21217. var norm = BABYLON.Vector3.Zero();
  21218. this.getFacetNormalToRef(i, norm);
  21219. return norm;
  21220. };
  21221. /**
  21222. * Sets the reference Vector3 with the i-th facet normal in the world system
  21223. * @param i defines the facet index
  21224. * @param ref defines the target vector
  21225. * @returns the current mesh
  21226. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21227. */
  21228. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21229. var localNorm = (this.getFacetLocalNormals())[i];
  21230. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21231. return this;
  21232. };
  21233. /**
  21234. * 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)
  21235. * @param x defines x coordinate
  21236. * @param y defines y coordinate
  21237. * @param z defines z coordinate
  21238. * @returns the array of facet indexes
  21239. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21240. */
  21241. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21242. var bInfo = this.getBoundingInfo();
  21243. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21244. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21245. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21246. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21247. return null;
  21248. }
  21249. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21250. };
  21251. /**
  21252. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21253. * @param projected sets as the (x,y,z) world projection on the facet
  21254. * @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
  21255. * @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
  21256. * @param x defines x coordinate
  21257. * @param y defines y coordinate
  21258. * @param z defines z coordinate
  21259. * @returns the face index if found (or null instead)
  21260. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21261. */
  21262. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21263. if (checkFace === void 0) { checkFace = false; }
  21264. if (facing === void 0) { facing = true; }
  21265. var world = this.getWorldMatrix();
  21266. var invMat = BABYLON.Tmp.Matrix[5];
  21267. world.invertToRef(invMat);
  21268. var invVect = BABYLON.Tmp.Vector3[8];
  21269. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21270. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21271. if (projected) {
  21272. // tranform the local computed projected vector to world coordinates
  21273. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21274. }
  21275. return closest;
  21276. };
  21277. /**
  21278. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21279. * @param projected sets as the (x,y,z) local projection on the facet
  21280. * @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
  21281. * @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
  21282. * @param x defines x coordinate
  21283. * @param y defines y coordinate
  21284. * @param z defines z coordinate
  21285. * @returns the face index if found (or null instead)
  21286. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21287. */
  21288. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21289. if (checkFace === void 0) { checkFace = false; }
  21290. if (facing === void 0) { facing = true; }
  21291. var closest = null;
  21292. var tmpx = 0.0;
  21293. var tmpy = 0.0;
  21294. var tmpz = 0.0;
  21295. var d = 0.0; // tmp dot facet normal * facet position
  21296. var t0 = 0.0;
  21297. var projx = 0.0;
  21298. var projy = 0.0;
  21299. var projz = 0.0;
  21300. // Get all the facets in the same partitioning block than (x, y, z)
  21301. var facetPositions = this.getFacetLocalPositions();
  21302. var facetNormals = this.getFacetLocalNormals();
  21303. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21304. if (!facetsInBlock) {
  21305. return null;
  21306. }
  21307. // Get the closest facet to (x, y, z)
  21308. var shortest = Number.MAX_VALUE; // init distance vars
  21309. var tmpDistance = shortest;
  21310. var fib; // current facet in the block
  21311. var norm; // current facet normal
  21312. var p0; // current facet barycenter position
  21313. // loop on all the facets in the current partitioning block
  21314. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21315. fib = facetsInBlock[idx];
  21316. norm = facetNormals[fib];
  21317. p0 = facetPositions[fib];
  21318. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21319. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21320. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21321. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21322. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21323. projx = x + norm.x * t0;
  21324. projy = y + norm.y * t0;
  21325. projz = z + norm.z * t0;
  21326. tmpx = projx - x;
  21327. tmpy = projy - y;
  21328. tmpz = projz - z;
  21329. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21330. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21331. shortest = tmpDistance;
  21332. closest = fib;
  21333. if (projected) {
  21334. projected.x = projx;
  21335. projected.y = projy;
  21336. projected.z = projz;
  21337. }
  21338. }
  21339. }
  21340. }
  21341. return closest;
  21342. };
  21343. /**
  21344. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21345. * @returns the parameters
  21346. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21347. */
  21348. AbstractMesh.prototype.getFacetDataParameters = function () {
  21349. return this._facetParameters;
  21350. };
  21351. /**
  21352. * Disables the feature FacetData and frees the related memory
  21353. * @returns the current mesh
  21354. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21355. */
  21356. AbstractMesh.prototype.disableFacetData = function () {
  21357. if (this._facetDataEnabled) {
  21358. this._facetDataEnabled = false;
  21359. this._facetPositions = new Array();
  21360. this._facetNormals = new Array();
  21361. this._facetPartitioning = new Array();
  21362. this._facetParameters = null;
  21363. this._depthSortedIndices = new Uint32Array(0);
  21364. }
  21365. return this;
  21366. };
  21367. /**
  21368. * Updates the AbstractMesh indices array
  21369. * @param indices defines the data source
  21370. * @returns the current mesh
  21371. */
  21372. AbstractMesh.prototype.updateIndices = function (indices) {
  21373. return this;
  21374. };
  21375. /**
  21376. * Creates new normals data for the mesh
  21377. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21378. * @returns the current mesh
  21379. */
  21380. AbstractMesh.prototype.createNormals = function (updatable) {
  21381. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21382. var indices = this.getIndices();
  21383. var normals;
  21384. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21385. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21386. }
  21387. else {
  21388. normals = [];
  21389. }
  21390. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21391. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21392. return this;
  21393. };
  21394. /**
  21395. * Align the mesh with a normal
  21396. * @param normal defines the normal to use
  21397. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21398. * @returns the current mesh
  21399. */
  21400. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21401. if (!upDirection) {
  21402. upDirection = BABYLON.Axis.Y;
  21403. }
  21404. var axisX = BABYLON.Tmp.Vector3[0];
  21405. var axisZ = BABYLON.Tmp.Vector3[1];
  21406. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21407. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21408. if (this.rotationQuaternion) {
  21409. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21410. }
  21411. else {
  21412. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21413. }
  21414. return this;
  21415. };
  21416. /** @hidden */
  21417. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21418. this._isOccluded = false;
  21419. };
  21420. /** No occlusion */
  21421. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21422. /** Occlusion set to optimisitic */
  21423. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21424. /** Occlusion set to strict */
  21425. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21426. /** Use an accurante occlusion algorithm */
  21427. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21428. /** Use a conservative occlusion algorithm */
  21429. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21430. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21431. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21432. /** Culling strategy with bounding sphere only and then frustum culling */
  21433. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21434. return AbstractMesh;
  21435. }(BABYLON.TransformNode));
  21436. BABYLON.AbstractMesh = AbstractMesh;
  21437. })(BABYLON || (BABYLON = {}));
  21438. //# sourceMappingURL=babylon.abstractMesh.js.map
  21439. var BABYLON;
  21440. (function (BABYLON) {
  21441. /**
  21442. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21443. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21444. * 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.
  21445. */
  21446. var Light = /** @class */ (function (_super) {
  21447. __extends(Light, _super);
  21448. /**
  21449. * Creates a Light object in the scene.
  21450. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21451. * @param name The firendly name of the light
  21452. * @param scene The scene the light belongs too
  21453. */
  21454. function Light(name, scene) {
  21455. var _this = _super.call(this, name, scene) || this;
  21456. /**
  21457. * Diffuse gives the basic color to an object.
  21458. */
  21459. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21460. /**
  21461. * Specular produces a highlight color on an object.
  21462. * Note: This is note affecting PBR materials.
  21463. */
  21464. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21465. /**
  21466. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21467. * falling off base on range or angle.
  21468. * This can be set to any values in Light.FALLOFF_x.
  21469. *
  21470. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21471. * other types of materials.
  21472. */
  21473. _this.falloffType = Light.FALLOFF_DEFAULT;
  21474. /**
  21475. * Strength of the light.
  21476. * Note: By default it is define in the framework own unit.
  21477. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21478. */
  21479. _this.intensity = 1.0;
  21480. _this._range = Number.MAX_VALUE;
  21481. _this._inverseSquaredRange = 0;
  21482. /**
  21483. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21484. * of light.
  21485. */
  21486. _this._photometricScale = 1.0;
  21487. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21488. _this._radius = 0.00001;
  21489. /**
  21490. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21491. * exceeding the number allowed of the materials.
  21492. */
  21493. _this.renderPriority = 0;
  21494. _this._shadowEnabled = true;
  21495. _this._excludeWithLayerMask = 0;
  21496. _this._includeOnlyWithLayerMask = 0;
  21497. _this._lightmapMode = 0;
  21498. /**
  21499. * @hidden Internal use only.
  21500. */
  21501. _this._excludedMeshesIds = new Array();
  21502. /**
  21503. * @hidden Internal use only.
  21504. */
  21505. _this._includedOnlyMeshesIds = new Array();
  21506. _this.getScene().addLight(_this);
  21507. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21508. _this._buildUniformLayout();
  21509. _this.includedOnlyMeshes = new Array();
  21510. _this.excludedMeshes = new Array();
  21511. _this._resyncMeshes();
  21512. return _this;
  21513. }
  21514. Object.defineProperty(Light.prototype, "range", {
  21515. /**
  21516. * Defines how far from the source the light is impacting in scene units.
  21517. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21518. */
  21519. get: function () {
  21520. return this._range;
  21521. },
  21522. /**
  21523. * Defines how far from the source the light is impacting in scene units.
  21524. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21525. */
  21526. set: function (value) {
  21527. this._range = value;
  21528. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21529. },
  21530. enumerable: true,
  21531. configurable: true
  21532. });
  21533. Object.defineProperty(Light.prototype, "intensityMode", {
  21534. /**
  21535. * Gets the photometric scale used to interpret the intensity.
  21536. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21537. */
  21538. get: function () {
  21539. return this._intensityMode;
  21540. },
  21541. /**
  21542. * Sets the photometric scale used to interpret the intensity.
  21543. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21544. */
  21545. set: function (value) {
  21546. this._intensityMode = value;
  21547. this._computePhotometricScale();
  21548. },
  21549. enumerable: true,
  21550. configurable: true
  21551. });
  21552. ;
  21553. ;
  21554. Object.defineProperty(Light.prototype, "radius", {
  21555. /**
  21556. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21557. */
  21558. get: function () {
  21559. return this._radius;
  21560. },
  21561. /**
  21562. * sets the light radius used by PBR Materials to simulate soft area lights.
  21563. */
  21564. set: function (value) {
  21565. this._radius = value;
  21566. this._computePhotometricScale();
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. ;
  21572. ;
  21573. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21574. /**
  21575. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21576. * the current shadow generator.
  21577. */
  21578. get: function () {
  21579. return this._shadowEnabled;
  21580. },
  21581. /**
  21582. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21583. * the current shadow generator.
  21584. */
  21585. set: function (value) {
  21586. if (this._shadowEnabled === value) {
  21587. return;
  21588. }
  21589. this._shadowEnabled = value;
  21590. this._markMeshesAsLightDirty();
  21591. },
  21592. enumerable: true,
  21593. configurable: true
  21594. });
  21595. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21596. /**
  21597. * Gets the only meshes impacted by this light.
  21598. */
  21599. get: function () {
  21600. return this._includedOnlyMeshes;
  21601. },
  21602. /**
  21603. * Sets the only meshes impacted by this light.
  21604. */
  21605. set: function (value) {
  21606. this._includedOnlyMeshes = value;
  21607. this._hookArrayForIncludedOnly(value);
  21608. },
  21609. enumerable: true,
  21610. configurable: true
  21611. });
  21612. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21613. /**
  21614. * Gets the meshes not impacted by this light.
  21615. */
  21616. get: function () {
  21617. return this._excludedMeshes;
  21618. },
  21619. /**
  21620. * Sets the meshes not impacted by this light.
  21621. */
  21622. set: function (value) {
  21623. this._excludedMeshes = value;
  21624. this._hookArrayForExcluded(value);
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21630. /**
  21631. * Gets the layer id use to find what meshes are not impacted by the light.
  21632. * Inactive if 0
  21633. */
  21634. get: function () {
  21635. return this._excludeWithLayerMask;
  21636. },
  21637. /**
  21638. * Sets the layer id use to find what meshes are not impacted by the light.
  21639. * Inactive if 0
  21640. */
  21641. set: function (value) {
  21642. this._excludeWithLayerMask = value;
  21643. this._resyncMeshes();
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21649. /**
  21650. * Gets the layer id use to find what meshes are impacted by the light.
  21651. * Inactive if 0
  21652. */
  21653. get: function () {
  21654. return this._includeOnlyWithLayerMask;
  21655. },
  21656. /**
  21657. * Sets the layer id use to find what meshes are impacted by the light.
  21658. * Inactive if 0
  21659. */
  21660. set: function (value) {
  21661. this._includeOnlyWithLayerMask = value;
  21662. this._resyncMeshes();
  21663. },
  21664. enumerable: true,
  21665. configurable: true
  21666. });
  21667. Object.defineProperty(Light.prototype, "lightmapMode", {
  21668. /**
  21669. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21670. */
  21671. get: function () {
  21672. return this._lightmapMode;
  21673. },
  21674. /**
  21675. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21676. */
  21677. set: function (value) {
  21678. if (this._lightmapMode === value) {
  21679. return;
  21680. }
  21681. this._lightmapMode = value;
  21682. this._markMeshesAsLightDirty();
  21683. },
  21684. enumerable: true,
  21685. configurable: true
  21686. });
  21687. /**
  21688. * Returns the string "Light".
  21689. * @returns the class name
  21690. */
  21691. Light.prototype.getClassName = function () {
  21692. return "Light";
  21693. };
  21694. /**
  21695. * Converts the light information to a readable string for debug purpose.
  21696. * @param fullDetails Supports for multiple levels of logging within scene loading
  21697. * @returns the human readable light info
  21698. */
  21699. Light.prototype.toString = function (fullDetails) {
  21700. var ret = "Name: " + this.name;
  21701. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21702. if (this.animations) {
  21703. for (var i = 0; i < this.animations.length; i++) {
  21704. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21705. }
  21706. }
  21707. if (fullDetails) {
  21708. }
  21709. return ret;
  21710. };
  21711. /**
  21712. * Set the enabled state of this node.
  21713. * @param value - the new enabled state
  21714. */
  21715. Light.prototype.setEnabled = function (value) {
  21716. _super.prototype.setEnabled.call(this, value);
  21717. this._resyncMeshes();
  21718. };
  21719. /**
  21720. * Returns the Light associated shadow generator if any.
  21721. * @return the associated shadow generator.
  21722. */
  21723. Light.prototype.getShadowGenerator = function () {
  21724. return this._shadowGenerator;
  21725. };
  21726. /**
  21727. * Returns a Vector3, the absolute light position in the World.
  21728. * @returns the world space position of the light
  21729. */
  21730. Light.prototype.getAbsolutePosition = function () {
  21731. return BABYLON.Vector3.Zero();
  21732. };
  21733. /**
  21734. * Specifies if the light will affect the passed mesh.
  21735. * @param mesh The mesh to test against the light
  21736. * @return true the mesh is affected otherwise, false.
  21737. */
  21738. Light.prototype.canAffectMesh = function (mesh) {
  21739. if (!mesh) {
  21740. return true;
  21741. }
  21742. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21743. return false;
  21744. }
  21745. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21746. return false;
  21747. }
  21748. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21749. return false;
  21750. }
  21751. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21752. return false;
  21753. }
  21754. return true;
  21755. };
  21756. /**
  21757. * Computes and Returns the light World matrix.
  21758. * @returns the world matrix
  21759. */
  21760. Light.prototype.getWorldMatrix = function () {
  21761. this._currentRenderId = this.getScene().getRenderId();
  21762. this._childRenderId = this._currentRenderId;
  21763. var worldMatrix = this._getWorldMatrix();
  21764. if (this.parent && this.parent.getWorldMatrix) {
  21765. if (!this._parentedWorldMatrix) {
  21766. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21767. }
  21768. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21769. this._markSyncedWithParent();
  21770. return this._parentedWorldMatrix;
  21771. }
  21772. return worldMatrix;
  21773. };
  21774. /**
  21775. * Sort function to order lights for rendering.
  21776. * @param a First Light object to compare to second.
  21777. * @param b Second Light object to compare first.
  21778. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21779. */
  21780. Light.CompareLightsPriority = function (a, b) {
  21781. //shadow-casting lights have priority over non-shadow-casting lights
  21782. //the renderPrioirty is a secondary sort criterion
  21783. if (a.shadowEnabled !== b.shadowEnabled) {
  21784. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21785. }
  21786. return b.renderPriority - a.renderPriority;
  21787. };
  21788. /**
  21789. * Releases resources associated with this node.
  21790. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21791. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21792. */
  21793. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21794. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21795. if (this._shadowGenerator) {
  21796. this._shadowGenerator.dispose();
  21797. this._shadowGenerator = null;
  21798. }
  21799. // Animations
  21800. this.getScene().stopAnimation(this);
  21801. // Remove from meshes
  21802. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21803. var mesh = _a[_i];
  21804. mesh._removeLightSource(this);
  21805. }
  21806. this._uniformBuffer.dispose();
  21807. // Remove from scene
  21808. this.getScene().removeLight(this);
  21809. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21810. };
  21811. /**
  21812. * Returns the light type ID (integer).
  21813. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21814. */
  21815. Light.prototype.getTypeID = function () {
  21816. return 0;
  21817. };
  21818. /**
  21819. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21820. * @returns the scaled intensity in intensity mode unit
  21821. */
  21822. Light.prototype.getScaledIntensity = function () {
  21823. return this._photometricScale * this.intensity;
  21824. };
  21825. /**
  21826. * Returns a new Light object, named "name", from the current one.
  21827. * @param name The name of the cloned light
  21828. * @returns the new created light
  21829. */
  21830. Light.prototype.clone = function (name) {
  21831. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21832. if (!constructor) {
  21833. return null;
  21834. }
  21835. return BABYLON.SerializationHelper.Clone(constructor, this);
  21836. };
  21837. /**
  21838. * Serializes the current light into a Serialization object.
  21839. * @returns the serialized object.
  21840. */
  21841. Light.prototype.serialize = function () {
  21842. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21843. // Type
  21844. serializationObject.type = this.getTypeID();
  21845. // Parent
  21846. if (this.parent) {
  21847. serializationObject.parentId = this.parent.id;
  21848. }
  21849. // Inclusion / exclusions
  21850. if (this.excludedMeshes.length > 0) {
  21851. serializationObject.excludedMeshesIds = [];
  21852. this.excludedMeshes.forEach(function (mesh) {
  21853. serializationObject.excludedMeshesIds.push(mesh.id);
  21854. });
  21855. }
  21856. if (this.includedOnlyMeshes.length > 0) {
  21857. serializationObject.includedOnlyMeshesIds = [];
  21858. this.includedOnlyMeshes.forEach(function (mesh) {
  21859. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21860. });
  21861. }
  21862. // Animations
  21863. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21864. serializationObject.ranges = this.serializeAnimationRanges();
  21865. return serializationObject;
  21866. };
  21867. /**
  21868. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21869. * This new light is named "name" and added to the passed scene.
  21870. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21871. * @param name The friendly name of the light
  21872. * @param scene The scene the new light will belong to
  21873. * @returns the constructor function
  21874. */
  21875. Light.GetConstructorFromName = function (type, name, scene) {
  21876. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21877. if (constructorFunc) {
  21878. return constructorFunc;
  21879. }
  21880. // Default to no light for none present once.
  21881. return null;
  21882. };
  21883. /**
  21884. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21885. * @param parsedLight The JSON representation of the light
  21886. * @param scene The scene to create the parsed light in
  21887. * @returns the created light after parsing
  21888. */
  21889. Light.Parse = function (parsedLight, scene) {
  21890. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21891. if (!constructor) {
  21892. return null;
  21893. }
  21894. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21895. // Inclusion / exclusions
  21896. if (parsedLight.excludedMeshesIds) {
  21897. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21898. }
  21899. if (parsedLight.includedOnlyMeshesIds) {
  21900. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21901. }
  21902. // Parent
  21903. if (parsedLight.parentId) {
  21904. light._waitingParentId = parsedLight.parentId;
  21905. }
  21906. // Animations
  21907. if (parsedLight.animations) {
  21908. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21909. var parsedAnimation = parsedLight.animations[animationIndex];
  21910. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21911. }
  21912. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21913. }
  21914. if (parsedLight.autoAnimate) {
  21915. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21916. }
  21917. return light;
  21918. };
  21919. Light.prototype._hookArrayForExcluded = function (array) {
  21920. var _this = this;
  21921. var oldPush = array.push;
  21922. array.push = function () {
  21923. var items = [];
  21924. for (var _i = 0; _i < arguments.length; _i++) {
  21925. items[_i] = arguments[_i];
  21926. }
  21927. var result = oldPush.apply(array, items);
  21928. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21929. var item = items_1[_a];
  21930. item._resyncLighSource(_this);
  21931. }
  21932. return result;
  21933. };
  21934. var oldSplice = array.splice;
  21935. array.splice = function (index, deleteCount) {
  21936. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21937. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21938. var item = deleted_1[_i];
  21939. item._resyncLighSource(_this);
  21940. }
  21941. return deleted;
  21942. };
  21943. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21944. var item = array_1[_i];
  21945. item._resyncLighSource(this);
  21946. }
  21947. };
  21948. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21949. var _this = this;
  21950. var oldPush = array.push;
  21951. array.push = function () {
  21952. var items = [];
  21953. for (var _i = 0; _i < arguments.length; _i++) {
  21954. items[_i] = arguments[_i];
  21955. }
  21956. var result = oldPush.apply(array, items);
  21957. _this._resyncMeshes();
  21958. return result;
  21959. };
  21960. var oldSplice = array.splice;
  21961. array.splice = function (index, deleteCount) {
  21962. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21963. _this._resyncMeshes();
  21964. return deleted;
  21965. };
  21966. this._resyncMeshes();
  21967. };
  21968. Light.prototype._resyncMeshes = function () {
  21969. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21970. var mesh = _a[_i];
  21971. mesh._resyncLighSource(this);
  21972. }
  21973. };
  21974. /**
  21975. * Forces the meshes to update their light related information in their rendering used effects
  21976. * @hidden Internal Use Only
  21977. */
  21978. Light.prototype._markMeshesAsLightDirty = function () {
  21979. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21980. var mesh = _a[_i];
  21981. if (mesh._lightSources.indexOf(this) !== -1) {
  21982. mesh._markSubMeshesAsLightDirty();
  21983. }
  21984. }
  21985. };
  21986. /**
  21987. * Recomputes the cached photometric scale if needed.
  21988. */
  21989. Light.prototype._computePhotometricScale = function () {
  21990. this._photometricScale = this._getPhotometricScale();
  21991. this.getScene().resetCachedMaterial();
  21992. };
  21993. /**
  21994. * Returns the Photometric Scale according to the light type and intensity mode.
  21995. */
  21996. Light.prototype._getPhotometricScale = function () {
  21997. var photometricScale = 0.0;
  21998. var lightTypeID = this.getTypeID();
  21999. //get photometric mode
  22000. var photometricMode = this.intensityMode;
  22001. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22002. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22003. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22004. }
  22005. else {
  22006. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22007. }
  22008. }
  22009. //compute photometric scale
  22010. switch (lightTypeID) {
  22011. case Light.LIGHTTYPEID_POINTLIGHT:
  22012. case Light.LIGHTTYPEID_SPOTLIGHT:
  22013. switch (photometricMode) {
  22014. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22015. photometricScale = 1.0 / (4.0 * Math.PI);
  22016. break;
  22017. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22018. photometricScale = 1.0;
  22019. break;
  22020. case Light.INTENSITYMODE_LUMINANCE:
  22021. photometricScale = this.radius * this.radius;
  22022. break;
  22023. }
  22024. break;
  22025. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22026. switch (photometricMode) {
  22027. case Light.INTENSITYMODE_ILLUMINANCE:
  22028. photometricScale = 1.0;
  22029. break;
  22030. case Light.INTENSITYMODE_LUMINANCE:
  22031. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22032. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22033. var apexAngleRadians = this.radius;
  22034. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22035. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22036. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22037. photometricScale = solidAngle;
  22038. break;
  22039. }
  22040. break;
  22041. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22042. // No fall off in hemisperic light.
  22043. photometricScale = 1.0;
  22044. break;
  22045. }
  22046. return photometricScale;
  22047. };
  22048. /**
  22049. * Reorder the light in the scene according to their defined priority.
  22050. * @hidden Internal Use Only
  22051. */
  22052. Light.prototype._reorderLightsInScene = function () {
  22053. var scene = this.getScene();
  22054. if (this._renderPriority != 0) {
  22055. scene.requireLightSorting = true;
  22056. }
  22057. this.getScene().sortLightsByPriority();
  22058. };
  22059. /**
  22060. * Falloff Default: light is falling off following the material specification:
  22061. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22062. */
  22063. Light.FALLOFF_DEFAULT = 0;
  22064. /**
  22065. * Falloff Physical: light is falling off following the inverse squared distance law.
  22066. */
  22067. Light.FALLOFF_PHYSICAL = 1;
  22068. /**
  22069. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22070. * to enhance interoperability with other engines.
  22071. */
  22072. Light.FALLOFF_GLTF = 2;
  22073. /**
  22074. * Falloff Standard: light is falling off like in the standard material
  22075. * to enhance interoperability with other materials.
  22076. */
  22077. Light.FALLOFF_STANDARD = 3;
  22078. //lightmapMode Consts
  22079. /**
  22080. * If every light affecting the material is in this lightmapMode,
  22081. * material.lightmapTexture adds or multiplies
  22082. * (depends on material.useLightmapAsShadowmap)
  22083. * after every other light calculations.
  22084. */
  22085. Light.LIGHTMAP_DEFAULT = 0;
  22086. /**
  22087. * material.lightmapTexture as only diffuse lighting from this light
  22088. * adds only specular lighting from this light
  22089. * adds dynamic shadows
  22090. */
  22091. Light.LIGHTMAP_SPECULAR = 1;
  22092. /**
  22093. * material.lightmapTexture as only lighting
  22094. * no light calculation from this light
  22095. * only adds dynamic shadows from this light
  22096. */
  22097. Light.LIGHTMAP_SHADOWSONLY = 2;
  22098. // Intensity Mode Consts
  22099. /**
  22100. * Each light type uses the default quantity according to its type:
  22101. * point/spot lights use luminous intensity
  22102. * directional lights use illuminance
  22103. */
  22104. Light.INTENSITYMODE_AUTOMATIC = 0;
  22105. /**
  22106. * lumen (lm)
  22107. */
  22108. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22109. /**
  22110. * candela (lm/sr)
  22111. */
  22112. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22113. /**
  22114. * lux (lm/m^2)
  22115. */
  22116. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22117. /**
  22118. * nit (cd/m^2)
  22119. */
  22120. Light.INTENSITYMODE_LUMINANCE = 4;
  22121. // Light types ids const.
  22122. /**
  22123. * Light type const id of the point light.
  22124. */
  22125. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22126. /**
  22127. * Light type const id of the directional light.
  22128. */
  22129. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22130. /**
  22131. * Light type const id of the spot light.
  22132. */
  22133. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22134. /**
  22135. * Light type const id of the hemispheric light.
  22136. */
  22137. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22138. __decorate([
  22139. BABYLON.serializeAsColor3()
  22140. ], Light.prototype, "diffuse", void 0);
  22141. __decorate([
  22142. BABYLON.serializeAsColor3()
  22143. ], Light.prototype, "specular", void 0);
  22144. __decorate([
  22145. BABYLON.serialize()
  22146. ], Light.prototype, "falloffType", void 0);
  22147. __decorate([
  22148. BABYLON.serialize()
  22149. ], Light.prototype, "intensity", void 0);
  22150. __decorate([
  22151. BABYLON.serialize()
  22152. ], Light.prototype, "range", null);
  22153. __decorate([
  22154. BABYLON.serialize()
  22155. ], Light.prototype, "intensityMode", null);
  22156. __decorate([
  22157. BABYLON.serialize()
  22158. ], Light.prototype, "radius", null);
  22159. __decorate([
  22160. BABYLON.serialize()
  22161. ], Light.prototype, "_renderPriority", void 0);
  22162. __decorate([
  22163. BABYLON.expandToProperty("_reorderLightsInScene")
  22164. ], Light.prototype, "renderPriority", void 0);
  22165. __decorate([
  22166. BABYLON.serialize("shadowEnabled")
  22167. ], Light.prototype, "_shadowEnabled", void 0);
  22168. __decorate([
  22169. BABYLON.serialize("excludeWithLayerMask")
  22170. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22171. __decorate([
  22172. BABYLON.serialize("includeOnlyWithLayerMask")
  22173. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22174. __decorate([
  22175. BABYLON.serialize("lightmapMode")
  22176. ], Light.prototype, "_lightmapMode", void 0);
  22177. return Light;
  22178. }(BABYLON.Node));
  22179. BABYLON.Light = Light;
  22180. })(BABYLON || (BABYLON = {}));
  22181. //# sourceMappingURL=babylon.light.js.map
  22182. var BABYLON;
  22183. (function (BABYLON) {
  22184. var Camera = /** @class */ (function (_super) {
  22185. __extends(Camera, _super);
  22186. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22187. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22188. var _this = _super.call(this, name, scene) || this;
  22189. /**
  22190. * The vector the camera should consider as up.
  22191. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22192. */
  22193. _this.upVector = BABYLON.Vector3.Up();
  22194. _this.orthoLeft = null;
  22195. _this.orthoRight = null;
  22196. _this.orthoBottom = null;
  22197. _this.orthoTop = null;
  22198. /**
  22199. * FOV is set in Radians. (default is 0.8)
  22200. */
  22201. _this.fov = 0.8;
  22202. _this.minZ = 1;
  22203. _this.maxZ = 10000.0;
  22204. _this.inertia = 0.9;
  22205. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22206. _this.isIntermediate = false;
  22207. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22208. /**
  22209. * Restricts the camera to viewing objects with the same layerMask.
  22210. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22211. */
  22212. _this.layerMask = 0x0FFFFFFF;
  22213. /**
  22214. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22215. */
  22216. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22217. // Camera rig members
  22218. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22219. /** @hidden */
  22220. _this._rigCameras = new Array();
  22221. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22222. /** @hidden */
  22223. _this._skipRendering = false;
  22224. _this.customRenderTargets = new Array();
  22225. // Observables
  22226. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22227. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22228. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22229. _this.onRestoreStateObservable = new BABYLON.Observable();
  22230. // Cache
  22231. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22232. _this._projectionMatrix = new BABYLON.Matrix();
  22233. _this._doNotComputeProjectionMatrix = false;
  22234. _this._worldMatrix = BABYLON.Matrix.Identity();
  22235. _this._postProcesses = new Array();
  22236. _this._transformMatrix = BABYLON.Matrix.Zero();
  22237. _this._activeMeshes = new BABYLON.SmartArray(256);
  22238. _this._globalPosition = BABYLON.Vector3.Zero();
  22239. _this._refreshFrustumPlanes = true;
  22240. _this.getScene().addCamera(_this);
  22241. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22242. _this.getScene().activeCamera = _this;
  22243. }
  22244. _this.position = position;
  22245. return _this;
  22246. }
  22247. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22248. get: function () {
  22249. return Camera._PERSPECTIVE_CAMERA;
  22250. },
  22251. enumerable: true,
  22252. configurable: true
  22253. });
  22254. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22255. get: function () {
  22256. return Camera._ORTHOGRAPHIC_CAMERA;
  22257. },
  22258. enumerable: true,
  22259. configurable: true
  22260. });
  22261. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22262. /**
  22263. * This is the default FOV mode for perspective cameras.
  22264. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22265. *
  22266. */
  22267. get: function () {
  22268. return Camera._FOVMODE_VERTICAL_FIXED;
  22269. },
  22270. enumerable: true,
  22271. configurable: true
  22272. });
  22273. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22274. /**
  22275. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22276. *
  22277. */
  22278. get: function () {
  22279. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22280. },
  22281. enumerable: true,
  22282. configurable: true
  22283. });
  22284. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22285. get: function () {
  22286. return Camera._RIG_MODE_NONE;
  22287. },
  22288. enumerable: true,
  22289. configurable: true
  22290. });
  22291. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22292. get: function () {
  22293. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22294. },
  22295. enumerable: true,
  22296. configurable: true
  22297. });
  22298. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22299. get: function () {
  22300. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22301. },
  22302. enumerable: true,
  22303. configurable: true
  22304. });
  22305. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22306. get: function () {
  22307. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22308. },
  22309. enumerable: true,
  22310. configurable: true
  22311. });
  22312. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22313. get: function () {
  22314. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22315. },
  22316. enumerable: true,
  22317. configurable: true
  22318. });
  22319. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22320. get: function () {
  22321. return Camera._RIG_MODE_VR;
  22322. },
  22323. enumerable: true,
  22324. configurable: true
  22325. });
  22326. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22327. get: function () {
  22328. return Camera._RIG_MODE_WEBVR;
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. /**
  22334. * Store current camera state (fov, position, etc..)
  22335. */
  22336. Camera.prototype.storeState = function () {
  22337. this._stateStored = true;
  22338. this._storedFov = this.fov;
  22339. return this;
  22340. };
  22341. /**
  22342. * Restores the camera state values if it has been stored. You must call storeState() first
  22343. */
  22344. Camera.prototype._restoreStateValues = function () {
  22345. if (!this._stateStored) {
  22346. return false;
  22347. }
  22348. this.fov = this._storedFov;
  22349. return true;
  22350. };
  22351. /**
  22352. * Restored camera state. You must call storeState() first
  22353. */
  22354. Camera.prototype.restoreState = function () {
  22355. if (this._restoreStateValues()) {
  22356. this.onRestoreStateObservable.notifyObservers(this);
  22357. return true;
  22358. }
  22359. return false;
  22360. };
  22361. Camera.prototype.getClassName = function () {
  22362. return "Camera";
  22363. };
  22364. /**
  22365. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22366. */
  22367. Camera.prototype.toString = function (fullDetails) {
  22368. var ret = "Name: " + this.name;
  22369. ret += ", type: " + this.getClassName();
  22370. if (this.animations) {
  22371. for (var i = 0; i < this.animations.length; i++) {
  22372. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22373. }
  22374. }
  22375. if (fullDetails) {
  22376. }
  22377. return ret;
  22378. };
  22379. Object.defineProperty(Camera.prototype, "globalPosition", {
  22380. get: function () {
  22381. return this._globalPosition;
  22382. },
  22383. enumerable: true,
  22384. configurable: true
  22385. });
  22386. Camera.prototype.getActiveMeshes = function () {
  22387. return this._activeMeshes;
  22388. };
  22389. Camera.prototype.isActiveMesh = function (mesh) {
  22390. return (this._activeMeshes.indexOf(mesh) !== -1);
  22391. };
  22392. /**
  22393. * Is this camera ready to be used/rendered
  22394. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22395. * @return true if the camera is ready
  22396. */
  22397. Camera.prototype.isReady = function (completeCheck) {
  22398. if (completeCheck === void 0) { completeCheck = false; }
  22399. if (completeCheck) {
  22400. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22401. var pp = _a[_i];
  22402. if (pp && !pp.isReady()) {
  22403. return false;
  22404. }
  22405. }
  22406. }
  22407. return _super.prototype.isReady.call(this, completeCheck);
  22408. };
  22409. //Cache
  22410. /** @hidden */
  22411. Camera.prototype._initCache = function () {
  22412. _super.prototype._initCache.call(this);
  22413. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22414. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22415. this._cache.mode = undefined;
  22416. this._cache.minZ = undefined;
  22417. this._cache.maxZ = undefined;
  22418. this._cache.fov = undefined;
  22419. this._cache.fovMode = undefined;
  22420. this._cache.aspectRatio = undefined;
  22421. this._cache.orthoLeft = undefined;
  22422. this._cache.orthoRight = undefined;
  22423. this._cache.orthoBottom = undefined;
  22424. this._cache.orthoTop = undefined;
  22425. this._cache.renderWidth = undefined;
  22426. this._cache.renderHeight = undefined;
  22427. };
  22428. /** @hidden */
  22429. Camera.prototype._updateCache = function (ignoreParentClass) {
  22430. if (!ignoreParentClass) {
  22431. _super.prototype._updateCache.call(this);
  22432. }
  22433. this._cache.position.copyFrom(this.position);
  22434. this._cache.upVector.copyFrom(this.upVector);
  22435. };
  22436. // Synchronized
  22437. /** @hidden */
  22438. Camera.prototype._isSynchronized = function () {
  22439. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22440. };
  22441. /** @hidden */
  22442. Camera.prototype._isSynchronizedViewMatrix = function () {
  22443. if (!_super.prototype._isSynchronized.call(this))
  22444. return false;
  22445. return this._cache.position.equals(this.position)
  22446. && this._cache.upVector.equals(this.upVector)
  22447. && this.isSynchronizedWithParent();
  22448. };
  22449. /** @hidden */
  22450. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22451. var check = this._cache.mode === this.mode
  22452. && this._cache.minZ === this.minZ
  22453. && this._cache.maxZ === this.maxZ;
  22454. if (!check) {
  22455. return false;
  22456. }
  22457. var engine = this.getEngine();
  22458. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22459. check = this._cache.fov === this.fov
  22460. && this._cache.fovMode === this.fovMode
  22461. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22462. }
  22463. else {
  22464. check = this._cache.orthoLeft === this.orthoLeft
  22465. && this._cache.orthoRight === this.orthoRight
  22466. && this._cache.orthoBottom === this.orthoBottom
  22467. && this._cache.orthoTop === this.orthoTop
  22468. && this._cache.renderWidth === engine.getRenderWidth()
  22469. && this._cache.renderHeight === engine.getRenderHeight();
  22470. }
  22471. return check;
  22472. };
  22473. // Controls
  22474. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22475. };
  22476. Camera.prototype.detachControl = function (element) {
  22477. };
  22478. Camera.prototype.update = function () {
  22479. this._checkInputs();
  22480. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22481. this._updateRigCameras();
  22482. }
  22483. };
  22484. /** @hidden */
  22485. Camera.prototype._checkInputs = function () {
  22486. this.onAfterCheckInputsObservable.notifyObservers(this);
  22487. };
  22488. Object.defineProperty(Camera.prototype, "rigCameras", {
  22489. get: function () {
  22490. return this._rigCameras;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22496. get: function () {
  22497. return this._rigPostProcess;
  22498. },
  22499. enumerable: true,
  22500. configurable: true
  22501. });
  22502. /**
  22503. * Internal, gets the first post proces.
  22504. * @returns the first post process to be run on this camera.
  22505. */
  22506. Camera.prototype._getFirstPostProcess = function () {
  22507. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22508. if (this._postProcesses[ppIndex] !== null) {
  22509. return this._postProcesses[ppIndex];
  22510. }
  22511. }
  22512. return null;
  22513. };
  22514. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22515. // invalidate framebuffer
  22516. var firstPostProcess = this._getFirstPostProcess();
  22517. if (firstPostProcess) {
  22518. firstPostProcess.markTextureDirty();
  22519. }
  22520. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22521. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22522. var cam = this._rigCameras[i];
  22523. var rigPostProcess = cam._rigPostProcess;
  22524. // for VR rig, there does not have to be a post process
  22525. if (rigPostProcess) {
  22526. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22527. if (isPass) {
  22528. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22529. cam.isIntermediate = this._postProcesses.length === 0;
  22530. }
  22531. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22532. rigPostProcess.markTextureDirty();
  22533. }
  22534. else {
  22535. cam._postProcesses = this._postProcesses.slice(0);
  22536. }
  22537. }
  22538. };
  22539. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22540. if (insertAt === void 0) { insertAt = null; }
  22541. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22542. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22543. return 0;
  22544. }
  22545. if (insertAt == null || insertAt < 0) {
  22546. this._postProcesses.push(postProcess);
  22547. }
  22548. else if (this._postProcesses[insertAt] === null) {
  22549. this._postProcesses[insertAt] = postProcess;
  22550. }
  22551. else {
  22552. this._postProcesses.splice(insertAt, 0, postProcess);
  22553. }
  22554. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22555. return this._postProcesses.indexOf(postProcess);
  22556. };
  22557. Camera.prototype.detachPostProcess = function (postProcess) {
  22558. var idx = this._postProcesses.indexOf(postProcess);
  22559. if (idx !== -1) {
  22560. this._postProcesses[idx] = null;
  22561. }
  22562. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22563. };
  22564. Camera.prototype.getWorldMatrix = function () {
  22565. if (this._isSynchronizedViewMatrix()) {
  22566. return this._worldMatrix;
  22567. }
  22568. // Getting the the view matrix will also compute the world matrix.
  22569. this.getViewMatrix();
  22570. return this._worldMatrix;
  22571. };
  22572. /** @hidden */
  22573. Camera.prototype._getViewMatrix = function () {
  22574. return BABYLON.Matrix.Identity();
  22575. };
  22576. Camera.prototype.getViewMatrix = function (force) {
  22577. if (!force && this._isSynchronizedViewMatrix()) {
  22578. return this._computedViewMatrix;
  22579. }
  22580. this.updateCache();
  22581. this._computedViewMatrix = this._getViewMatrix();
  22582. this._currentRenderId = this.getScene().getRenderId();
  22583. this._childRenderId = this._currentRenderId;
  22584. this._refreshFrustumPlanes = true;
  22585. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22586. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22587. }
  22588. this.onViewMatrixChangedObservable.notifyObservers(this);
  22589. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22590. return this._computedViewMatrix;
  22591. };
  22592. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22593. this._doNotComputeProjectionMatrix = true;
  22594. if (projection !== undefined) {
  22595. this._projectionMatrix = projection;
  22596. }
  22597. };
  22598. ;
  22599. Camera.prototype.unfreezeProjectionMatrix = function () {
  22600. this._doNotComputeProjectionMatrix = false;
  22601. };
  22602. ;
  22603. Camera.prototype.getProjectionMatrix = function (force) {
  22604. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22605. return this._projectionMatrix;
  22606. }
  22607. // Cache
  22608. this._cache.mode = this.mode;
  22609. this._cache.minZ = this.minZ;
  22610. this._cache.maxZ = this.maxZ;
  22611. // Matrix
  22612. this._refreshFrustumPlanes = true;
  22613. var engine = this.getEngine();
  22614. var scene = this.getScene();
  22615. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22616. this._cache.fov = this.fov;
  22617. this._cache.fovMode = this.fovMode;
  22618. this._cache.aspectRatio = engine.getAspectRatio(this);
  22619. if (this.minZ <= 0) {
  22620. this.minZ = 0.1;
  22621. }
  22622. if (scene.useRightHandedSystem) {
  22623. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22624. }
  22625. else {
  22626. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22627. }
  22628. }
  22629. else {
  22630. var halfWidth = engine.getRenderWidth() / 2.0;
  22631. var halfHeight = engine.getRenderHeight() / 2.0;
  22632. if (scene.useRightHandedSystem) {
  22633. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22634. }
  22635. else {
  22636. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22637. }
  22638. this._cache.orthoLeft = this.orthoLeft;
  22639. this._cache.orthoRight = this.orthoRight;
  22640. this._cache.orthoBottom = this.orthoBottom;
  22641. this._cache.orthoTop = this.orthoTop;
  22642. this._cache.renderWidth = engine.getRenderWidth();
  22643. this._cache.renderHeight = engine.getRenderHeight();
  22644. }
  22645. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22646. return this._projectionMatrix;
  22647. };
  22648. /**
  22649. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22650. * @returns a Matrix
  22651. */
  22652. Camera.prototype.getTransformationMatrix = function () {
  22653. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22654. return this._transformMatrix;
  22655. };
  22656. Camera.prototype.updateFrustumPlanes = function () {
  22657. if (!this._refreshFrustumPlanes) {
  22658. return;
  22659. }
  22660. this.getTransformationMatrix();
  22661. if (!this._frustumPlanes) {
  22662. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22663. }
  22664. else {
  22665. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22666. }
  22667. this._refreshFrustumPlanes = false;
  22668. };
  22669. Camera.prototype.isInFrustum = function (target) {
  22670. this.updateFrustumPlanes();
  22671. return target.isInFrustum(this._frustumPlanes);
  22672. };
  22673. Camera.prototype.isCompletelyInFrustum = function (target) {
  22674. this.updateFrustumPlanes();
  22675. return target.isCompletelyInFrustum(this._frustumPlanes);
  22676. };
  22677. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22678. if (length === void 0) { length = 100; }
  22679. if (!transform) {
  22680. transform = this.getWorldMatrix();
  22681. }
  22682. if (!origin) {
  22683. origin = this.position;
  22684. }
  22685. var forward = new BABYLON.Vector3(0, 0, 1);
  22686. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22687. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22688. return new BABYLON.Ray(origin, direction, length);
  22689. };
  22690. /**
  22691. * Releases resources associated with this node.
  22692. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22693. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22694. */
  22695. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22696. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22697. // Observables
  22698. this.onViewMatrixChangedObservable.clear();
  22699. this.onProjectionMatrixChangedObservable.clear();
  22700. this.onAfterCheckInputsObservable.clear();
  22701. this.onRestoreStateObservable.clear();
  22702. // Inputs
  22703. if (this.inputs) {
  22704. this.inputs.clear();
  22705. }
  22706. // Animations
  22707. this.getScene().stopAnimation(this);
  22708. // Remove from scene
  22709. this.getScene().removeCamera(this);
  22710. while (this._rigCameras.length > 0) {
  22711. var camera = this._rigCameras.pop();
  22712. if (camera) {
  22713. camera.dispose();
  22714. }
  22715. }
  22716. // Postprocesses
  22717. if (this._rigPostProcess) {
  22718. this._rigPostProcess.dispose(this);
  22719. this._rigPostProcess = null;
  22720. this._postProcesses = [];
  22721. }
  22722. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22723. this._rigPostProcess = null;
  22724. this._postProcesses = [];
  22725. }
  22726. else {
  22727. var i = this._postProcesses.length;
  22728. while (--i >= 0) {
  22729. var postProcess = this._postProcesses[i];
  22730. if (postProcess) {
  22731. postProcess.dispose(this);
  22732. }
  22733. }
  22734. }
  22735. // Render targets
  22736. var i = this.customRenderTargets.length;
  22737. while (--i >= 0) {
  22738. this.customRenderTargets[i].dispose();
  22739. }
  22740. this.customRenderTargets = [];
  22741. // Active Meshes
  22742. this._activeMeshes.dispose();
  22743. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22744. };
  22745. Object.defineProperty(Camera.prototype, "leftCamera", {
  22746. // ---- Camera rigs section ----
  22747. get: function () {
  22748. if (this._rigCameras.length < 1) {
  22749. return null;
  22750. }
  22751. return this._rigCameras[0];
  22752. },
  22753. enumerable: true,
  22754. configurable: true
  22755. });
  22756. Object.defineProperty(Camera.prototype, "rightCamera", {
  22757. get: function () {
  22758. if (this._rigCameras.length < 2) {
  22759. return null;
  22760. }
  22761. return this._rigCameras[1];
  22762. },
  22763. enumerable: true,
  22764. configurable: true
  22765. });
  22766. Camera.prototype.getLeftTarget = function () {
  22767. if (this._rigCameras.length < 1) {
  22768. return null;
  22769. }
  22770. return this._rigCameras[0].getTarget();
  22771. };
  22772. Camera.prototype.getRightTarget = function () {
  22773. if (this._rigCameras.length < 2) {
  22774. return null;
  22775. }
  22776. return this._rigCameras[1].getTarget();
  22777. };
  22778. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22779. if (this.cameraRigMode === mode) {
  22780. return;
  22781. }
  22782. while (this._rigCameras.length > 0) {
  22783. var camera = this._rigCameras.pop();
  22784. if (camera) {
  22785. camera.dispose();
  22786. }
  22787. }
  22788. this.cameraRigMode = mode;
  22789. this._cameraRigParams = {};
  22790. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22791. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22792. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22793. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22794. // create the rig cameras, unless none
  22795. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22796. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22797. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22798. if (leftCamera && rightCamera) {
  22799. this._rigCameras.push(leftCamera);
  22800. this._rigCameras.push(rightCamera);
  22801. }
  22802. }
  22803. switch (this.cameraRigMode) {
  22804. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22805. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22806. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22807. break;
  22808. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22809. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22810. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22811. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22812. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22813. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22814. break;
  22815. case Camera.RIG_MODE_VR:
  22816. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22817. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22818. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22819. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22820. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22821. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22822. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22823. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22824. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22825. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22826. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22827. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22828. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22829. if (metrics.compensateDistortion) {
  22830. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22831. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22832. }
  22833. break;
  22834. case Camera.RIG_MODE_WEBVR:
  22835. if (rigParams.vrDisplay) {
  22836. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22837. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22838. //Left eye
  22839. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22840. this._rigCameras[0].setCameraRigParameter("left", true);
  22841. //leaving this for future reference
  22842. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22843. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22844. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22845. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22846. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22847. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22848. this._rigCameras[0].parent = this;
  22849. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22850. //Right eye
  22851. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22852. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22853. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22854. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22855. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22856. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22857. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22858. this._rigCameras[1].parent = this;
  22859. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22860. if (Camera.UseAlternateWebVRRendering) {
  22861. this._rigCameras[1]._skipRendering = true;
  22862. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22863. }
  22864. }
  22865. break;
  22866. }
  22867. this._cascadePostProcessesToRigCams();
  22868. this.update();
  22869. };
  22870. Camera.prototype._getVRProjectionMatrix = function () {
  22871. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22872. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22873. return this._projectionMatrix;
  22874. };
  22875. Camera.prototype._updateCameraRotationMatrix = function () {
  22876. //Here for WebVR
  22877. };
  22878. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22879. //Here for WebVR
  22880. };
  22881. /**
  22882. * This function MUST be overwritten by the different WebVR cameras available.
  22883. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22884. */
  22885. Camera.prototype._getWebVRProjectionMatrix = function () {
  22886. return BABYLON.Matrix.Identity();
  22887. };
  22888. /**
  22889. * This function MUST be overwritten by the different WebVR cameras available.
  22890. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22891. */
  22892. Camera.prototype._getWebVRViewMatrix = function () {
  22893. return BABYLON.Matrix.Identity();
  22894. };
  22895. Camera.prototype.setCameraRigParameter = function (name, value) {
  22896. if (!this._cameraRigParams) {
  22897. this._cameraRigParams = {};
  22898. }
  22899. this._cameraRigParams[name] = value;
  22900. //provisionnally:
  22901. if (name === "interaxialDistance") {
  22902. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22903. }
  22904. };
  22905. /**
  22906. * needs to be overridden by children so sub has required properties to be copied
  22907. */
  22908. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22909. return null;
  22910. };
  22911. /**
  22912. * May need to be overridden by children
  22913. * @hidden
  22914. */
  22915. Camera.prototype._updateRigCameras = function () {
  22916. for (var i = 0; i < this._rigCameras.length; i++) {
  22917. this._rigCameras[i].minZ = this.minZ;
  22918. this._rigCameras[i].maxZ = this.maxZ;
  22919. this._rigCameras[i].fov = this.fov;
  22920. }
  22921. // only update viewport when ANAGLYPH
  22922. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22923. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22924. }
  22925. };
  22926. /** @hidden */
  22927. Camera.prototype._setupInputs = function () {
  22928. };
  22929. Camera.prototype.serialize = function () {
  22930. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22931. // Type
  22932. serializationObject.type = this.getClassName();
  22933. // Parent
  22934. if (this.parent) {
  22935. serializationObject.parentId = this.parent.id;
  22936. }
  22937. if (this.inputs) {
  22938. this.inputs.serialize(serializationObject);
  22939. }
  22940. // Animations
  22941. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22942. serializationObject.ranges = this.serializeAnimationRanges();
  22943. return serializationObject;
  22944. };
  22945. Camera.prototype.clone = function (name) {
  22946. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22947. };
  22948. Camera.prototype.getDirection = function (localAxis) {
  22949. var result = BABYLON.Vector3.Zero();
  22950. this.getDirectionToRef(localAxis, result);
  22951. return result;
  22952. };
  22953. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22954. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22955. };
  22956. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22957. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22958. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22959. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22960. interaxial_distance: interaxial_distance,
  22961. isStereoscopicSideBySide: isStereoscopicSideBySide
  22962. });
  22963. if (constructorFunc) {
  22964. return constructorFunc;
  22965. }
  22966. // Default to universal camera
  22967. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22968. };
  22969. Camera.prototype.computeWorldMatrix = function () {
  22970. return this.getWorldMatrix();
  22971. };
  22972. Camera.Parse = function (parsedCamera, scene) {
  22973. var type = parsedCamera.type;
  22974. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22975. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22976. // Parent
  22977. if (parsedCamera.parentId) {
  22978. camera._waitingParentId = parsedCamera.parentId;
  22979. }
  22980. //If camera has an input manager, let it parse inputs settings
  22981. if (camera.inputs) {
  22982. camera.inputs.parse(parsedCamera);
  22983. camera._setupInputs();
  22984. }
  22985. if (camera.setPosition) { // need to force position
  22986. camera.position.copyFromFloats(0, 0, 0);
  22987. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22988. }
  22989. // Target
  22990. if (parsedCamera.target) {
  22991. if (camera.setTarget) {
  22992. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22993. }
  22994. }
  22995. // Apply 3d rig, when found
  22996. if (parsedCamera.cameraRigMode) {
  22997. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22998. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22999. }
  23000. // Animations
  23001. if (parsedCamera.animations) {
  23002. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23003. var parsedAnimation = parsedCamera.animations[animationIndex];
  23004. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23005. }
  23006. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23007. }
  23008. if (parsedCamera.autoAnimate) {
  23009. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23010. }
  23011. return camera;
  23012. };
  23013. // Statics
  23014. Camera._PERSPECTIVE_CAMERA = 0;
  23015. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23016. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23017. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23018. Camera._RIG_MODE_NONE = 0;
  23019. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23020. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23021. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23022. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23023. Camera._RIG_MODE_VR = 20;
  23024. Camera._RIG_MODE_WEBVR = 21;
  23025. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23026. Camera.UseAlternateWebVRRendering = false;
  23027. __decorate([
  23028. BABYLON.serializeAsVector3()
  23029. ], Camera.prototype, "position", void 0);
  23030. __decorate([
  23031. BABYLON.serializeAsVector3()
  23032. ], Camera.prototype, "upVector", void 0);
  23033. __decorate([
  23034. BABYLON.serialize()
  23035. ], Camera.prototype, "orthoLeft", void 0);
  23036. __decorate([
  23037. BABYLON.serialize()
  23038. ], Camera.prototype, "orthoRight", void 0);
  23039. __decorate([
  23040. BABYLON.serialize()
  23041. ], Camera.prototype, "orthoBottom", void 0);
  23042. __decorate([
  23043. BABYLON.serialize()
  23044. ], Camera.prototype, "orthoTop", void 0);
  23045. __decorate([
  23046. BABYLON.serialize()
  23047. ], Camera.prototype, "fov", void 0);
  23048. __decorate([
  23049. BABYLON.serialize()
  23050. ], Camera.prototype, "minZ", void 0);
  23051. __decorate([
  23052. BABYLON.serialize()
  23053. ], Camera.prototype, "maxZ", void 0);
  23054. __decorate([
  23055. BABYLON.serialize()
  23056. ], Camera.prototype, "inertia", void 0);
  23057. __decorate([
  23058. BABYLON.serialize()
  23059. ], Camera.prototype, "mode", void 0);
  23060. __decorate([
  23061. BABYLON.serialize()
  23062. ], Camera.prototype, "layerMask", void 0);
  23063. __decorate([
  23064. BABYLON.serialize()
  23065. ], Camera.prototype, "fovMode", void 0);
  23066. __decorate([
  23067. BABYLON.serialize()
  23068. ], Camera.prototype, "cameraRigMode", void 0);
  23069. __decorate([
  23070. BABYLON.serialize()
  23071. ], Camera.prototype, "interaxialDistance", void 0);
  23072. __decorate([
  23073. BABYLON.serialize()
  23074. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23075. return Camera;
  23076. }(BABYLON.Node));
  23077. BABYLON.Camera = Camera;
  23078. })(BABYLON || (BABYLON = {}));
  23079. //# sourceMappingURL=babylon.camera.js.map
  23080. var BABYLON;
  23081. (function (BABYLON) {
  23082. var RenderingManager = /** @class */ (function () {
  23083. function RenderingManager(scene) {
  23084. /**
  23085. * @hidden
  23086. */
  23087. this._useSceneAutoClearSetup = false;
  23088. this._renderingGroups = new Array();
  23089. this._autoClearDepthStencil = {};
  23090. this._customOpaqueSortCompareFn = {};
  23091. this._customAlphaTestSortCompareFn = {};
  23092. this._customTransparentSortCompareFn = {};
  23093. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23094. this._scene = scene;
  23095. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23096. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23097. }
  23098. }
  23099. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23100. if (depth === void 0) { depth = true; }
  23101. if (stencil === void 0) { stencil = true; }
  23102. if (this._depthStencilBufferAlreadyCleaned) {
  23103. return;
  23104. }
  23105. this._scene.getEngine().clear(null, false, depth, stencil);
  23106. this._depthStencilBufferAlreadyCleaned = true;
  23107. };
  23108. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23109. // Update the observable context (not null as it only goes away on dispose)
  23110. var info = this._renderingGroupInfo;
  23111. info.scene = this._scene;
  23112. info.camera = this._scene.activeCamera;
  23113. // Dispatch sprites
  23114. if (this._scene.spriteManagers && renderSprites) {
  23115. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23116. var manager = this._scene.spriteManagers[index];
  23117. this.dispatchSprites(manager);
  23118. }
  23119. }
  23120. // Render
  23121. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23122. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23123. var renderingGroup = this._renderingGroups[index];
  23124. if (!renderingGroup)
  23125. continue;
  23126. var renderingGroupMask = Math.pow(2, index);
  23127. info.renderingGroupId = index;
  23128. // Before Observable
  23129. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23130. // Clear depth/stencil if needed
  23131. if (RenderingManager.AUTOCLEAR) {
  23132. var autoClear = this._useSceneAutoClearSetup ?
  23133. this._scene.getAutoClearDepthStencilSetup(index) :
  23134. this._autoClearDepthStencil[index];
  23135. if (autoClear && autoClear.autoClear) {
  23136. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23137. }
  23138. }
  23139. // Render
  23140. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23141. var step = _a[_i];
  23142. step.action(index);
  23143. }
  23144. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23145. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23146. var step = _c[_b];
  23147. step.action(index);
  23148. }
  23149. // After Observable
  23150. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23151. }
  23152. };
  23153. RenderingManager.prototype.reset = function () {
  23154. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23155. var renderingGroup = this._renderingGroups[index];
  23156. if (renderingGroup) {
  23157. renderingGroup.prepare();
  23158. }
  23159. }
  23160. };
  23161. RenderingManager.prototype.dispose = function () {
  23162. this.freeRenderingGroups();
  23163. this._renderingGroups.length = 0;
  23164. this._renderingGroupInfo = null;
  23165. };
  23166. /**
  23167. * Clear the info related to rendering groups preventing retention points during dispose.
  23168. */
  23169. RenderingManager.prototype.freeRenderingGroups = function () {
  23170. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23171. var renderingGroup = this._renderingGroups[index];
  23172. if (renderingGroup) {
  23173. renderingGroup.dispose();
  23174. }
  23175. }
  23176. };
  23177. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23178. if (this._renderingGroups[renderingGroupId] === undefined) {
  23179. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23180. }
  23181. };
  23182. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23183. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23184. this._prepareRenderingGroup(renderingGroupId);
  23185. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23186. };
  23187. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23188. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23189. this._prepareRenderingGroup(renderingGroupId);
  23190. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23191. };
  23192. /**
  23193. * @param subMesh The submesh to dispatch
  23194. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23195. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23196. */
  23197. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23198. if (mesh === undefined) {
  23199. mesh = subMesh.getMesh();
  23200. }
  23201. var renderingGroupId = mesh.renderingGroupId || 0;
  23202. this._prepareRenderingGroup(renderingGroupId);
  23203. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23204. };
  23205. /**
  23206. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23207. * This allowed control for front to back rendering or reversly depending of the special needs.
  23208. *
  23209. * @param renderingGroupId The rendering group id corresponding to its index
  23210. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23211. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23212. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23213. */
  23214. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23215. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23216. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23217. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23218. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23219. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23220. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23221. if (this._renderingGroups[renderingGroupId]) {
  23222. var group = this._renderingGroups[renderingGroupId];
  23223. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23224. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23225. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23226. }
  23227. };
  23228. /**
  23229. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23230. *
  23231. * @param renderingGroupId The rendering group id corresponding to its index
  23232. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23233. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23234. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23235. */
  23236. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23237. if (depth === void 0) { depth = true; }
  23238. if (stencil === void 0) { stencil = true; }
  23239. this._autoClearDepthStencil[renderingGroupId] = {
  23240. autoClear: autoClearDepthStencil,
  23241. depth: depth,
  23242. stencil: stencil
  23243. };
  23244. };
  23245. /**
  23246. * Gets the current auto clear configuration for one rendering group of the rendering
  23247. * manager.
  23248. * @param index the rendering group index to get the information for
  23249. * @returns The auto clear setup for the requested rendering group
  23250. */
  23251. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23252. return this._autoClearDepthStencil[index];
  23253. };
  23254. /**
  23255. * The max id used for rendering groups (not included)
  23256. */
  23257. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23258. /**
  23259. * The min id used for rendering groups (included)
  23260. */
  23261. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23262. /**
  23263. * Used to globally prevent autoclearing scenes.
  23264. */
  23265. RenderingManager.AUTOCLEAR = true;
  23266. return RenderingManager;
  23267. }());
  23268. BABYLON.RenderingManager = RenderingManager;
  23269. })(BABYLON || (BABYLON = {}));
  23270. //# sourceMappingURL=babylon.renderingManager.js.map
  23271. var BABYLON;
  23272. (function (BABYLON) {
  23273. var RenderingGroup = /** @class */ (function () {
  23274. /**
  23275. * Creates a new rendering group.
  23276. * @param index The rendering group index
  23277. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23278. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23279. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23280. */
  23281. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23282. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23283. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23284. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23285. this.index = index;
  23286. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23287. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23288. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23289. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23290. this._particleSystems = new BABYLON.SmartArray(256);
  23291. this._spriteManagers = new BABYLON.SmartArray(256);
  23292. this._edgesRenderers = new BABYLON.SmartArray(16);
  23293. this._scene = scene;
  23294. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23295. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23296. this.transparentSortCompareFn = transparentSortCompareFn;
  23297. }
  23298. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23299. /**
  23300. * Set the opaque sort comparison function.
  23301. * If null the sub meshes will be render in the order they were created
  23302. */
  23303. set: function (value) {
  23304. this._opaqueSortCompareFn = value;
  23305. if (value) {
  23306. this._renderOpaque = this.renderOpaqueSorted;
  23307. }
  23308. else {
  23309. this._renderOpaque = RenderingGroup.renderUnsorted;
  23310. }
  23311. },
  23312. enumerable: true,
  23313. configurable: true
  23314. });
  23315. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23316. /**
  23317. * Set the alpha test sort comparison function.
  23318. * If null the sub meshes will be render in the order they were created
  23319. */
  23320. set: function (value) {
  23321. this._alphaTestSortCompareFn = value;
  23322. if (value) {
  23323. this._renderAlphaTest = this.renderAlphaTestSorted;
  23324. }
  23325. else {
  23326. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23327. }
  23328. },
  23329. enumerable: true,
  23330. configurable: true
  23331. });
  23332. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23333. /**
  23334. * Set the transparent sort comparison function.
  23335. * If null the sub meshes will be render in the order they were created
  23336. */
  23337. set: function (value) {
  23338. if (value) {
  23339. this._transparentSortCompareFn = value;
  23340. }
  23341. else {
  23342. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23343. }
  23344. this._renderTransparent = this.renderTransparentSorted;
  23345. },
  23346. enumerable: true,
  23347. configurable: true
  23348. });
  23349. /**
  23350. * Render all the sub meshes contained in the group.
  23351. * @param customRenderFunction Used to override the default render behaviour of the group.
  23352. * @returns true if rendered some submeshes.
  23353. */
  23354. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23355. if (customRenderFunction) {
  23356. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23357. return;
  23358. }
  23359. var engine = this._scene.getEngine();
  23360. // Depth only
  23361. if (this._depthOnlySubMeshes.length !== 0) {
  23362. engine.setColorWrite(false);
  23363. this._renderAlphaTest(this._depthOnlySubMeshes);
  23364. engine.setColorWrite(true);
  23365. }
  23366. // Opaque
  23367. if (this._opaqueSubMeshes.length !== 0) {
  23368. this._renderOpaque(this._opaqueSubMeshes);
  23369. }
  23370. // Alpha test
  23371. if (this._alphaTestSubMeshes.length !== 0) {
  23372. this._renderAlphaTest(this._alphaTestSubMeshes);
  23373. }
  23374. var stencilState = engine.getStencilBuffer();
  23375. engine.setStencilBuffer(false);
  23376. // Sprites
  23377. if (renderSprites) {
  23378. this._renderSprites();
  23379. }
  23380. // Particles
  23381. if (renderParticles) {
  23382. this._renderParticles(activeMeshes);
  23383. }
  23384. if (this.onBeforeTransparentRendering) {
  23385. this.onBeforeTransparentRendering();
  23386. }
  23387. // Transparent
  23388. if (this._transparentSubMeshes.length !== 0) {
  23389. this._renderTransparent(this._transparentSubMeshes);
  23390. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23391. }
  23392. // Set back stencil to false in case it changes before the edge renderer.
  23393. engine.setStencilBuffer(false);
  23394. // Edges
  23395. if (this._edgesRenderers.length) {
  23396. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23397. this._edgesRenderers.data[edgesRendererIndex].render();
  23398. }
  23399. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23400. }
  23401. // Restore Stencil state.
  23402. engine.setStencilBuffer(stencilState);
  23403. };
  23404. /**
  23405. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23406. * @param subMeshes The submeshes to render
  23407. */
  23408. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23409. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23410. };
  23411. /**
  23412. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23413. * @param subMeshes The submeshes to render
  23414. */
  23415. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23416. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23417. };
  23418. /**
  23419. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23420. * @param subMeshes The submeshes to render
  23421. */
  23422. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23423. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23424. };
  23425. /**
  23426. * Renders the submeshes in a specified order.
  23427. * @param subMeshes The submeshes to sort before render
  23428. * @param sortCompareFn The comparison function use to sort
  23429. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23430. * @param transparent Specifies to activate blending if true
  23431. */
  23432. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23433. var subIndex = 0;
  23434. var subMesh;
  23435. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23436. for (; subIndex < subMeshes.length; subIndex++) {
  23437. subMesh = subMeshes.data[subIndex];
  23438. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23439. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23440. }
  23441. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23442. if (sortCompareFn) {
  23443. sortedArray.sort(sortCompareFn);
  23444. }
  23445. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23446. subMesh = sortedArray[subIndex];
  23447. if (transparent) {
  23448. var material = subMesh.getMaterial();
  23449. if (material && material.needDepthPrePass) {
  23450. var engine = material.getScene().getEngine();
  23451. engine.setColorWrite(false);
  23452. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23453. subMesh.render(false);
  23454. engine.setColorWrite(true);
  23455. }
  23456. }
  23457. subMesh.render(transparent);
  23458. }
  23459. };
  23460. /**
  23461. * Renders the submeshes in the order they were dispatched (no sort applied).
  23462. * @param subMeshes The submeshes to render
  23463. */
  23464. RenderingGroup.renderUnsorted = function (subMeshes) {
  23465. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23466. var submesh = subMeshes.data[subIndex];
  23467. submesh.render(false);
  23468. }
  23469. };
  23470. /**
  23471. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23472. * are rendered back to front if in the same alpha index.
  23473. *
  23474. * @param a The first submesh
  23475. * @param b The second submesh
  23476. * @returns The result of the comparison
  23477. */
  23478. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23479. // Alpha index first
  23480. if (a._alphaIndex > b._alphaIndex) {
  23481. return 1;
  23482. }
  23483. if (a._alphaIndex < b._alphaIndex) {
  23484. return -1;
  23485. }
  23486. // Then distance to camera
  23487. return RenderingGroup.backToFrontSortCompare(a, b);
  23488. };
  23489. /**
  23490. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23491. * are rendered back to front.
  23492. *
  23493. * @param a The first submesh
  23494. * @param b The second submesh
  23495. * @returns The result of the comparison
  23496. */
  23497. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23498. // Then distance to camera
  23499. if (a._distanceToCamera < b._distanceToCamera) {
  23500. return 1;
  23501. }
  23502. if (a._distanceToCamera > b._distanceToCamera) {
  23503. return -1;
  23504. }
  23505. return 0;
  23506. };
  23507. /**
  23508. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23509. * are rendered front to back (prevent overdraw).
  23510. *
  23511. * @param a The first submesh
  23512. * @param b The second submesh
  23513. * @returns The result of the comparison
  23514. */
  23515. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23516. // Then distance to camera
  23517. if (a._distanceToCamera < b._distanceToCamera) {
  23518. return -1;
  23519. }
  23520. if (a._distanceToCamera > b._distanceToCamera) {
  23521. return 1;
  23522. }
  23523. return 0;
  23524. };
  23525. /**
  23526. * Resets the different lists of submeshes to prepare a new frame.
  23527. */
  23528. RenderingGroup.prototype.prepare = function () {
  23529. this._opaqueSubMeshes.reset();
  23530. this._transparentSubMeshes.reset();
  23531. this._alphaTestSubMeshes.reset();
  23532. this._depthOnlySubMeshes.reset();
  23533. this._particleSystems.reset();
  23534. this._spriteManagers.reset();
  23535. this._edgesRenderers.reset();
  23536. };
  23537. RenderingGroup.prototype.dispose = function () {
  23538. this._opaqueSubMeshes.dispose();
  23539. this._transparentSubMeshes.dispose();
  23540. this._alphaTestSubMeshes.dispose();
  23541. this._depthOnlySubMeshes.dispose();
  23542. this._particleSystems.dispose();
  23543. this._spriteManagers.dispose();
  23544. this._edgesRenderers.dispose();
  23545. };
  23546. /**
  23547. * Inserts the submesh in its correct queue depending on its material.
  23548. * @param subMesh The submesh to dispatch
  23549. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23550. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23551. */
  23552. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23553. // Get mesh and materials if not provided
  23554. if (mesh === undefined) {
  23555. mesh = subMesh.getMesh();
  23556. }
  23557. if (material === undefined) {
  23558. material = subMesh.getMaterial();
  23559. }
  23560. if (material === null || material === undefined) {
  23561. return;
  23562. }
  23563. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23564. this._transparentSubMeshes.push(subMesh);
  23565. }
  23566. else if (material.needAlphaTesting()) { // Alpha test
  23567. if (material.needDepthPrePass) {
  23568. this._depthOnlySubMeshes.push(subMesh);
  23569. }
  23570. this._alphaTestSubMeshes.push(subMesh);
  23571. }
  23572. else {
  23573. if (material.needDepthPrePass) {
  23574. this._depthOnlySubMeshes.push(subMesh);
  23575. }
  23576. this._opaqueSubMeshes.push(subMesh); // Opaque
  23577. }
  23578. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23579. this._edgesRenderers.push(mesh._edgesRenderer);
  23580. }
  23581. };
  23582. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23583. this._spriteManagers.push(spriteManager);
  23584. };
  23585. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23586. this._particleSystems.push(particleSystem);
  23587. };
  23588. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23589. if (this._particleSystems.length === 0) {
  23590. return;
  23591. }
  23592. // Particles
  23593. var activeCamera = this._scene.activeCamera;
  23594. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23595. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23596. var particleSystem = this._particleSystems.data[particleIndex];
  23597. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23598. continue;
  23599. }
  23600. var emitter = particleSystem.emitter;
  23601. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23602. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23603. }
  23604. }
  23605. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23606. };
  23607. RenderingGroup.prototype._renderSprites = function () {
  23608. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23609. return;
  23610. }
  23611. // Sprites
  23612. var activeCamera = this._scene.activeCamera;
  23613. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23614. for (var id = 0; id < this._spriteManagers.length; id++) {
  23615. var spriteManager = this._spriteManagers.data[id];
  23616. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23617. spriteManager.render();
  23618. }
  23619. }
  23620. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23621. };
  23622. return RenderingGroup;
  23623. }());
  23624. BABYLON.RenderingGroup = RenderingGroup;
  23625. })(BABYLON || (BABYLON = {}));
  23626. //# sourceMappingURL=babylon.renderingGroup.js.map
  23627. var BABYLON;
  23628. (function (BABYLON) {
  23629. /**
  23630. * Groups all the scene component constants in one place to ease maintenance.
  23631. * @hidden
  23632. */
  23633. var SceneComponentConstants = /** @class */ (function () {
  23634. function SceneComponentConstants() {
  23635. }
  23636. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23637. SceneComponentConstants.NAME_LAYER = "Layer";
  23638. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23639. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23640. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23641. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23642. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23643. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23644. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23645. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23646. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23647. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23648. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23649. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23650. SceneComponentConstants.NAME_OCTREE = "Octree";
  23651. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23652. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23653. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23654. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23655. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23656. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23657. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23658. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23659. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23660. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23661. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23662. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23663. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23664. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23665. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23666. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23667. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23668. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23669. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23670. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23671. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23672. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23673. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23674. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23675. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23676. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23677. return SceneComponentConstants;
  23678. }());
  23679. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23680. /**
  23681. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23682. * @hidden
  23683. */
  23684. var Stage = /** @class */ (function (_super) {
  23685. __extends(Stage, _super);
  23686. /**
  23687. * Hide ctor from the rest of the world.
  23688. * @param items The items to add.
  23689. */
  23690. function Stage(items) {
  23691. return _super.apply(this, items) || this;
  23692. }
  23693. /**
  23694. * Creates a new Stage.
  23695. * @returns A new instance of a Stage
  23696. */
  23697. Stage.Create = function () {
  23698. return Object.create(Stage.prototype);
  23699. };
  23700. /**
  23701. * Registers a step in an ordered way in the targeted stage.
  23702. * @param index Defines the position to register the step in
  23703. * @param component Defines the component attached to the step
  23704. * @param action Defines the action to launch during the step
  23705. */
  23706. Stage.prototype.registerStep = function (index, component, action) {
  23707. var i = 0;
  23708. var maxIndex = Number.MAX_VALUE;
  23709. for (; i < this.length && i < maxIndex; i++) {
  23710. var step = this[i];
  23711. maxIndex = step.index;
  23712. }
  23713. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23714. };
  23715. /**
  23716. * Clears all the steps from the stage.
  23717. */
  23718. Stage.prototype.clear = function () {
  23719. this.length = 0;
  23720. };
  23721. return Stage;
  23722. }(Array));
  23723. BABYLON.Stage = Stage;
  23724. })(BABYLON || (BABYLON = {}));
  23725. //# sourceMappingURL=babylon.sceneComponent.js.map
  23726. var BABYLON;
  23727. (function (BABYLON) {
  23728. /**
  23729. * Base class of the scene acting as a container for the different elements composing a scene.
  23730. * This class is dynamically extended by the different components of the scene increasing
  23731. * flexibility and reducing coupling
  23732. */
  23733. var AbstractScene = /** @class */ (function () {
  23734. function AbstractScene() {
  23735. /**
  23736. * Gets the list of root nodes (ie. nodes with no parent)
  23737. */
  23738. this.rootNodes = new Array();
  23739. /** All of the cameras added to this scene
  23740. * @see http://doc.babylonjs.com/babylon101/cameras
  23741. */
  23742. this.cameras = new Array();
  23743. /**
  23744. * All of the lights added to this scene
  23745. * @see http://doc.babylonjs.com/babylon101/lights
  23746. */
  23747. this.lights = new Array();
  23748. /**
  23749. * All of the (abstract) meshes added to this scene
  23750. */
  23751. this.meshes = new Array();
  23752. /**
  23753. * The list of skeletons added to the scene
  23754. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23755. */
  23756. this.skeletons = new Array();
  23757. /**
  23758. * All of the particle systems added to this scene
  23759. * @see http://doc.babylonjs.com/babylon101/particles
  23760. */
  23761. this.particleSystems = new Array();
  23762. /**
  23763. * Gets a list of Animations associated with the scene
  23764. */
  23765. this.animations = [];
  23766. /**
  23767. * All of the animation groups added to this scene
  23768. * @see http://doc.babylonjs.com/how_to/group
  23769. */
  23770. this.animationGroups = new Array();
  23771. /**
  23772. * All of the multi-materials added to this scene
  23773. * @see http://doc.babylonjs.com/how_to/multi_materials
  23774. */
  23775. this.multiMaterials = new Array();
  23776. /**
  23777. * All of the materials added to this scene
  23778. * @see http://doc.babylonjs.com/babylon101/materials
  23779. */
  23780. this.materials = new Array();
  23781. /**
  23782. * The list of morph target managers added to the scene
  23783. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23784. */
  23785. this.morphTargetManagers = new Array();
  23786. /**
  23787. * The list of geometries used in the scene.
  23788. */
  23789. this.geometries = new Array();
  23790. /**
  23791. * All of the tranform nodes added to this scene
  23792. * @see http://doc.babylonjs.com/how_to/transformnode
  23793. */
  23794. this.transformNodes = new Array();
  23795. /**
  23796. * ActionManagers available on the scene.
  23797. */
  23798. this.actionManagers = new Array();
  23799. /**
  23800. * Sounds to keep.
  23801. */
  23802. this.sounds = new Array();
  23803. /**
  23804. * Textures to keep.
  23805. */
  23806. this.textures = new Array();
  23807. }
  23808. /**
  23809. * Adds a parser in the list of available ones
  23810. * @param name Defines the name of the parser
  23811. * @param parser Defines the parser to add
  23812. */
  23813. AbstractScene.AddParser = function (name, parser) {
  23814. this._BabylonFileParsers[name] = parser;
  23815. };
  23816. /**
  23817. * Gets a general parser from the list of avaialble ones
  23818. * @param name Defines the name of the parser
  23819. * @returns the requested parser or null
  23820. */
  23821. AbstractScene.GetParser = function (name) {
  23822. if (this._BabylonFileParsers[name]) {
  23823. return this._BabylonFileParsers[name];
  23824. }
  23825. return null;
  23826. };
  23827. /**
  23828. * Adds n individual parser in the list of available ones
  23829. * @param name Defines the name of the parser
  23830. * @param parser Defines the parser to add
  23831. */
  23832. AbstractScene.AddIndividualParser = function (name, parser) {
  23833. this._IndividualBabylonFileParsers[name] = parser;
  23834. };
  23835. /**
  23836. * Gets an individual parser from the list of avaialble ones
  23837. * @param name Defines the name of the parser
  23838. * @returns the requested parser or null
  23839. */
  23840. AbstractScene.GetIndividualParser = function (name) {
  23841. if (this._IndividualBabylonFileParsers[name]) {
  23842. return this._IndividualBabylonFileParsers[name];
  23843. }
  23844. return null;
  23845. };
  23846. /**
  23847. * Parser json data and populate both a scene and its associated container object
  23848. * @param jsonData Defines the data to parse
  23849. * @param scene Defines the scene to parse the data for
  23850. * @param container Defines the container attached to the parsing sequence
  23851. * @param rootUrl Defines the root url of the data
  23852. */
  23853. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23854. for (var parserName in this._BabylonFileParsers) {
  23855. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23856. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23857. }
  23858. }
  23859. };
  23860. /**
  23861. * Stores the list of available parsers in the application.
  23862. */
  23863. AbstractScene._BabylonFileParsers = {};
  23864. /**
  23865. * Stores the list of available individual parsers in the application.
  23866. */
  23867. AbstractScene._IndividualBabylonFileParsers = {};
  23868. return AbstractScene;
  23869. }());
  23870. BABYLON.AbstractScene = AbstractScene;
  23871. })(BABYLON || (BABYLON = {}));
  23872. //# sourceMappingURL=babylon.abstractScene.js.map
  23873. var BABYLON;
  23874. (function (BABYLON) {
  23875. /** @hidden */
  23876. var ClickInfo = /** @class */ (function () {
  23877. function ClickInfo() {
  23878. this._singleClick = false;
  23879. this._doubleClick = false;
  23880. this._hasSwiped = false;
  23881. this._ignore = false;
  23882. }
  23883. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23884. get: function () {
  23885. return this._singleClick;
  23886. },
  23887. set: function (b) {
  23888. this._singleClick = b;
  23889. },
  23890. enumerable: true,
  23891. configurable: true
  23892. });
  23893. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23894. get: function () {
  23895. return this._doubleClick;
  23896. },
  23897. set: function (b) {
  23898. this._doubleClick = b;
  23899. },
  23900. enumerable: true,
  23901. configurable: true
  23902. });
  23903. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23904. get: function () {
  23905. return this._hasSwiped;
  23906. },
  23907. set: function (b) {
  23908. this._hasSwiped = b;
  23909. },
  23910. enumerable: true,
  23911. configurable: true
  23912. });
  23913. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23914. get: function () {
  23915. return this._ignore;
  23916. },
  23917. set: function (b) {
  23918. this._ignore = b;
  23919. },
  23920. enumerable: true,
  23921. configurable: true
  23922. });
  23923. return ClickInfo;
  23924. }());
  23925. /**
  23926. * This class is used by the onRenderingGroupObservable
  23927. */
  23928. var RenderingGroupInfo = /** @class */ (function () {
  23929. function RenderingGroupInfo() {
  23930. }
  23931. return RenderingGroupInfo;
  23932. }());
  23933. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23934. /**
  23935. * Represents a scene to be rendered by the engine.
  23936. * @see http://doc.babylonjs.com/features/scene
  23937. */
  23938. var Scene = /** @class */ (function (_super) {
  23939. __extends(Scene, _super);
  23940. /**
  23941. * Creates a new Scene
  23942. * @param engine defines the engine to use to render this scene
  23943. */
  23944. function Scene(engine) {
  23945. var _this = _super.call(this) || this;
  23946. // Members
  23947. /**
  23948. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23949. */
  23950. _this.autoClear = true;
  23951. /**
  23952. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23953. */
  23954. _this.autoClearDepthAndStencil = true;
  23955. /**
  23956. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23957. */
  23958. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23959. /**
  23960. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23961. */
  23962. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23963. _this._forceWireframe = false;
  23964. _this._forcePointsCloud = false;
  23965. /**
  23966. * Gets or sets a boolean indicating if animations are enabled
  23967. */
  23968. _this.animationsEnabled = true;
  23969. _this._animationPropertiesOverride = null;
  23970. /**
  23971. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23972. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23973. */
  23974. _this.useConstantAnimationDeltaTime = false;
  23975. /**
  23976. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23977. * Please note that it requires to run a ray cast through the scene on every frame
  23978. */
  23979. _this.constantlyUpdateMeshUnderPointer = false;
  23980. /**
  23981. * Defines the HTML cursor to use when hovering over interactive elements
  23982. */
  23983. _this.hoverCursor = "pointer";
  23984. /**
  23985. * Defines the HTML default cursor to use (empty by default)
  23986. */
  23987. _this.defaultCursor = "";
  23988. /**
  23989. * This is used to call preventDefault() on pointer down
  23990. * in order to block unwanted artifacts like system double clicks
  23991. */
  23992. _this.preventDefaultOnPointerDown = true;
  23993. // Metadata
  23994. /**
  23995. * Gets or sets user defined metadata
  23996. */
  23997. _this.metadata = null;
  23998. /**
  23999. * Use this array to add regular expressions used to disable offline support for specific urls
  24000. */
  24001. _this.disableOfflineSupportExceptionRules = new Array();
  24002. /**
  24003. * An event triggered when the scene is disposed.
  24004. */
  24005. _this.onDisposeObservable = new BABYLON.Observable();
  24006. _this._onDisposeObserver = null;
  24007. /**
  24008. * An event triggered before rendering the scene (right after animations and physics)
  24009. */
  24010. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24011. _this._onBeforeRenderObserver = null;
  24012. /**
  24013. * An event triggered after rendering the scene
  24014. */
  24015. _this.onAfterRenderObservable = new BABYLON.Observable();
  24016. _this._onAfterRenderObserver = null;
  24017. /**
  24018. * An event triggered before animating the scene
  24019. */
  24020. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24021. /**
  24022. * An event triggered after animations processing
  24023. */
  24024. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24025. /**
  24026. * An event triggered before draw calls are ready to be sent
  24027. */
  24028. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24029. /**
  24030. * An event triggered after draw calls have been sent
  24031. */
  24032. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24033. /**
  24034. * An event triggered when physic simulation is about to be run
  24035. */
  24036. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24037. /**
  24038. * An event triggered when physic simulation has been done
  24039. */
  24040. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered when the scene is ready
  24043. */
  24044. _this.onReadyObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered before rendering a camera
  24047. */
  24048. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24049. _this._onBeforeCameraRenderObserver = null;
  24050. /**
  24051. * An event triggered after rendering a camera
  24052. */
  24053. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24054. _this._onAfterCameraRenderObserver = null;
  24055. /**
  24056. * An event triggered when active meshes evaluation is about to start
  24057. */
  24058. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24059. /**
  24060. * An event triggered when active meshes evaluation is done
  24061. */
  24062. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24063. /**
  24064. * An event triggered when particles rendering is about to start
  24065. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24066. */
  24067. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24068. /**
  24069. * An event triggered when particles rendering is done
  24070. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24071. */
  24072. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24073. /**
  24074. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24075. */
  24076. _this.onDataLoadedObservable = new BABYLON.Observable();
  24077. /**
  24078. * An event triggered when a camera is created
  24079. */
  24080. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24081. /**
  24082. * An event triggered when a camera is removed
  24083. */
  24084. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24085. /**
  24086. * An event triggered when a light is created
  24087. */
  24088. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24089. /**
  24090. * An event triggered when a light is removed
  24091. */
  24092. _this.onLightRemovedObservable = new BABYLON.Observable();
  24093. /**
  24094. * An event triggered when a geometry is created
  24095. */
  24096. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24097. /**
  24098. * An event triggered when a geometry is removed
  24099. */
  24100. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24101. /**
  24102. * An event triggered when a transform node is created
  24103. */
  24104. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24105. /**
  24106. * An event triggered when a transform node is removed
  24107. */
  24108. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24109. /**
  24110. * An event triggered when a mesh is created
  24111. */
  24112. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24113. /**
  24114. * An event triggered when a mesh is removed
  24115. */
  24116. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24117. /**
  24118. * An event triggered when render targets are about to be rendered
  24119. * Can happen multiple times per frame.
  24120. */
  24121. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24122. /**
  24123. * An event triggered when render targets were rendered.
  24124. * Can happen multiple times per frame.
  24125. */
  24126. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24127. /**
  24128. * An event triggered before calculating deterministic simulation step
  24129. */
  24130. _this.onBeforeStepObservable = new BABYLON.Observable();
  24131. /**
  24132. * An event triggered after calculating deterministic simulation step
  24133. */
  24134. _this.onAfterStepObservable = new BABYLON.Observable();
  24135. /**
  24136. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24137. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24138. * 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)
  24139. */
  24140. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24141. /**
  24142. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24143. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24144. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  24145. */
  24146. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24147. /**
  24148. * This Observable will when a mesh has been imported into the scene.
  24149. */
  24150. _this.onMeshImportedObservable = new BABYLON.Observable();
  24151. // Animations
  24152. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24153. /**
  24154. * 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).
  24155. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24156. */
  24157. _this.onPrePointerObservable = new BABYLON.Observable();
  24158. /**
  24159. * Observable event triggered each time an input event is received from the rendering canvas
  24160. */
  24161. _this.onPointerObservable = new BABYLON.Observable();
  24162. _this._meshPickProceed = false;
  24163. _this._currentPickResult = null;
  24164. _this._previousPickResult = null;
  24165. _this._totalPointersPressed = 0;
  24166. _this._doubleClickOccured = false;
  24167. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24168. _this.cameraToUseForPointers = null;
  24169. _this._pointerX = 0;
  24170. _this._pointerY = 0;
  24171. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24172. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24173. _this._startingPointerTime = 0;
  24174. _this._previousStartingPointerTime = 0;
  24175. _this._pointerCaptures = {};
  24176. // Deterministic lockstep
  24177. _this._timeAccumulator = 0;
  24178. _this._currentStepId = 0;
  24179. _this._currentInternalStep = 0;
  24180. // Keyboard
  24181. /**
  24182. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24183. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24184. */
  24185. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24186. /**
  24187. * Observable event triggered each time an keyboard event is received from the hosting window
  24188. */
  24189. _this.onKeyboardObservable = new BABYLON.Observable();
  24190. // Coordinates system
  24191. _this._useRightHandedSystem = false;
  24192. // Fog
  24193. _this._fogEnabled = true;
  24194. _this._fogMode = Scene.FOGMODE_NONE;
  24195. /**
  24196. * Gets or sets the fog color to use
  24197. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24198. */
  24199. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24200. /**
  24201. * Gets or sets the fog density to use
  24202. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24203. */
  24204. _this.fogDensity = 0.1;
  24205. /**
  24206. * Gets or sets the fog start distance to use
  24207. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24208. */
  24209. _this.fogStart = 0;
  24210. /**
  24211. * Gets or sets the fog end distance to use
  24212. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24213. */
  24214. _this.fogEnd = 1000.0;
  24215. // Lights
  24216. _this._shadowsEnabled = true;
  24217. _this._lightsEnabled = true;
  24218. /** All of the active cameras added to this scene. */
  24219. _this.activeCameras = new Array();
  24220. // Textures
  24221. _this._texturesEnabled = true;
  24222. // Particles
  24223. /**
  24224. * Gets or sets a boolean indicating if particles are enabled on this scene
  24225. */
  24226. _this.particlesEnabled = true;
  24227. // Sprites
  24228. /**
  24229. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24230. */
  24231. _this.spritesEnabled = true;
  24232. // Skeletons
  24233. _this._skeletonsEnabled = true;
  24234. // Lens flares
  24235. /**
  24236. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24237. */
  24238. _this.lensFlaresEnabled = true;
  24239. // Collisions
  24240. /**
  24241. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24242. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24243. */
  24244. _this.collisionsEnabled = true;
  24245. /**
  24246. * Defines the gravity applied to this scene (used only for collisions)
  24247. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24248. */
  24249. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24250. // Postprocesses
  24251. /**
  24252. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24253. */
  24254. _this.postProcessesEnabled = true;
  24255. /**
  24256. * The list of postprocesses added to the scene
  24257. */
  24258. _this.postProcesses = new Array();
  24259. // Customs render targets
  24260. /**
  24261. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24262. */
  24263. _this.renderTargetsEnabled = true;
  24264. /**
  24265. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24266. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24267. */
  24268. _this.dumpNextRenderTargets = false;
  24269. /**
  24270. * The list of user defined render targets added to the scene
  24271. */
  24272. _this.customRenderTargets = new Array();
  24273. /**
  24274. * Gets the list of meshes imported to the scene through SceneLoader
  24275. */
  24276. _this.importedMeshesFiles = new Array();
  24277. // Probes
  24278. /**
  24279. * Gets or sets a boolean indicating if probes are enabled on this scene
  24280. */
  24281. _this.probesEnabled = true;
  24282. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24283. // Procedural textures
  24284. /**
  24285. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24286. */
  24287. _this.proceduralTexturesEnabled = true;
  24288. /**
  24289. * The list of sound tracks added to the scene
  24290. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24291. */
  24292. _this.soundTracks = new Array();
  24293. _this._audioEnabled = true;
  24294. _this._headphone = false;
  24295. // Performance counters
  24296. _this._totalVertices = new BABYLON.PerfCounter();
  24297. /** @hidden */
  24298. _this._activeIndices = new BABYLON.PerfCounter();
  24299. /** @hidden */
  24300. _this._activeParticles = new BABYLON.PerfCounter();
  24301. /** @hidden */
  24302. _this._activeBones = new BABYLON.PerfCounter();
  24303. _this._animationTime = 0;
  24304. /**
  24305. * Gets or sets a general scale for animation speed
  24306. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24307. */
  24308. _this.animationTimeScale = 1;
  24309. _this._renderId = 0;
  24310. _this._frameId = 0;
  24311. _this._executeWhenReadyTimeoutId = -1;
  24312. _this._intermediateRendering = false;
  24313. _this._viewUpdateFlag = -1;
  24314. _this._projectionUpdateFlag = -1;
  24315. _this._alternateViewUpdateFlag = -1;
  24316. _this._alternateProjectionUpdateFlag = -1;
  24317. /** @hidden */
  24318. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24319. _this._activeRequests = new Array();
  24320. _this._pendingData = new Array();
  24321. _this._isDisposed = false;
  24322. /**
  24323. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24324. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24325. */
  24326. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24327. _this._activeMeshes = new BABYLON.SmartArray(256);
  24328. _this._processedMaterials = new BABYLON.SmartArray(256);
  24329. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24330. /** @hidden */
  24331. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24332. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24333. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24334. /** @hidden */
  24335. _this._activeAnimatables = new Array();
  24336. _this._transformMatrix = BABYLON.Matrix.Zero();
  24337. _this._useAlternateCameraConfiguration = false;
  24338. _this._alternateRendering = false;
  24339. /**
  24340. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24341. * This is useful if there are more lights that the maximum simulteanous authorized
  24342. */
  24343. _this.requireLightSorting = false;
  24344. /**
  24345. * @hidden
  24346. * Backing store of defined scene components.
  24347. */
  24348. _this._components = [];
  24349. /**
  24350. * @hidden
  24351. * Backing store of defined scene components.
  24352. */
  24353. _this._serializableComponents = [];
  24354. /**
  24355. * List of components to register on the next registration step.
  24356. */
  24357. _this._transientComponents = [];
  24358. /**
  24359. * @hidden
  24360. * Defines the actions happening before camera updates.
  24361. */
  24362. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24363. /**
  24364. * @hidden
  24365. * Defines the actions happening before clear the canvas.
  24366. */
  24367. _this._beforeClearStage = BABYLON.Stage.Create();
  24368. /**
  24369. * @hidden
  24370. * Defines the actions when collecting render targets for the frame.
  24371. */
  24372. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24373. /**
  24374. * @hidden
  24375. * Defines the actions happening for one camera in the frame.
  24376. */
  24377. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24378. /**
  24379. * @hidden
  24380. * Defines the actions happening during the per mesh ready checks.
  24381. */
  24382. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24383. /**
  24384. * @hidden
  24385. * Defines the actions happening before evaluate active mesh checks.
  24386. */
  24387. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24388. /**
  24389. * @hidden
  24390. * Defines the actions happening during the evaluate sub mesh checks.
  24391. */
  24392. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24393. /**
  24394. * @hidden
  24395. * Defines the actions happening during the active mesh stage.
  24396. */
  24397. _this._activeMeshStage = BABYLON.Stage.Create();
  24398. /**
  24399. * @hidden
  24400. * Defines the actions happening during the per camera render target step.
  24401. */
  24402. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24403. /**
  24404. * @hidden
  24405. * Defines the actions happening just before the active camera is drawing.
  24406. */
  24407. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24408. /**
  24409. * @hidden
  24410. * Defines the actions happening just before a rendering group is drawing.
  24411. */
  24412. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24413. /**
  24414. * @hidden
  24415. * Defines the actions happening just before a mesh is drawing.
  24416. */
  24417. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24418. /**
  24419. * @hidden
  24420. * Defines the actions happening just after a mesh has been drawn.
  24421. */
  24422. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24423. /**
  24424. * @hidden
  24425. * Defines the actions happening just after a rendering group has been drawn.
  24426. */
  24427. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24428. /**
  24429. * @hidden
  24430. * Defines the actions happening just after the active camera has been drawn.
  24431. */
  24432. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24433. /**
  24434. * @hidden
  24435. * Defines the actions happening when a pointer move event happens.
  24436. */
  24437. _this._pointerMoveStage = BABYLON.Stage.Create();
  24438. /**
  24439. * @hidden
  24440. * Defines the actions happening when a pointer down event happens.
  24441. */
  24442. _this._pointerDownStage = BABYLON.Stage.Create();
  24443. /**
  24444. * @hidden
  24445. * Defines the actions happening when a pointer up event happens.
  24446. */
  24447. _this._pointerUpStage = BABYLON.Stage.Create();
  24448. _this._defaultMeshCandidates = {
  24449. data: [],
  24450. length: 0
  24451. };
  24452. _this._defaultSubMeshCandidates = {
  24453. data: [],
  24454. length: 0
  24455. };
  24456. _this._activeMeshesFrozen = false;
  24457. /** @hidden */
  24458. _this._allowPostProcessClearColor = true;
  24459. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24460. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24461. _this.blockMaterialDirtyMechanism = false;
  24462. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24463. _this._engine.scenes.push(_this);
  24464. _this._uid = null;
  24465. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24466. if (BABYLON.PostProcessManager) {
  24467. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24468. }
  24469. if (BABYLON.Tools.IsWindowObjectExist()) {
  24470. _this.attachControl();
  24471. }
  24472. //collision coordinator initialization. For now legacy per default.
  24473. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24474. // Uniform Buffer
  24475. _this._createUbo();
  24476. // Default Image processing definition
  24477. if (BABYLON.ImageProcessingConfiguration) {
  24478. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24479. }
  24480. _this.setDefaultCandidateProviders();
  24481. return _this;
  24482. }
  24483. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24484. /**
  24485. * Texture used in all pbr material as the reflection texture.
  24486. * As in the majority of the scene they are the same (exception for multi room and so on),
  24487. * this is easier to reference from here than from all the materials.
  24488. */
  24489. get: function () {
  24490. return this._environmentTexture;
  24491. },
  24492. /**
  24493. * Texture used in all pbr material as the reflection texture.
  24494. * As in the majority of the scene they are the same (exception for multi room and so on),
  24495. * this is easier to set here than in all the materials.
  24496. */
  24497. set: function (value) {
  24498. if (this._environmentTexture === value) {
  24499. return;
  24500. }
  24501. this._environmentTexture = value;
  24502. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24503. },
  24504. enumerable: true,
  24505. configurable: true
  24506. });
  24507. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24508. /**
  24509. * Default image processing configuration used either in the rendering
  24510. * Forward main pass or through the imageProcessingPostProcess if present.
  24511. * As in the majority of the scene they are the same (exception for multi camera),
  24512. * this is easier to reference from here than from all the materials and post process.
  24513. *
  24514. * No setter as we it is a shared configuration, you can set the values instead.
  24515. */
  24516. get: function () {
  24517. return this._imageProcessingConfiguration;
  24518. },
  24519. enumerable: true,
  24520. configurable: true
  24521. });
  24522. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24523. get: function () {
  24524. return this._forceWireframe;
  24525. },
  24526. /**
  24527. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24528. */
  24529. set: function (value) {
  24530. if (this._forceWireframe === value) {
  24531. return;
  24532. }
  24533. this._forceWireframe = value;
  24534. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24540. get: function () {
  24541. return this._forcePointsCloud;
  24542. },
  24543. /**
  24544. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24545. */
  24546. set: function (value) {
  24547. if (this._forcePointsCloud === value) {
  24548. return;
  24549. }
  24550. this._forcePointsCloud = value;
  24551. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24557. /**
  24558. * Gets or sets the animation properties override
  24559. */
  24560. get: function () {
  24561. return this._animationPropertiesOverride;
  24562. },
  24563. set: function (value) {
  24564. this._animationPropertiesOverride = value;
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. Object.defineProperty(Scene.prototype, "onDispose", {
  24570. /** Sets a function to be executed when this scene is disposed. */
  24571. set: function (callback) {
  24572. if (this._onDisposeObserver) {
  24573. this.onDisposeObservable.remove(this._onDisposeObserver);
  24574. }
  24575. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(Scene.prototype, "beforeRender", {
  24581. /** Sets a function to be executed before rendering this scene */
  24582. set: function (callback) {
  24583. if (this._onBeforeRenderObserver) {
  24584. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24585. }
  24586. if (callback) {
  24587. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24588. }
  24589. },
  24590. enumerable: true,
  24591. configurable: true
  24592. });
  24593. Object.defineProperty(Scene.prototype, "afterRender", {
  24594. /** Sets a function to be executed after rendering this scene */
  24595. set: function (callback) {
  24596. if (this._onAfterRenderObserver) {
  24597. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24598. }
  24599. if (callback) {
  24600. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24601. }
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24607. /** Sets a function to be executed before rendering a camera*/
  24608. set: function (callback) {
  24609. if (this._onBeforeCameraRenderObserver) {
  24610. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24611. }
  24612. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24613. },
  24614. enumerable: true,
  24615. configurable: true
  24616. });
  24617. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24618. /** Sets a function to be executed after rendering a camera*/
  24619. set: function (callback) {
  24620. if (this._onAfterCameraRenderObserver) {
  24621. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24622. }
  24623. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24629. /**
  24630. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24631. */
  24632. get: function () {
  24633. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24634. },
  24635. enumerable: true,
  24636. configurable: true
  24637. });
  24638. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24639. get: function () {
  24640. return this._useRightHandedSystem;
  24641. },
  24642. /**
  24643. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24644. */
  24645. set: function (value) {
  24646. if (this._useRightHandedSystem === value) {
  24647. return;
  24648. }
  24649. this._useRightHandedSystem = value;
  24650. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24651. },
  24652. enumerable: true,
  24653. configurable: true
  24654. });
  24655. /**
  24656. * Sets the step Id used by deterministic lock step
  24657. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24658. * @param newStepId defines the step Id
  24659. */
  24660. Scene.prototype.setStepId = function (newStepId) {
  24661. this._currentStepId = newStepId;
  24662. };
  24663. ;
  24664. /**
  24665. * Gets the step Id used by deterministic lock step
  24666. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24667. * @returns the step Id
  24668. */
  24669. Scene.prototype.getStepId = function () {
  24670. return this._currentStepId;
  24671. };
  24672. ;
  24673. /**
  24674. * Gets the internal step used by deterministic lock step
  24675. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24676. * @returns the internal step
  24677. */
  24678. Scene.prototype.getInternalStep = function () {
  24679. return this._currentInternalStep;
  24680. };
  24681. ;
  24682. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24683. get: function () {
  24684. return this._fogEnabled;
  24685. },
  24686. /**
  24687. * Gets or sets a boolean indicating if fog is enabled on this scene
  24688. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24689. */
  24690. set: function (value) {
  24691. if (this._fogEnabled === value) {
  24692. return;
  24693. }
  24694. this._fogEnabled = value;
  24695. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. Object.defineProperty(Scene.prototype, "fogMode", {
  24701. get: function () {
  24702. return this._fogMode;
  24703. },
  24704. /**
  24705. * Gets or sets the fog mode to use
  24706. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24707. */
  24708. set: function (value) {
  24709. if (this._fogMode === value) {
  24710. return;
  24711. }
  24712. this._fogMode = value;
  24713. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24714. },
  24715. enumerable: true,
  24716. configurable: true
  24717. });
  24718. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24719. get: function () {
  24720. return this._shadowsEnabled;
  24721. },
  24722. /**
  24723. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24724. */
  24725. set: function (value) {
  24726. if (this._shadowsEnabled === value) {
  24727. return;
  24728. }
  24729. this._shadowsEnabled = value;
  24730. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24736. get: function () {
  24737. return this._lightsEnabled;
  24738. },
  24739. /**
  24740. * Gets or sets a boolean indicating if lights are enabled on this scene
  24741. */
  24742. set: function (value) {
  24743. if (this._lightsEnabled === value) {
  24744. return;
  24745. }
  24746. this._lightsEnabled = value;
  24747. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24748. },
  24749. enumerable: true,
  24750. configurable: true
  24751. });
  24752. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24753. /** The default material used on meshes when no material is affected */
  24754. get: function () {
  24755. if (!this._defaultMaterial) {
  24756. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24757. }
  24758. return this._defaultMaterial;
  24759. },
  24760. /** The default material used on meshes when no material is affected */
  24761. set: function (value) {
  24762. this._defaultMaterial = value;
  24763. },
  24764. enumerable: true,
  24765. configurable: true
  24766. });
  24767. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24768. get: function () {
  24769. return this._texturesEnabled;
  24770. },
  24771. /**
  24772. * Gets or sets a boolean indicating if textures are enabled on this scene
  24773. */
  24774. set: function (value) {
  24775. if (this._texturesEnabled === value) {
  24776. return;
  24777. }
  24778. this._texturesEnabled = value;
  24779. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24785. get: function () {
  24786. return this._skeletonsEnabled;
  24787. },
  24788. /**
  24789. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24790. */
  24791. set: function (value) {
  24792. if (this._skeletonsEnabled === value) {
  24793. return;
  24794. }
  24795. this._skeletonsEnabled = value;
  24796. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24797. },
  24798. enumerable: true,
  24799. configurable: true
  24800. });
  24801. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24802. /**
  24803. * Gets the main soundtrack associated with the scene
  24804. */
  24805. get: function () {
  24806. if (!this._mainSoundTrack) {
  24807. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24808. }
  24809. return this._mainSoundTrack;
  24810. },
  24811. enumerable: true,
  24812. configurable: true
  24813. });
  24814. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24815. /** @hidden */
  24816. get: function () {
  24817. return this._alternateRendering;
  24818. },
  24819. enumerable: true,
  24820. configurable: true
  24821. });
  24822. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24823. /**
  24824. * Gets the list of frustum planes (built from the active camera)
  24825. */
  24826. get: function () {
  24827. return this._frustumPlanes;
  24828. },
  24829. enumerable: true,
  24830. configurable: true
  24831. });
  24832. /**
  24833. * Registers the transient components if needed.
  24834. */
  24835. Scene.prototype._registerTransientComponents = function () {
  24836. // Register components that have been associated lately to the scene.
  24837. if (this._transientComponents.length > 0) {
  24838. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24839. var component = _a[_i];
  24840. component.register();
  24841. }
  24842. this._transientComponents = [];
  24843. }
  24844. };
  24845. /**
  24846. * @hidden
  24847. * Add a component to the scene.
  24848. * Note that the ccomponent could be registered on th next frame if this is called after
  24849. * the register component stage.
  24850. * @param component Defines the component to add to the scene
  24851. */
  24852. Scene.prototype._addComponent = function (component) {
  24853. this._components.push(component);
  24854. this._transientComponents.push(component);
  24855. var serializableComponent = component;
  24856. if (serializableComponent.addFromContainer) {
  24857. this._serializableComponents.push(serializableComponent);
  24858. }
  24859. };
  24860. /**
  24861. * @hidden
  24862. * Gets a component from the scene.
  24863. * @param name defines the name of the component to retrieve
  24864. * @returns the component or null if not present
  24865. */
  24866. Scene.prototype._getComponent = function (name) {
  24867. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24868. var component = _a[_i];
  24869. if (component.name === name) {
  24870. return component;
  24871. }
  24872. }
  24873. return null;
  24874. };
  24875. /**
  24876. * @hidden
  24877. */
  24878. Scene.prototype._getDefaultMeshCandidates = function () {
  24879. this._defaultMeshCandidates.data = this.meshes;
  24880. this._defaultMeshCandidates.length = this.meshes.length;
  24881. return this._defaultMeshCandidates;
  24882. };
  24883. /**
  24884. * @hidden
  24885. */
  24886. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  24887. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  24888. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  24889. return this._defaultSubMeshCandidates;
  24890. };
  24891. /**
  24892. * Sets the default candidate providers for the scene.
  24893. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  24894. * and getCollidingSubMeshCandidates to their default function
  24895. */
  24896. Scene.prototype.setDefaultCandidateProviders = function () {
  24897. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  24898. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24899. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24900. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24901. };
  24902. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24903. /**
  24904. * Gets a boolean indicating if collisions are processed on a web worker
  24905. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24906. */
  24907. get: function () {
  24908. return this._workerCollisions;
  24909. },
  24910. set: function (enabled) {
  24911. if (!BABYLON.CollisionCoordinatorLegacy) {
  24912. return;
  24913. }
  24914. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24915. this._workerCollisions = enabled;
  24916. if (this.collisionCoordinator) {
  24917. this.collisionCoordinator.destroy();
  24918. }
  24919. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24920. this.collisionCoordinator.init(this);
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24926. /**
  24927. * Gets the mesh that is currently under the pointer
  24928. */
  24929. get: function () {
  24930. return this._pointerOverMesh;
  24931. },
  24932. enumerable: true,
  24933. configurable: true
  24934. });
  24935. Object.defineProperty(Scene.prototype, "pointerX", {
  24936. /**
  24937. * Gets the current on-screen X position of the pointer
  24938. */
  24939. get: function () {
  24940. return this._pointerX;
  24941. },
  24942. enumerable: true,
  24943. configurable: true
  24944. });
  24945. Object.defineProperty(Scene.prototype, "pointerY", {
  24946. /**
  24947. * Gets the current on-screen Y position of the pointer
  24948. */
  24949. get: function () {
  24950. return this._pointerY;
  24951. },
  24952. enumerable: true,
  24953. configurable: true
  24954. });
  24955. /**
  24956. * Gets the cached material (ie. the latest rendered one)
  24957. * @returns the cached material
  24958. */
  24959. Scene.prototype.getCachedMaterial = function () {
  24960. return this._cachedMaterial;
  24961. };
  24962. /**
  24963. * Gets the cached effect (ie. the latest rendered one)
  24964. * @returns the cached effect
  24965. */
  24966. Scene.prototype.getCachedEffect = function () {
  24967. return this._cachedEffect;
  24968. };
  24969. /**
  24970. * Gets the cached visibility state (ie. the latest rendered one)
  24971. * @returns the cached visibility state
  24972. */
  24973. Scene.prototype.getCachedVisibility = function () {
  24974. return this._cachedVisibility;
  24975. };
  24976. /**
  24977. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24978. * @param material defines the current material
  24979. * @param effect defines the current effect
  24980. * @param visibility defines the current visibility state
  24981. * @returns true if one parameter is not cached
  24982. */
  24983. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24984. if (visibility === void 0) { visibility = 1; }
  24985. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24986. };
  24987. /**
  24988. * Gets the engine associated with the scene
  24989. * @returns an Engine
  24990. */
  24991. Scene.prototype.getEngine = function () {
  24992. return this._engine;
  24993. };
  24994. /**
  24995. * Gets the total number of vertices rendered per frame
  24996. * @returns the total number of vertices rendered per frame
  24997. */
  24998. Scene.prototype.getTotalVertices = function () {
  24999. return this._totalVertices.current;
  25000. };
  25001. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25002. /**
  25003. * Gets the performance counter for total vertices
  25004. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25005. */
  25006. get: function () {
  25007. return this._totalVertices;
  25008. },
  25009. enumerable: true,
  25010. configurable: true
  25011. });
  25012. /**
  25013. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25014. * @returns the total number of active indices rendered per frame
  25015. */
  25016. Scene.prototype.getActiveIndices = function () {
  25017. return this._activeIndices.current;
  25018. };
  25019. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25020. /**
  25021. * Gets the performance counter for active indices
  25022. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25023. */
  25024. get: function () {
  25025. return this._activeIndices;
  25026. },
  25027. enumerable: true,
  25028. configurable: true
  25029. });
  25030. /**
  25031. * Gets the total number of active particles rendered per frame
  25032. * @returns the total number of active particles rendered per frame
  25033. */
  25034. Scene.prototype.getActiveParticles = function () {
  25035. return this._activeParticles.current;
  25036. };
  25037. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25038. /**
  25039. * Gets the performance counter for active particles
  25040. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25041. */
  25042. get: function () {
  25043. return this._activeParticles;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. /**
  25049. * Gets the total number of active bones rendered per frame
  25050. * @returns the total number of active bones rendered per frame
  25051. */
  25052. Scene.prototype.getActiveBones = function () {
  25053. return this._activeBones.current;
  25054. };
  25055. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25056. /**
  25057. * Gets the performance counter for active bones
  25058. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25059. */
  25060. get: function () {
  25061. return this._activeBones;
  25062. },
  25063. enumerable: true,
  25064. configurable: true
  25065. });
  25066. /** @hidden */
  25067. Scene.prototype.getInterFramePerfCounter = function () {
  25068. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25069. return 0;
  25070. };
  25071. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25072. /** @hidden */
  25073. get: function () {
  25074. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25075. return null;
  25076. },
  25077. enumerable: true,
  25078. configurable: true
  25079. });
  25080. /** @hidden */
  25081. Scene.prototype.getLastFrameDuration = function () {
  25082. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25083. return 0;
  25084. };
  25085. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25086. /** @hidden */
  25087. get: function () {
  25088. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25089. return null;
  25090. },
  25091. enumerable: true,
  25092. configurable: true
  25093. });
  25094. /** @hidden */
  25095. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25096. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25097. return 0;
  25098. };
  25099. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25100. /** @hidden */
  25101. get: function () {
  25102. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25103. return null;
  25104. },
  25105. enumerable: true,
  25106. configurable: true
  25107. });
  25108. /**
  25109. * Gets the array of active meshes
  25110. * @returns an array of AbstractMesh
  25111. */
  25112. Scene.prototype.getActiveMeshes = function () {
  25113. return this._activeMeshes;
  25114. };
  25115. /** @hidden */
  25116. Scene.prototype.getRenderTargetsDuration = function () {
  25117. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25118. return 0;
  25119. };
  25120. /** @hidden */
  25121. Scene.prototype.getRenderDuration = function () {
  25122. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25123. return 0;
  25124. };
  25125. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25126. /** @hidden */
  25127. get: function () {
  25128. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25129. return null;
  25130. },
  25131. enumerable: true,
  25132. configurable: true
  25133. });
  25134. /** @hidden */
  25135. Scene.prototype.getParticlesDuration = function () {
  25136. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25137. return 0;
  25138. };
  25139. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25140. /** @hidden */
  25141. get: function () {
  25142. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25143. return null;
  25144. },
  25145. enumerable: true,
  25146. configurable: true
  25147. });
  25148. /** @hidden */
  25149. Scene.prototype.getSpritesDuration = function () {
  25150. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25151. return 0;
  25152. };
  25153. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25154. /** @hidden */
  25155. get: function () {
  25156. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25157. return null;
  25158. },
  25159. enumerable: true,
  25160. configurable: true
  25161. });
  25162. /**
  25163. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25164. * @returns a number
  25165. */
  25166. Scene.prototype.getAnimationRatio = function () {
  25167. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25168. };
  25169. /**
  25170. * Gets an unique Id for the current render phase
  25171. * @returns a number
  25172. */
  25173. Scene.prototype.getRenderId = function () {
  25174. return this._renderId;
  25175. };
  25176. /**
  25177. * Gets an unique Id for the current frame
  25178. * @returns a number
  25179. */
  25180. Scene.prototype.getFrameId = function () {
  25181. return this._frameId;
  25182. };
  25183. /** Call this function if you want to manually increment the render Id*/
  25184. Scene.prototype.incrementRenderId = function () {
  25185. this._renderId++;
  25186. };
  25187. Scene.prototype._updatePointerPosition = function (evt) {
  25188. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25189. if (!canvasRect) {
  25190. return;
  25191. }
  25192. this._pointerX = evt.clientX - canvasRect.left;
  25193. this._pointerY = evt.clientY - canvasRect.top;
  25194. this._unTranslatedPointerX = this._pointerX;
  25195. this._unTranslatedPointerY = this._pointerY;
  25196. };
  25197. Scene.prototype._createUbo = function () {
  25198. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25199. this._sceneUbo.addUniform("viewProjection", 16);
  25200. this._sceneUbo.addUniform("view", 16);
  25201. };
  25202. Scene.prototype._createAlternateUbo = function () {
  25203. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25204. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25205. this._alternateSceneUbo.addUniform("view", 16);
  25206. };
  25207. // Pointers handling
  25208. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25209. if (pointerInfo.pickInfo) {
  25210. if (!pointerInfo.pickInfo.ray) {
  25211. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25212. }
  25213. }
  25214. };
  25215. /**
  25216. * Use this method to simulate a pointer move on a mesh
  25217. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25218. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25219. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25220. * @returns the current scene
  25221. */
  25222. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25223. var evt = new PointerEvent("pointermove", pointerEventInit);
  25224. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25225. return this;
  25226. }
  25227. return this._processPointerMove(pickResult, evt);
  25228. };
  25229. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25230. var canvas = this._engine.getRenderingCanvas();
  25231. if (!canvas) {
  25232. return this;
  25233. }
  25234. // Restore pointer
  25235. canvas.style.cursor = this.defaultCursor;
  25236. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25237. if (isMeshPicked) {
  25238. this.setPointerOverMesh(pickResult.pickedMesh);
  25239. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25240. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25241. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25242. }
  25243. else {
  25244. canvas.style.cursor = this.hoverCursor;
  25245. }
  25246. }
  25247. }
  25248. else {
  25249. this.setPointerOverMesh(null);
  25250. }
  25251. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25252. var step = _a[_i];
  25253. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25254. }
  25255. if (pickResult) {
  25256. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25257. if (this.onPointerMove) {
  25258. this.onPointerMove(evt, pickResult, type);
  25259. }
  25260. if (this.onPointerObservable.hasObservers()) {
  25261. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25262. this._setRayOnPointerInfo(pi);
  25263. this.onPointerObservable.notifyObservers(pi, type);
  25264. }
  25265. }
  25266. return this;
  25267. };
  25268. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25269. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25270. if (pickResult) {
  25271. pi.ray = pickResult.ray;
  25272. }
  25273. this.onPrePointerObservable.notifyObservers(pi, type);
  25274. if (pi.skipOnPointerObservable) {
  25275. return true;
  25276. }
  25277. else {
  25278. return false;
  25279. }
  25280. };
  25281. /**
  25282. * Use this method to simulate a pointer down on a mesh
  25283. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25284. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25285. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25286. * @returns the current scene
  25287. */
  25288. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25289. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25290. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25291. return this;
  25292. }
  25293. return this._processPointerDown(pickResult, evt);
  25294. };
  25295. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25296. var _this = this;
  25297. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25298. this._pickedDownMesh = pickResult.pickedMesh;
  25299. var actionManager = pickResult.pickedMesh.actionManager;
  25300. if (actionManager) {
  25301. if (actionManager.hasPickTriggers) {
  25302. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25303. switch (evt.button) {
  25304. case 0:
  25305. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25306. break;
  25307. case 1:
  25308. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25309. break;
  25310. case 2:
  25311. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25312. break;
  25313. }
  25314. }
  25315. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25316. window.setTimeout(function () {
  25317. 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);
  25318. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25319. if (_this._totalPointersPressed !== 0 &&
  25320. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25321. !_this._isPointerSwiping()) {
  25322. _this._startingPointerTime = 0;
  25323. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25324. }
  25325. }
  25326. }, Scene.LongPressDelay);
  25327. }
  25328. }
  25329. }
  25330. else {
  25331. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25332. var step = _a[_i];
  25333. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25334. }
  25335. }
  25336. if (pickResult) {
  25337. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25338. if (this.onPointerDown) {
  25339. this.onPointerDown(evt, pickResult, type);
  25340. }
  25341. if (this.onPointerObservable.hasObservers()) {
  25342. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25343. this._setRayOnPointerInfo(pi);
  25344. this.onPointerObservable.notifyObservers(pi, type);
  25345. }
  25346. }
  25347. return this;
  25348. };
  25349. /**
  25350. * Use this method to simulate a pointer up on a mesh
  25351. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25352. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25353. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25354. * @returns the current scene
  25355. */
  25356. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25357. var evt = new PointerEvent("pointerup", pointerEventInit);
  25358. var clickInfo = new ClickInfo();
  25359. clickInfo.singleClick = true;
  25360. clickInfo.ignore = true;
  25361. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25362. return this;
  25363. }
  25364. return this._processPointerUp(pickResult, evt, clickInfo);
  25365. };
  25366. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25367. if (pickResult && pickResult && pickResult.pickedMesh) {
  25368. this._pickedUpMesh = pickResult.pickedMesh;
  25369. if (this._pickedDownMesh === this._pickedUpMesh) {
  25370. if (this.onPointerPick) {
  25371. this.onPointerPick(evt, pickResult);
  25372. }
  25373. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25374. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25375. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25376. this._setRayOnPointerInfo(pi);
  25377. this.onPointerObservable.notifyObservers(pi, type_1);
  25378. }
  25379. }
  25380. if (pickResult.pickedMesh.actionManager) {
  25381. if (clickInfo.ignore) {
  25382. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25383. }
  25384. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25385. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25386. }
  25387. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25388. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25389. }
  25390. }
  25391. }
  25392. else {
  25393. if (!clickInfo.ignore) {
  25394. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25395. var step = _a[_i];
  25396. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25397. }
  25398. }
  25399. }
  25400. if (this._pickedDownMesh &&
  25401. this._pickedDownMesh.actionManager &&
  25402. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25403. this._pickedDownMesh !== this._pickedUpMesh) {
  25404. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25405. }
  25406. var type = BABYLON.PointerEventTypes.POINTERUP;
  25407. if (this.onPointerObservable.hasObservers()) {
  25408. if (!clickInfo.ignore) {
  25409. if (!clickInfo.hasSwiped) {
  25410. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25411. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25412. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25413. this._setRayOnPointerInfo(pi);
  25414. this.onPointerObservable.notifyObservers(pi, type_2);
  25415. }
  25416. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25417. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25418. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25419. this._setRayOnPointerInfo(pi);
  25420. this.onPointerObservable.notifyObservers(pi, type_3);
  25421. }
  25422. }
  25423. }
  25424. else {
  25425. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25426. this._setRayOnPointerInfo(pi);
  25427. this.onPointerObservable.notifyObservers(pi, type);
  25428. }
  25429. }
  25430. if (this.onPointerUp) {
  25431. this.onPointerUp(evt, pickResult, type);
  25432. }
  25433. return this;
  25434. };
  25435. /**
  25436. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25437. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25438. * @returns true if the pointer was captured
  25439. */
  25440. Scene.prototype.isPointerCaptured = function (pointerId) {
  25441. if (pointerId === void 0) { pointerId = 0; }
  25442. return this._pointerCaptures[pointerId];
  25443. };
  25444. /** @hidden */
  25445. Scene.prototype._isPointerSwiping = function () {
  25446. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25447. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25448. };
  25449. /**
  25450. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25451. * @param attachUp defines if you want to attach events to pointerup
  25452. * @param attachDown defines if you want to attach events to pointerdown
  25453. * @param attachMove defines if you want to attach events to pointermove
  25454. */
  25455. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25456. var _this = this;
  25457. if (attachUp === void 0) { attachUp = true; }
  25458. if (attachDown === void 0) { attachDown = true; }
  25459. if (attachMove === void 0) { attachMove = true; }
  25460. this._initActionManager = function (act, clickInfo) {
  25461. if (!_this._meshPickProceed) {
  25462. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25463. _this._currentPickResult = pickResult;
  25464. if (pickResult) {
  25465. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25466. }
  25467. _this._meshPickProceed = true;
  25468. }
  25469. return act;
  25470. };
  25471. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25472. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25473. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25474. btn !== _this._previousButtonPressed) {
  25475. _this._doubleClickOccured = false;
  25476. clickInfo.singleClick = true;
  25477. clickInfo.ignore = false;
  25478. cb(clickInfo, _this._currentPickResult);
  25479. }
  25480. };
  25481. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25482. var clickInfo = new ClickInfo();
  25483. _this._currentPickResult = null;
  25484. var act = null;
  25485. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25486. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25487. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25488. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25489. act = _this._initActionManager(act, clickInfo);
  25490. if (act)
  25491. checkPicking = act.hasPickTriggers;
  25492. }
  25493. if (checkPicking) {
  25494. var btn = evt.button;
  25495. clickInfo.hasSwiped = _this._isPointerSwiping();
  25496. if (!clickInfo.hasSwiped) {
  25497. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25498. if (!checkSingleClickImmediately) {
  25499. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25500. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25501. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25502. act = _this._initActionManager(act, clickInfo);
  25503. if (act)
  25504. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25505. }
  25506. }
  25507. if (checkSingleClickImmediately) {
  25508. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25509. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25510. btn !== _this._previousButtonPressed) {
  25511. clickInfo.singleClick = true;
  25512. cb(clickInfo, _this._currentPickResult);
  25513. }
  25514. }
  25515. // at least one double click is required to be check and exclusive double click is enabled
  25516. else {
  25517. // wait that no double click has been raised during the double click delay
  25518. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25519. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25520. }
  25521. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25522. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25523. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25524. act = _this._initActionManager(act, clickInfo);
  25525. if (act)
  25526. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25527. }
  25528. if (checkDoubleClick) {
  25529. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25530. if (btn === _this._previousButtonPressed &&
  25531. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25532. !_this._doubleClickOccured) {
  25533. // pointer has not moved for 2 clicks, it's a double click
  25534. if (!clickInfo.hasSwiped &&
  25535. !_this._isPointerSwiping()) {
  25536. _this._previousStartingPointerTime = 0;
  25537. _this._doubleClickOccured = true;
  25538. clickInfo.doubleClick = true;
  25539. clickInfo.ignore = false;
  25540. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25541. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25542. }
  25543. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25544. cb(clickInfo, _this._currentPickResult);
  25545. }
  25546. // if the two successive clicks are too far, it's just two simple clicks
  25547. else {
  25548. _this._doubleClickOccured = false;
  25549. _this._previousStartingPointerTime = _this._startingPointerTime;
  25550. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25551. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25552. _this._previousButtonPressed = btn;
  25553. if (Scene.ExclusiveDoubleClickMode) {
  25554. if (_this._previousDelayedSimpleClickTimeout) {
  25555. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25556. }
  25557. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25558. cb(clickInfo, _this._previousPickResult);
  25559. }
  25560. else {
  25561. cb(clickInfo, _this._currentPickResult);
  25562. }
  25563. }
  25564. }
  25565. // just the first click of the double has been raised
  25566. else {
  25567. _this._doubleClickOccured = false;
  25568. _this._previousStartingPointerTime = _this._startingPointerTime;
  25569. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25570. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25571. _this._previousButtonPressed = btn;
  25572. }
  25573. }
  25574. }
  25575. }
  25576. clickInfo.ignore = true;
  25577. cb(clickInfo, _this._currentPickResult);
  25578. };
  25579. this._onPointerMove = function (evt) {
  25580. _this._updatePointerPosition(evt);
  25581. // PreObservable support
  25582. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25583. return;
  25584. }
  25585. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25586. return;
  25587. }
  25588. if (!_this.pointerMovePredicate) {
  25589. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25590. }
  25591. // Meshes
  25592. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25593. _this._processPointerMove(pickResult, evt);
  25594. };
  25595. this._onPointerDown = function (evt) {
  25596. _this._totalPointersPressed++;
  25597. _this._pickedDownMesh = null;
  25598. _this._meshPickProceed = false;
  25599. _this._updatePointerPosition(evt);
  25600. if (_this.preventDefaultOnPointerDown && canvas) {
  25601. evt.preventDefault();
  25602. canvas.focus();
  25603. }
  25604. // PreObservable support
  25605. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25606. return;
  25607. }
  25608. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25609. return;
  25610. }
  25611. _this._pointerCaptures[evt.pointerId] = true;
  25612. _this._startingPointerPosition.x = _this._pointerX;
  25613. _this._startingPointerPosition.y = _this._pointerY;
  25614. _this._startingPointerTime = Date.now();
  25615. if (!_this.pointerDownPredicate) {
  25616. _this.pointerDownPredicate = function (mesh) {
  25617. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25618. };
  25619. }
  25620. // Meshes
  25621. _this._pickedDownMesh = null;
  25622. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25623. _this._processPointerDown(pickResult, evt);
  25624. };
  25625. this._onPointerUp = function (evt) {
  25626. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25627. return; // So we need to test it the pointer down was pressed before.
  25628. }
  25629. _this._totalPointersPressed--;
  25630. _this._pickedUpMesh = null;
  25631. _this._meshPickProceed = false;
  25632. _this._updatePointerPosition(evt);
  25633. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25634. // PreObservable support
  25635. if (_this.onPrePointerObservable.hasObservers()) {
  25636. if (!clickInfo.ignore) {
  25637. if (!clickInfo.hasSwiped) {
  25638. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25639. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25640. return;
  25641. }
  25642. }
  25643. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25644. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25645. return;
  25646. }
  25647. }
  25648. }
  25649. }
  25650. else {
  25651. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25652. return;
  25653. }
  25654. }
  25655. }
  25656. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25657. return;
  25658. }
  25659. _this._pointerCaptures[evt.pointerId] = false;
  25660. if (!_this.pointerUpPredicate) {
  25661. _this.pointerUpPredicate = function (mesh) {
  25662. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25663. };
  25664. }
  25665. // Meshes
  25666. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25667. _this._initActionManager(null, clickInfo);
  25668. }
  25669. if (!pickResult) {
  25670. pickResult = _this._currentPickResult;
  25671. }
  25672. _this._processPointerUp(pickResult, evt, clickInfo);
  25673. _this._previousPickResult = _this._currentPickResult;
  25674. });
  25675. };
  25676. this._onKeyDown = function (evt) {
  25677. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25678. if (_this.onPreKeyboardObservable.hasObservers()) {
  25679. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25680. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25681. if (pi.skipOnPointerObservable) {
  25682. return;
  25683. }
  25684. }
  25685. if (_this.onKeyboardObservable.hasObservers()) {
  25686. var pi = new BABYLON.KeyboardInfo(type, evt);
  25687. _this.onKeyboardObservable.notifyObservers(pi, type);
  25688. }
  25689. if (_this.actionManager) {
  25690. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25691. }
  25692. };
  25693. this._onKeyUp = function (evt) {
  25694. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25695. if (_this.onPreKeyboardObservable.hasObservers()) {
  25696. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25697. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25698. if (pi.skipOnPointerObservable) {
  25699. return;
  25700. }
  25701. }
  25702. if (_this.onKeyboardObservable.hasObservers()) {
  25703. var pi = new BABYLON.KeyboardInfo(type, evt);
  25704. _this.onKeyboardObservable.notifyObservers(pi, type);
  25705. }
  25706. if (_this.actionManager) {
  25707. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25708. }
  25709. };
  25710. var engine = this.getEngine();
  25711. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25712. if (!canvas) {
  25713. return;
  25714. }
  25715. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25716. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25717. });
  25718. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25719. if (!canvas) {
  25720. return;
  25721. }
  25722. canvas.removeEventListener("keydown", _this._onKeyDown);
  25723. canvas.removeEventListener("keyup", _this._onKeyUp);
  25724. });
  25725. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25726. var canvas = this._engine.getRenderingCanvas();
  25727. if (!canvas) {
  25728. return;
  25729. }
  25730. if (attachMove) {
  25731. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25732. // Wheel
  25733. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25734. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25735. }
  25736. if (attachDown) {
  25737. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25738. }
  25739. if (attachUp) {
  25740. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25741. }
  25742. canvas.tabIndex = 1;
  25743. };
  25744. /** Detaches all event handlers*/
  25745. Scene.prototype.detachControl = function () {
  25746. var engine = this.getEngine();
  25747. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25748. var canvas = engine.getRenderingCanvas();
  25749. if (!canvas) {
  25750. return;
  25751. }
  25752. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25753. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25754. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25755. if (this._onCanvasBlurObserver) {
  25756. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25757. }
  25758. if (this._onCanvasFocusObserver) {
  25759. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25760. }
  25761. // Wheel
  25762. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25763. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25764. // Keyboard
  25765. canvas.removeEventListener("keydown", this._onKeyDown);
  25766. canvas.removeEventListener("keyup", this._onKeyUp);
  25767. // Observables
  25768. this.onKeyboardObservable.clear();
  25769. this.onPreKeyboardObservable.clear();
  25770. this.onPointerObservable.clear();
  25771. this.onPrePointerObservable.clear();
  25772. };
  25773. /**
  25774. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25775. * Delay loaded resources are not taking in account
  25776. * @return true if all required resources are ready
  25777. */
  25778. Scene.prototype.isReady = function () {
  25779. if (this._isDisposed) {
  25780. return false;
  25781. }
  25782. if (this._pendingData.length > 0) {
  25783. return false;
  25784. }
  25785. var index;
  25786. var engine = this.getEngine();
  25787. // Geometries
  25788. for (index = 0; index < this.geometries.length; index++) {
  25789. var geometry = this.geometries[index];
  25790. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25791. return false;
  25792. }
  25793. }
  25794. // Meshes
  25795. for (index = 0; index < this.meshes.length; index++) {
  25796. var mesh = this.meshes[index];
  25797. if (!mesh.isEnabled()) {
  25798. continue;
  25799. }
  25800. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25801. continue;
  25802. }
  25803. if (!mesh.isReady(true)) {
  25804. return false;
  25805. }
  25806. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25807. // Is Ready For Mesh
  25808. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25809. var step = _a[_i];
  25810. if (!step.action(mesh, hardwareInstancedRendering)) {
  25811. return false;
  25812. }
  25813. }
  25814. }
  25815. // Post-processes
  25816. if (this.activeCameras && this.activeCameras.length > 0) {
  25817. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25818. var camera = _c[_b];
  25819. if (!camera.isReady(true)) {
  25820. return false;
  25821. }
  25822. }
  25823. }
  25824. else if (this.activeCamera) {
  25825. if (!this.activeCamera.isReady(true)) {
  25826. return false;
  25827. }
  25828. }
  25829. // Particles
  25830. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25831. var particleSystem = _e[_d];
  25832. if (!particleSystem.isReady()) {
  25833. return false;
  25834. }
  25835. }
  25836. return true;
  25837. };
  25838. /** Resets all cached information relative to material (including effect and visibility) */
  25839. Scene.prototype.resetCachedMaterial = function () {
  25840. this._cachedMaterial = null;
  25841. this._cachedEffect = null;
  25842. this._cachedVisibility = null;
  25843. };
  25844. /**
  25845. * Registers a function to be called before every frame render
  25846. * @param func defines the function to register
  25847. */
  25848. Scene.prototype.registerBeforeRender = function (func) {
  25849. this.onBeforeRenderObservable.add(func);
  25850. };
  25851. /**
  25852. * Unregisters a function called before every frame render
  25853. * @param func defines the function to unregister
  25854. */
  25855. Scene.prototype.unregisterBeforeRender = function (func) {
  25856. this.onBeforeRenderObservable.removeCallback(func);
  25857. };
  25858. /**
  25859. * Registers a function to be called after every frame render
  25860. * @param func defines the function to register
  25861. */
  25862. Scene.prototype.registerAfterRender = function (func) {
  25863. this.onAfterRenderObservable.add(func);
  25864. };
  25865. /**
  25866. * Unregisters a function called after every frame render
  25867. * @param func defines the function to unregister
  25868. */
  25869. Scene.prototype.unregisterAfterRender = function (func) {
  25870. this.onAfterRenderObservable.removeCallback(func);
  25871. };
  25872. Scene.prototype._executeOnceBeforeRender = function (func) {
  25873. var _this = this;
  25874. var execFunc = function () {
  25875. func();
  25876. setTimeout(function () {
  25877. _this.unregisterBeforeRender(execFunc);
  25878. });
  25879. };
  25880. this.registerBeforeRender(execFunc);
  25881. };
  25882. /**
  25883. * The provided function will run before render once and will be disposed afterwards.
  25884. * A timeout delay can be provided so that the function will be executed in N ms.
  25885. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25886. * @param func The function to be executed.
  25887. * @param timeout optional delay in ms
  25888. */
  25889. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25890. var _this = this;
  25891. if (timeout !== undefined) {
  25892. setTimeout(function () {
  25893. _this._executeOnceBeforeRender(func);
  25894. }, timeout);
  25895. }
  25896. else {
  25897. this._executeOnceBeforeRender(func);
  25898. }
  25899. };
  25900. /** @hidden */
  25901. Scene.prototype._addPendingData = function (data) {
  25902. this._pendingData.push(data);
  25903. };
  25904. /** @hidden */
  25905. Scene.prototype._removePendingData = function (data) {
  25906. var wasLoading = this.isLoading;
  25907. var index = this._pendingData.indexOf(data);
  25908. if (index !== -1) {
  25909. this._pendingData.splice(index, 1);
  25910. }
  25911. if (wasLoading && !this.isLoading) {
  25912. this.onDataLoadedObservable.notifyObservers(this);
  25913. }
  25914. };
  25915. /**
  25916. * Returns the number of items waiting to be loaded
  25917. * @returns the number of items waiting to be loaded
  25918. */
  25919. Scene.prototype.getWaitingItemsCount = function () {
  25920. return this._pendingData.length;
  25921. };
  25922. Object.defineProperty(Scene.prototype, "isLoading", {
  25923. /**
  25924. * Returns a boolean indicating if the scene is still loading data
  25925. */
  25926. get: function () {
  25927. return this._pendingData.length > 0;
  25928. },
  25929. enumerable: true,
  25930. configurable: true
  25931. });
  25932. /**
  25933. * Registers a function to be executed when the scene is ready
  25934. * @param {Function} func - the function to be executed
  25935. */
  25936. Scene.prototype.executeWhenReady = function (func) {
  25937. var _this = this;
  25938. this.onReadyObservable.add(func);
  25939. if (this._executeWhenReadyTimeoutId !== -1) {
  25940. return;
  25941. }
  25942. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25943. _this._checkIsReady();
  25944. }, 150);
  25945. };
  25946. /**
  25947. * Returns a promise that resolves when the scene is ready
  25948. * @returns A promise that resolves when the scene is ready
  25949. */
  25950. Scene.prototype.whenReadyAsync = function () {
  25951. var _this = this;
  25952. return new Promise(function (resolve) {
  25953. _this.executeWhenReady(function () {
  25954. resolve();
  25955. });
  25956. });
  25957. };
  25958. /** @hidden */
  25959. Scene.prototype._checkIsReady = function () {
  25960. var _this = this;
  25961. this._registerTransientComponents();
  25962. if (this.isReady()) {
  25963. this.onReadyObservable.notifyObservers(this);
  25964. this.onReadyObservable.clear();
  25965. this._executeWhenReadyTimeoutId = -1;
  25966. return;
  25967. }
  25968. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25969. _this._checkIsReady();
  25970. }, 150);
  25971. };
  25972. // Animations
  25973. /**
  25974. * Will start the animation sequence of a given target
  25975. * @param target defines the target
  25976. * @param from defines from which frame should animation start
  25977. * @param to defines until which frame should animation run.
  25978. * @param weight defines the weight to apply to the animation (1.0 by default)
  25979. * @param loop defines if the animation loops
  25980. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25981. * @param onAnimationEnd defines the function to be executed when the animation ends
  25982. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25983. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25984. * @returns the animatable object created for this animation
  25985. */
  25986. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25987. if (weight === void 0) { weight = 1.0; }
  25988. if (speedRatio === void 0) { speedRatio = 1.0; }
  25989. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25990. returnedAnimatable.weight = weight;
  25991. return returnedAnimatable;
  25992. };
  25993. /**
  25994. * Will start the animation sequence of a given target
  25995. * @param target defines the target
  25996. * @param from defines from which frame should animation start
  25997. * @param to defines until which frame should animation run.
  25998. * @param loop defines if the animation loops
  25999. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26000. * @param onAnimationEnd defines the function to be executed when the animation ends
  26001. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26002. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26003. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26004. * @returns the animatable object created for this animation
  26005. */
  26006. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26007. if (speedRatio === void 0) { speedRatio = 1.0; }
  26008. if (stopCurrent === void 0) { stopCurrent = true; }
  26009. if (from > to && speedRatio > 0) {
  26010. speedRatio *= -1;
  26011. }
  26012. if (stopCurrent) {
  26013. this.stopAnimation(target, undefined, targetMask);
  26014. }
  26015. if (!animatable) {
  26016. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26017. }
  26018. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26019. // Local animations
  26020. if (target.animations && shouldRunTargetAnimations) {
  26021. animatable.appendAnimations(target, target.animations);
  26022. }
  26023. // Children animations
  26024. if (target.getAnimatables) {
  26025. var animatables = target.getAnimatables();
  26026. for (var index = 0; index < animatables.length; index++) {
  26027. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26028. }
  26029. }
  26030. animatable.reset();
  26031. return animatable;
  26032. };
  26033. /**
  26034. * Begin a new animation on a given node
  26035. * @param target defines the target where the animation will take place
  26036. * @param animations defines the list of animations to start
  26037. * @param from defines the initial value
  26038. * @param to defines the final value
  26039. * @param loop defines if you want animation to loop (off by default)
  26040. * @param speedRatio defines the speed ratio to apply to all animations
  26041. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26042. * @returns the list of created animatables
  26043. */
  26044. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26045. if (speedRatio === undefined) {
  26046. speedRatio = 1.0;
  26047. }
  26048. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26049. return animatable;
  26050. };
  26051. /**
  26052. * Begin a new animation on a given node and its hierarchy
  26053. * @param target defines the root node where the animation will take place
  26054. * @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.
  26055. * @param animations defines the list of animations to start
  26056. * @param from defines the initial value
  26057. * @param to defines the final value
  26058. * @param loop defines if you want animation to loop (off by default)
  26059. * @param speedRatio defines the speed ratio to apply to all animations
  26060. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26061. * @returns the list of animatables created for all nodes
  26062. */
  26063. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26064. var children = target.getDescendants(directDescendantsOnly);
  26065. var result = [];
  26066. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26067. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26068. var child = children_1[_i];
  26069. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26070. }
  26071. return result;
  26072. };
  26073. /**
  26074. * Gets the animatable associated with a specific target
  26075. * @param target defines the target of the animatable
  26076. * @returns the required animatable if found
  26077. */
  26078. Scene.prototype.getAnimatableByTarget = function (target) {
  26079. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26080. if (this._activeAnimatables[index].target === target) {
  26081. return this._activeAnimatables[index];
  26082. }
  26083. }
  26084. return null;
  26085. };
  26086. /**
  26087. * Gets all animatables associated with a given target
  26088. * @param target defines the target to look animatables for
  26089. * @returns an array of Animatables
  26090. */
  26091. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26092. var result = [];
  26093. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26094. if (this._activeAnimatables[index].target === target) {
  26095. result.push(this._activeAnimatables[index]);
  26096. }
  26097. }
  26098. return result;
  26099. };
  26100. Object.defineProperty(Scene.prototype, "animatables", {
  26101. /**
  26102. * Gets all animatable attached to the scene
  26103. */
  26104. get: function () {
  26105. return this._activeAnimatables;
  26106. },
  26107. enumerable: true,
  26108. configurable: true
  26109. });
  26110. /**
  26111. * Will stop the animation of the given target
  26112. * @param target - the target
  26113. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26114. * @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)
  26115. */
  26116. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26117. var animatables = this.getAllAnimatablesByTarget(target);
  26118. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26119. var animatable = animatables_1[_i];
  26120. animatable.stop(animationName, targetMask);
  26121. }
  26122. };
  26123. /**
  26124. * Stops and removes all animations that have been applied to the scene
  26125. */
  26126. Scene.prototype.stopAllAnimations = function () {
  26127. if (this._activeAnimatables) {
  26128. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26129. this._activeAnimatables[i].stop();
  26130. }
  26131. this._activeAnimatables = [];
  26132. }
  26133. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26134. var group = _a[_i];
  26135. group.stop();
  26136. }
  26137. };
  26138. Scene.prototype._animate = function () {
  26139. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26140. return;
  26141. }
  26142. // Getting time
  26143. var now = BABYLON.Tools.Now;
  26144. if (!this._animationTimeLast) {
  26145. if (this._pendingData.length > 0) {
  26146. return;
  26147. }
  26148. this._animationTimeLast = now;
  26149. }
  26150. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26151. this._animationTime += deltaTime;
  26152. this._animationTimeLast = now;
  26153. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26154. this._activeAnimatables[index]._animate(this._animationTime);
  26155. }
  26156. // Late animation bindings
  26157. this._processLateAnimationBindings();
  26158. };
  26159. /** @hidden */
  26160. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26161. var target = runtimeAnimation.target;
  26162. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26163. if (!target._lateAnimationHolders) {
  26164. target._lateAnimationHolders = {};
  26165. }
  26166. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26167. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26168. totalWeight: 0,
  26169. animations: [],
  26170. originalValue: originalValue
  26171. };
  26172. }
  26173. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26174. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26175. };
  26176. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26177. var normalizer = 1.0;
  26178. var finalPosition = BABYLON.Tmp.Vector3[0];
  26179. var finalScaling = BABYLON.Tmp.Vector3[1];
  26180. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26181. var startIndex = 0;
  26182. var originalAnimation = holder.animations[0];
  26183. var originalValue = holder.originalValue;
  26184. var scale = 1;
  26185. if (holder.totalWeight < 1.0) {
  26186. // We need to mix the original value in
  26187. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26188. scale = 1.0 - holder.totalWeight;
  26189. }
  26190. else {
  26191. startIndex = 1;
  26192. // We need to normalize the weights
  26193. normalizer = holder.totalWeight;
  26194. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26195. scale = originalAnimation.weight / normalizer;
  26196. if (scale == 1) {
  26197. return originalAnimation.currentValue;
  26198. }
  26199. }
  26200. finalScaling.scaleInPlace(scale);
  26201. finalPosition.scaleInPlace(scale);
  26202. finalQuaternion.scaleInPlace(scale);
  26203. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26204. var runtimeAnimation = holder.animations[animIndex];
  26205. var scale = runtimeAnimation.weight / normalizer;
  26206. var currentPosition = BABYLON.Tmp.Vector3[2];
  26207. var currentScaling = BABYLON.Tmp.Vector3[3];
  26208. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26209. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26210. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26211. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26212. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26213. }
  26214. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26215. return originalAnimation._workValue;
  26216. };
  26217. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26218. var originalAnimation = holder.animations[0];
  26219. var originalValue = holder.originalValue;
  26220. if (holder.animations.length === 1) {
  26221. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26222. return refQuaternion;
  26223. }
  26224. var normalizer = 1.0;
  26225. var quaternions;
  26226. var weights;
  26227. if (holder.totalWeight < 1.0) {
  26228. var scale = 1.0 - holder.totalWeight;
  26229. quaternions = [];
  26230. weights = [];
  26231. quaternions.push(originalValue);
  26232. weights.push(scale);
  26233. }
  26234. else {
  26235. if (holder.animations.length === 2) { // Slerp as soon as we can
  26236. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26237. return refQuaternion;
  26238. }
  26239. quaternions = [];
  26240. weights = [];
  26241. normalizer = holder.totalWeight;
  26242. }
  26243. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26244. var runtimeAnimation = holder.animations[animIndex];
  26245. quaternions.push(runtimeAnimation.currentValue);
  26246. weights.push(runtimeAnimation.weight / normalizer);
  26247. }
  26248. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26249. var cumulativeAmount = 0;
  26250. var cumulativeQuaternion = null;
  26251. for (var index = 0; index < quaternions.length;) {
  26252. if (!cumulativeQuaternion) {
  26253. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26254. cumulativeQuaternion = refQuaternion;
  26255. cumulativeAmount = weights[index] + weights[index + 1];
  26256. index += 2;
  26257. continue;
  26258. }
  26259. cumulativeAmount += weights[index];
  26260. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26261. index++;
  26262. }
  26263. return cumulativeQuaternion;
  26264. };
  26265. Scene.prototype._processLateAnimationBindings = function () {
  26266. if (!this._registeredForLateAnimationBindings.length) {
  26267. return;
  26268. }
  26269. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26270. var target = this._registeredForLateAnimationBindings.data[index];
  26271. for (var path in target._lateAnimationHolders) {
  26272. var holder = target._lateAnimationHolders[path];
  26273. var originalAnimation = holder.animations[0];
  26274. var originalValue = holder.originalValue;
  26275. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26276. var finalValue = target[path];
  26277. if (matrixDecomposeMode) {
  26278. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26279. }
  26280. else {
  26281. var quaternionMode = originalValue.w !== undefined;
  26282. if (quaternionMode) {
  26283. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26284. }
  26285. else {
  26286. var startIndex = 0;
  26287. var normalizer = 1.0;
  26288. if (holder.totalWeight < 1.0) {
  26289. // We need to mix the original value in
  26290. if (originalValue.scale) {
  26291. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26292. }
  26293. else {
  26294. finalValue = originalValue * (1.0 - holder.totalWeight);
  26295. }
  26296. }
  26297. else {
  26298. // We need to normalize the weights
  26299. normalizer = holder.totalWeight;
  26300. var scale_1 = originalAnimation.weight / normalizer;
  26301. if (scale_1 !== 1) {
  26302. if (originalAnimation.currentValue.scale) {
  26303. finalValue = originalAnimation.currentValue.scale(scale_1);
  26304. }
  26305. else {
  26306. finalValue = originalAnimation.currentValue * scale_1;
  26307. }
  26308. }
  26309. else {
  26310. finalValue = originalAnimation.currentValue;
  26311. }
  26312. startIndex = 1;
  26313. }
  26314. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26315. var runtimeAnimation = holder.animations[animIndex];
  26316. var scale = runtimeAnimation.weight / normalizer;
  26317. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26318. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26319. }
  26320. else {
  26321. finalValue += runtimeAnimation.currentValue * scale;
  26322. }
  26323. }
  26324. }
  26325. }
  26326. target[path] = finalValue;
  26327. }
  26328. target._lateAnimationHolders = {};
  26329. }
  26330. this._registeredForLateAnimationBindings.reset();
  26331. };
  26332. // Matrix
  26333. /** @hidden */
  26334. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26335. this._useAlternateCameraConfiguration = active;
  26336. };
  26337. /**
  26338. * Gets the current view matrix
  26339. * @returns a Matrix
  26340. */
  26341. Scene.prototype.getViewMatrix = function () {
  26342. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26343. };
  26344. /**
  26345. * Gets the current projection matrix
  26346. * @returns a Matrix
  26347. */
  26348. Scene.prototype.getProjectionMatrix = function () {
  26349. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26350. };
  26351. /**
  26352. * Gets the current transform matrix
  26353. * @returns a Matrix made of View * Projection
  26354. */
  26355. Scene.prototype.getTransformMatrix = function () {
  26356. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26357. };
  26358. /**
  26359. * Sets the current transform matrix
  26360. * @param view defines the View matrix to use
  26361. * @param projection defines the Projection matrix to use
  26362. */
  26363. Scene.prototype.setTransformMatrix = function (view, projection) {
  26364. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26365. return;
  26366. }
  26367. this._viewUpdateFlag = view.updateFlag;
  26368. this._projectionUpdateFlag = projection.updateFlag;
  26369. this._viewMatrix = view;
  26370. this._projectionMatrix = projection;
  26371. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26372. // Update frustum
  26373. if (!this._frustumPlanes) {
  26374. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26375. }
  26376. else {
  26377. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26378. }
  26379. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26380. var otherCamera = this.activeCamera._alternateCamera;
  26381. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26382. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26383. }
  26384. if (this._sceneUbo.useUbo) {
  26385. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26386. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26387. this._sceneUbo.update();
  26388. }
  26389. };
  26390. /** @hidden */
  26391. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26392. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26393. return;
  26394. }
  26395. this._alternateViewUpdateFlag = view.updateFlag;
  26396. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26397. this._alternateViewMatrix = view;
  26398. this._alternateProjectionMatrix = projection;
  26399. if (!this._alternateTransformMatrix) {
  26400. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26401. }
  26402. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26403. if (!this._alternateSceneUbo) {
  26404. this._createAlternateUbo();
  26405. }
  26406. if (this._alternateSceneUbo.useUbo) {
  26407. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26408. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26409. this._alternateSceneUbo.update();
  26410. }
  26411. };
  26412. /**
  26413. * Gets the uniform buffer used to store scene data
  26414. * @returns a UniformBuffer
  26415. */
  26416. Scene.prototype.getSceneUniformBuffer = function () {
  26417. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26418. };
  26419. /**
  26420. * Gets an unique (relatively to the current scene) Id
  26421. * @returns an unique number for the scene
  26422. */
  26423. Scene.prototype.getUniqueId = function () {
  26424. var result = Scene._uniqueIdCounter;
  26425. Scene._uniqueIdCounter++;
  26426. return result;
  26427. };
  26428. /**
  26429. * Add a mesh to the list of scene's meshes
  26430. * @param newMesh defines the mesh to add
  26431. * @param recursive if all child meshes should also be added to the scene
  26432. */
  26433. Scene.prototype.addMesh = function (newMesh, recursive) {
  26434. var _this = this;
  26435. if (recursive === void 0) { recursive = false; }
  26436. this.meshes.push(newMesh);
  26437. //notify the collision coordinator
  26438. if (this.collisionCoordinator) {
  26439. this.collisionCoordinator.onMeshAdded(newMesh);
  26440. }
  26441. newMesh._resyncLightSources();
  26442. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26443. if (recursive) {
  26444. newMesh.getChildMeshes().forEach(function (m) {
  26445. _this.addMesh(m);
  26446. });
  26447. }
  26448. };
  26449. /**
  26450. * Remove a mesh for the list of scene's meshes
  26451. * @param toRemove defines the mesh to remove
  26452. * @param recursive if all child meshes should also be removed from the scene
  26453. * @returns the index where the mesh was in the mesh list
  26454. */
  26455. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26456. var _this = this;
  26457. if (recursive === void 0) { recursive = false; }
  26458. var index = this.meshes.indexOf(toRemove);
  26459. if (index !== -1) {
  26460. // Remove from the scene if mesh found
  26461. this.meshes.splice(index, 1);
  26462. }
  26463. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26464. if (recursive) {
  26465. toRemove.getChildMeshes().forEach(function (m) {
  26466. _this.removeMesh(m);
  26467. });
  26468. }
  26469. return index;
  26470. };
  26471. /**
  26472. * Add a transform node to the list of scene's transform nodes
  26473. * @param newTransformNode defines the transform node to add
  26474. */
  26475. Scene.prototype.addTransformNode = function (newTransformNode) {
  26476. this.transformNodes.push(newTransformNode);
  26477. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26478. };
  26479. /**
  26480. * Remove a transform node for the list of scene's transform nodes
  26481. * @param toRemove defines the transform node to remove
  26482. * @returns the index where the transform node was in the transform node list
  26483. */
  26484. Scene.prototype.removeTransformNode = function (toRemove) {
  26485. var index = this.transformNodes.indexOf(toRemove);
  26486. if (index !== -1) {
  26487. // Remove from the scene if found
  26488. this.transformNodes.splice(index, 1);
  26489. }
  26490. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26491. return index;
  26492. };
  26493. /**
  26494. * Remove a skeleton for the list of scene's skeletons
  26495. * @param toRemove defines the skeleton to remove
  26496. * @returns the index where the skeleton was in the skeleton list
  26497. */
  26498. Scene.prototype.removeSkeleton = function (toRemove) {
  26499. var index = this.skeletons.indexOf(toRemove);
  26500. if (index !== -1) {
  26501. // Remove from the scene if found
  26502. this.skeletons.splice(index, 1);
  26503. }
  26504. return index;
  26505. };
  26506. /**
  26507. * Remove a morph target for the list of scene's morph targets
  26508. * @param toRemove defines the morph target to remove
  26509. * @returns the index where the morph target was in the morph target list
  26510. */
  26511. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26512. var index = this.morphTargetManagers.indexOf(toRemove);
  26513. if (index !== -1) {
  26514. // Remove from the scene if found
  26515. this.morphTargetManagers.splice(index, 1);
  26516. }
  26517. return index;
  26518. };
  26519. /**
  26520. * Remove a light for the list of scene's lights
  26521. * @param toRemove defines the light to remove
  26522. * @returns the index where the light was in the light list
  26523. */
  26524. Scene.prototype.removeLight = function (toRemove) {
  26525. var index = this.lights.indexOf(toRemove);
  26526. if (index !== -1) {
  26527. // Remove from meshes
  26528. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26529. var mesh = _a[_i];
  26530. mesh._removeLightSource(toRemove);
  26531. }
  26532. // Remove from the scene if mesh found
  26533. this.lights.splice(index, 1);
  26534. this.sortLightsByPriority();
  26535. }
  26536. this.onLightRemovedObservable.notifyObservers(toRemove);
  26537. return index;
  26538. };
  26539. /**
  26540. * Remove a camera for the list of scene's cameras
  26541. * @param toRemove defines the camera to remove
  26542. * @returns the index where the camera was in the camera list
  26543. */
  26544. Scene.prototype.removeCamera = function (toRemove) {
  26545. var index = this.cameras.indexOf(toRemove);
  26546. if (index !== -1) {
  26547. // Remove from the scene if mesh found
  26548. this.cameras.splice(index, 1);
  26549. }
  26550. // Remove from activeCameras
  26551. var index2 = this.activeCameras.indexOf(toRemove);
  26552. if (index2 !== -1) {
  26553. // Remove from the scene if mesh found
  26554. this.activeCameras.splice(index2, 1);
  26555. }
  26556. // Reset the activeCamera
  26557. if (this.activeCamera === toRemove) {
  26558. if (this.cameras.length > 0) {
  26559. this.activeCamera = this.cameras[0];
  26560. }
  26561. else {
  26562. this.activeCamera = null;
  26563. }
  26564. }
  26565. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26566. return index;
  26567. };
  26568. /**
  26569. * Remove a particle system for the list of scene's particle systems
  26570. * @param toRemove defines the particle system to remove
  26571. * @returns the index where the particle system was in the particle system list
  26572. */
  26573. Scene.prototype.removeParticleSystem = function (toRemove) {
  26574. var index = this.particleSystems.indexOf(toRemove);
  26575. if (index !== -1) {
  26576. this.particleSystems.splice(index, 1);
  26577. }
  26578. return index;
  26579. };
  26580. /**
  26581. * Remove a animation for the list of scene's animations
  26582. * @param toRemove defines the animation to remove
  26583. * @returns the index where the animation was in the animation list
  26584. */
  26585. Scene.prototype.removeAnimation = function (toRemove) {
  26586. var index = this.animations.indexOf(toRemove);
  26587. if (index !== -1) {
  26588. this.animations.splice(index, 1);
  26589. }
  26590. return index;
  26591. };
  26592. /**
  26593. * Removes the given animation group from this scene.
  26594. * @param toRemove The animation group to remove
  26595. * @returns The index of the removed animation group
  26596. */
  26597. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26598. var index = this.animationGroups.indexOf(toRemove);
  26599. if (index !== -1) {
  26600. this.animationGroups.splice(index, 1);
  26601. }
  26602. return index;
  26603. };
  26604. /**
  26605. * Removes the given multi-material from this scene.
  26606. * @param toRemove The multi-material to remove
  26607. * @returns The index of the removed multi-material
  26608. */
  26609. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26610. var index = this.multiMaterials.indexOf(toRemove);
  26611. if (index !== -1) {
  26612. this.multiMaterials.splice(index, 1);
  26613. }
  26614. return index;
  26615. };
  26616. /**
  26617. * Removes the given material from this scene.
  26618. * @param toRemove The material to remove
  26619. * @returns The index of the removed material
  26620. */
  26621. Scene.prototype.removeMaterial = function (toRemove) {
  26622. var index = this.materials.indexOf(toRemove);
  26623. if (index !== -1) {
  26624. this.materials.splice(index, 1);
  26625. }
  26626. return index;
  26627. };
  26628. /**
  26629. * Removes the given action manager from this scene.
  26630. * @param toRemove The action manager to remove
  26631. * @returns The index of the removed action manager
  26632. */
  26633. Scene.prototype.removeActionManager = function (toRemove) {
  26634. var index = this.actionManagers.indexOf(toRemove);
  26635. if (index !== -1) {
  26636. this.actionManagers.splice(index, 1);
  26637. }
  26638. return index;
  26639. };
  26640. /**
  26641. * Removes the given texture from this scene.
  26642. * @param toRemove The texture to remove
  26643. * @returns The index of the removed texture
  26644. */
  26645. Scene.prototype.removeTexture = function (toRemove) {
  26646. var index = this.textures.indexOf(toRemove);
  26647. if (index !== -1) {
  26648. this.textures.splice(index, 1);
  26649. }
  26650. return index;
  26651. };
  26652. /**
  26653. * Adds the given light to this scene
  26654. * @param newLight The light to add
  26655. */
  26656. Scene.prototype.addLight = function (newLight) {
  26657. this.lights.push(newLight);
  26658. this.sortLightsByPriority();
  26659. // Add light to all meshes (To support if the light is removed and then readded)
  26660. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26661. var mesh = _a[_i];
  26662. if (mesh._lightSources.indexOf(newLight) === -1) {
  26663. mesh._lightSources.push(newLight);
  26664. mesh._resyncLightSources();
  26665. }
  26666. }
  26667. this.onNewLightAddedObservable.notifyObservers(newLight);
  26668. };
  26669. /**
  26670. * Sorts the list list based on light priorities
  26671. */
  26672. Scene.prototype.sortLightsByPriority = function () {
  26673. if (this.requireLightSorting) {
  26674. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26675. }
  26676. };
  26677. /**
  26678. * Adds the given camera to this scene
  26679. * @param newCamera The camera to add
  26680. */
  26681. Scene.prototype.addCamera = function (newCamera) {
  26682. this.cameras.push(newCamera);
  26683. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26684. };
  26685. /**
  26686. * Adds the given skeleton to this scene
  26687. * @param newSkeleton The skeleton to add
  26688. */
  26689. Scene.prototype.addSkeleton = function (newSkeleton) {
  26690. this.skeletons.push(newSkeleton);
  26691. };
  26692. /**
  26693. * Adds the given particle system to this scene
  26694. * @param newParticleSystem The particle system to add
  26695. */
  26696. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26697. this.particleSystems.push(newParticleSystem);
  26698. };
  26699. /**
  26700. * Adds the given animation to this scene
  26701. * @param newAnimation The animation to add
  26702. */
  26703. Scene.prototype.addAnimation = function (newAnimation) {
  26704. this.animations.push(newAnimation);
  26705. };
  26706. /**
  26707. * Adds the given animation group to this scene.
  26708. * @param newAnimationGroup The animation group to add
  26709. */
  26710. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26711. this.animationGroups.push(newAnimationGroup);
  26712. };
  26713. /**
  26714. * Adds the given multi-material to this scene
  26715. * @param newMultiMaterial The multi-material to add
  26716. */
  26717. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26718. this.multiMaterials.push(newMultiMaterial);
  26719. };
  26720. /**
  26721. * Adds the given material to this scene
  26722. * @param newMaterial The material to add
  26723. */
  26724. Scene.prototype.addMaterial = function (newMaterial) {
  26725. this.materials.push(newMaterial);
  26726. };
  26727. /**
  26728. * Adds the given morph target to this scene
  26729. * @param newMorphTargetManager The morph target to add
  26730. */
  26731. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26732. this.morphTargetManagers.push(newMorphTargetManager);
  26733. };
  26734. /**
  26735. * Adds the given geometry to this scene
  26736. * @param newGeometry The geometry to add
  26737. */
  26738. Scene.prototype.addGeometry = function (newGeometry) {
  26739. this.geometries.push(newGeometry);
  26740. };
  26741. /**
  26742. * Adds the given action manager to this scene
  26743. * @param newActionManager The action manager to add
  26744. */
  26745. Scene.prototype.addActionManager = function (newActionManager) {
  26746. this.actionManagers.push(newActionManager);
  26747. };
  26748. /**
  26749. * Adds the given texture to this scene.
  26750. * @param newTexture The texture to add
  26751. */
  26752. Scene.prototype.addTexture = function (newTexture) {
  26753. this.textures.push(newTexture);
  26754. };
  26755. /**
  26756. * Switch active camera
  26757. * @param newCamera defines the new active camera
  26758. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26759. */
  26760. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26761. if (attachControl === void 0) { attachControl = true; }
  26762. var canvas = this._engine.getRenderingCanvas();
  26763. if (!canvas) {
  26764. return;
  26765. }
  26766. if (this.activeCamera) {
  26767. this.activeCamera.detachControl(canvas);
  26768. }
  26769. this.activeCamera = newCamera;
  26770. if (attachControl) {
  26771. newCamera.attachControl(canvas);
  26772. }
  26773. };
  26774. /**
  26775. * sets the active camera of the scene using its ID
  26776. * @param id defines the camera's ID
  26777. * @return the new active camera or null if none found.
  26778. */
  26779. Scene.prototype.setActiveCameraByID = function (id) {
  26780. var camera = this.getCameraByID(id);
  26781. if (camera) {
  26782. this.activeCamera = camera;
  26783. return camera;
  26784. }
  26785. return null;
  26786. };
  26787. /**
  26788. * sets the active camera of the scene using its name
  26789. * @param name defines the camera's name
  26790. * @returns the new active camera or null if none found.
  26791. */
  26792. Scene.prototype.setActiveCameraByName = function (name) {
  26793. var camera = this.getCameraByName(name);
  26794. if (camera) {
  26795. this.activeCamera = camera;
  26796. return camera;
  26797. }
  26798. return null;
  26799. };
  26800. /**
  26801. * get an animation group using its name
  26802. * @param name defines the material's name
  26803. * @return the animation group or null if none found.
  26804. */
  26805. Scene.prototype.getAnimationGroupByName = function (name) {
  26806. for (var index = 0; index < this.animationGroups.length; index++) {
  26807. if (this.animationGroups[index].name === name) {
  26808. return this.animationGroups[index];
  26809. }
  26810. }
  26811. return null;
  26812. };
  26813. /**
  26814. * get a material using its id
  26815. * @param id defines the material's ID
  26816. * @return the material or null if none found.
  26817. */
  26818. Scene.prototype.getMaterialByID = function (id) {
  26819. for (var index = 0; index < this.materials.length; index++) {
  26820. if (this.materials[index].id === id) {
  26821. return this.materials[index];
  26822. }
  26823. }
  26824. return null;
  26825. };
  26826. /**
  26827. * Gets a material using its name
  26828. * @param name defines the material's name
  26829. * @return the material or null if none found.
  26830. */
  26831. Scene.prototype.getMaterialByName = function (name) {
  26832. for (var index = 0; index < this.materials.length; index++) {
  26833. if (this.materials[index].name === name) {
  26834. return this.materials[index];
  26835. }
  26836. }
  26837. return null;
  26838. };
  26839. /**
  26840. * Gets a camera using its id
  26841. * @param id defines the id to look for
  26842. * @returns the camera or null if not found
  26843. */
  26844. Scene.prototype.getCameraByID = function (id) {
  26845. for (var index = 0; index < this.cameras.length; index++) {
  26846. if (this.cameras[index].id === id) {
  26847. return this.cameras[index];
  26848. }
  26849. }
  26850. return null;
  26851. };
  26852. /**
  26853. * Gets a camera using its unique id
  26854. * @param uniqueId defines the unique id to look for
  26855. * @returns the camera or null if not found
  26856. */
  26857. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26858. for (var index = 0; index < this.cameras.length; index++) {
  26859. if (this.cameras[index].uniqueId === uniqueId) {
  26860. return this.cameras[index];
  26861. }
  26862. }
  26863. return null;
  26864. };
  26865. /**
  26866. * Gets a camera using its name
  26867. * @param name defines the camera's name
  26868. * @return the camera or null if none found.
  26869. */
  26870. Scene.prototype.getCameraByName = function (name) {
  26871. for (var index = 0; index < this.cameras.length; index++) {
  26872. if (this.cameras[index].name === name) {
  26873. return this.cameras[index];
  26874. }
  26875. }
  26876. return null;
  26877. };
  26878. /**
  26879. * Gets a bone using its id
  26880. * @param id defines the bone's id
  26881. * @return the bone or null if not found
  26882. */
  26883. Scene.prototype.getBoneByID = function (id) {
  26884. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26885. var skeleton = this.skeletons[skeletonIndex];
  26886. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26887. if (skeleton.bones[boneIndex].id === id) {
  26888. return skeleton.bones[boneIndex];
  26889. }
  26890. }
  26891. }
  26892. return null;
  26893. };
  26894. /**
  26895. * Gets a bone using its id
  26896. * @param name defines the bone's name
  26897. * @return the bone or null if not found
  26898. */
  26899. Scene.prototype.getBoneByName = function (name) {
  26900. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26901. var skeleton = this.skeletons[skeletonIndex];
  26902. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26903. if (skeleton.bones[boneIndex].name === name) {
  26904. return skeleton.bones[boneIndex];
  26905. }
  26906. }
  26907. }
  26908. return null;
  26909. };
  26910. /**
  26911. * Gets a light node using its name
  26912. * @param name defines the the light's name
  26913. * @return the light or null if none found.
  26914. */
  26915. Scene.prototype.getLightByName = function (name) {
  26916. for (var index = 0; index < this.lights.length; index++) {
  26917. if (this.lights[index].name === name) {
  26918. return this.lights[index];
  26919. }
  26920. }
  26921. return null;
  26922. };
  26923. /**
  26924. * Gets a light node using its id
  26925. * @param id defines the light's id
  26926. * @return the light or null if none found.
  26927. */
  26928. Scene.prototype.getLightByID = function (id) {
  26929. for (var index = 0; index < this.lights.length; index++) {
  26930. if (this.lights[index].id === id) {
  26931. return this.lights[index];
  26932. }
  26933. }
  26934. return null;
  26935. };
  26936. /**
  26937. * Gets a light node using its scene-generated unique ID
  26938. * @param uniqueId defines the light's unique id
  26939. * @return the light or null if none found.
  26940. */
  26941. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26942. for (var index = 0; index < this.lights.length; index++) {
  26943. if (this.lights[index].uniqueId === uniqueId) {
  26944. return this.lights[index];
  26945. }
  26946. }
  26947. return null;
  26948. };
  26949. /**
  26950. * Gets a particle system by id
  26951. * @param id defines the particle system id
  26952. * @return the corresponding system or null if none found
  26953. */
  26954. Scene.prototype.getParticleSystemByID = function (id) {
  26955. for (var index = 0; index < this.particleSystems.length; index++) {
  26956. if (this.particleSystems[index].id === id) {
  26957. return this.particleSystems[index];
  26958. }
  26959. }
  26960. return null;
  26961. };
  26962. /**
  26963. * Gets a geometry using its ID
  26964. * @param id defines the geometry's id
  26965. * @return the geometry or null if none found.
  26966. */
  26967. Scene.prototype.getGeometryByID = function (id) {
  26968. for (var index = 0; index < this.geometries.length; index++) {
  26969. if (this.geometries[index].id === id) {
  26970. return this.geometries[index];
  26971. }
  26972. }
  26973. return null;
  26974. };
  26975. /**
  26976. * Add a new geometry to this scene
  26977. * @param geometry defines the geometry to be added to the scene.
  26978. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26979. * @return a boolean defining if the geometry was added or not
  26980. */
  26981. Scene.prototype.pushGeometry = function (geometry, force) {
  26982. if (!force && this.getGeometryByID(geometry.id)) {
  26983. return false;
  26984. }
  26985. this.geometries.push(geometry);
  26986. //notify the collision coordinator
  26987. if (this.collisionCoordinator) {
  26988. this.collisionCoordinator.onGeometryAdded(geometry);
  26989. }
  26990. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26991. return true;
  26992. };
  26993. /**
  26994. * Removes an existing geometry
  26995. * @param geometry defines the geometry to be removed from the scene
  26996. * @return a boolean defining if the geometry was removed or not
  26997. */
  26998. Scene.prototype.removeGeometry = function (geometry) {
  26999. var index = this.geometries.indexOf(geometry);
  27000. if (index > -1) {
  27001. this.geometries.splice(index, 1);
  27002. //notify the collision coordinator
  27003. if (this.collisionCoordinator) {
  27004. this.collisionCoordinator.onGeometryDeleted(geometry);
  27005. }
  27006. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27007. return true;
  27008. }
  27009. return false;
  27010. };
  27011. /**
  27012. * Gets the list of geometries attached to the scene
  27013. * @returns an array of Geometry
  27014. */
  27015. Scene.prototype.getGeometries = function () {
  27016. return this.geometries;
  27017. };
  27018. /**
  27019. * Gets the first added mesh found of a given ID
  27020. * @param id defines the id to search for
  27021. * @return the mesh found or null if not found at all
  27022. */
  27023. Scene.prototype.getMeshByID = function (id) {
  27024. for (var index = 0; index < this.meshes.length; index++) {
  27025. if (this.meshes[index].id === id) {
  27026. return this.meshes[index];
  27027. }
  27028. }
  27029. return null;
  27030. };
  27031. /**
  27032. * Gets a list of meshes using their id
  27033. * @param id defines the id to search for
  27034. * @returns a list of meshes
  27035. */
  27036. Scene.prototype.getMeshesByID = function (id) {
  27037. return this.meshes.filter(function (m) {
  27038. return m.id === id;
  27039. });
  27040. };
  27041. /**
  27042. * Gets the first added transform node found of a given ID
  27043. * @param id defines the id to search for
  27044. * @return the found transform node or null if not found at all.
  27045. */
  27046. Scene.prototype.getTransformNodeByID = function (id) {
  27047. for (var index = 0; index < this.transformNodes.length; index++) {
  27048. if (this.transformNodes[index].id === id) {
  27049. return this.transformNodes[index];
  27050. }
  27051. }
  27052. return null;
  27053. };
  27054. /**
  27055. * Gets a list of transform nodes using their id
  27056. * @param id defines the id to search for
  27057. * @returns a list of transform nodes
  27058. */
  27059. Scene.prototype.getTransformNodesByID = function (id) {
  27060. return this.transformNodes.filter(function (m) {
  27061. return m.id === id;
  27062. });
  27063. };
  27064. /**
  27065. * Gets a mesh with its auto-generated unique id
  27066. * @param uniqueId defines the unique id to search for
  27067. * @return the found mesh or null if not found at all.
  27068. */
  27069. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27070. for (var index = 0; index < this.meshes.length; index++) {
  27071. if (this.meshes[index].uniqueId === uniqueId) {
  27072. return this.meshes[index];
  27073. }
  27074. }
  27075. return null;
  27076. };
  27077. /**
  27078. * Gets a the last added mesh using a given id
  27079. * @param id defines the id to search for
  27080. * @return the found mesh or null if not found at all.
  27081. */
  27082. Scene.prototype.getLastMeshByID = function (id) {
  27083. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27084. if (this.meshes[index].id === id) {
  27085. return this.meshes[index];
  27086. }
  27087. }
  27088. return null;
  27089. };
  27090. /**
  27091. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27092. * @param id defines the id to search for
  27093. * @return the found node or null if not found at all
  27094. */
  27095. Scene.prototype.getLastEntryByID = function (id) {
  27096. var index;
  27097. for (index = this.meshes.length - 1; index >= 0; index--) {
  27098. if (this.meshes[index].id === id) {
  27099. return this.meshes[index];
  27100. }
  27101. }
  27102. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27103. if (this.transformNodes[index].id === id) {
  27104. return this.transformNodes[index];
  27105. }
  27106. }
  27107. for (index = this.cameras.length - 1; index >= 0; index--) {
  27108. if (this.cameras[index].id === id) {
  27109. return this.cameras[index];
  27110. }
  27111. }
  27112. for (index = this.lights.length - 1; index >= 0; index--) {
  27113. if (this.lights[index].id === id) {
  27114. return this.lights[index];
  27115. }
  27116. }
  27117. return null;
  27118. };
  27119. /**
  27120. * Gets a node (Mesh, Camera, Light) using a given id
  27121. * @param id defines the id to search for
  27122. * @return the found node or null if not found at all
  27123. */
  27124. Scene.prototype.getNodeByID = function (id) {
  27125. var mesh = this.getMeshByID(id);
  27126. if (mesh) {
  27127. return mesh;
  27128. }
  27129. var light = this.getLightByID(id);
  27130. if (light) {
  27131. return light;
  27132. }
  27133. var camera = this.getCameraByID(id);
  27134. if (camera) {
  27135. return camera;
  27136. }
  27137. var bone = this.getBoneByID(id);
  27138. return bone;
  27139. };
  27140. /**
  27141. * Gets a node (Mesh, Camera, Light) using a given name
  27142. * @param name defines the name to search for
  27143. * @return the found node or null if not found at all.
  27144. */
  27145. Scene.prototype.getNodeByName = function (name) {
  27146. var mesh = this.getMeshByName(name);
  27147. if (mesh) {
  27148. return mesh;
  27149. }
  27150. var light = this.getLightByName(name);
  27151. if (light) {
  27152. return light;
  27153. }
  27154. var camera = this.getCameraByName(name);
  27155. if (camera) {
  27156. return camera;
  27157. }
  27158. var bone = this.getBoneByName(name);
  27159. return bone;
  27160. };
  27161. /**
  27162. * Gets a mesh using a given name
  27163. * @param name defines the name to search for
  27164. * @return the found mesh or null if not found at all.
  27165. */
  27166. Scene.prototype.getMeshByName = function (name) {
  27167. for (var index = 0; index < this.meshes.length; index++) {
  27168. if (this.meshes[index].name === name) {
  27169. return this.meshes[index];
  27170. }
  27171. }
  27172. return null;
  27173. };
  27174. /**
  27175. * Gets a transform node using a given name
  27176. * @param name defines the name to search for
  27177. * @return the found transform node or null if not found at all.
  27178. */
  27179. Scene.prototype.getTransformNodeByName = function (name) {
  27180. for (var index = 0; index < this.transformNodes.length; index++) {
  27181. if (this.transformNodes[index].name === name) {
  27182. return this.transformNodes[index];
  27183. }
  27184. }
  27185. return null;
  27186. };
  27187. /**
  27188. * Gets a sound using a given name
  27189. * @param name defines the name to search for
  27190. * @return the found sound or null if not found at all.
  27191. */
  27192. Scene.prototype.getSoundByName = function (name) {
  27193. var index;
  27194. if (BABYLON.AudioEngine) {
  27195. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27196. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27197. return this.mainSoundTrack.soundCollection[index];
  27198. }
  27199. }
  27200. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27201. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27202. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27203. return this.soundTracks[sdIndex].soundCollection[index];
  27204. }
  27205. }
  27206. }
  27207. }
  27208. return null;
  27209. };
  27210. /**
  27211. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27212. * @param id defines the id to search for
  27213. * @return the found skeleton or null if not found at all.
  27214. */
  27215. Scene.prototype.getLastSkeletonByID = function (id) {
  27216. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27217. if (this.skeletons[index].id === id) {
  27218. return this.skeletons[index];
  27219. }
  27220. }
  27221. return null;
  27222. };
  27223. /**
  27224. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27225. * @param id defines the id to search for
  27226. * @return the found skeleton or null if not found at all.
  27227. */
  27228. Scene.prototype.getSkeletonById = function (id) {
  27229. for (var index = 0; index < this.skeletons.length; index++) {
  27230. if (this.skeletons[index].id === id) {
  27231. return this.skeletons[index];
  27232. }
  27233. }
  27234. return null;
  27235. };
  27236. /**
  27237. * Gets a skeleton using a given name
  27238. * @param name defines the name to search for
  27239. * @return the found skeleton or null if not found at all.
  27240. */
  27241. Scene.prototype.getSkeletonByName = function (name) {
  27242. for (var index = 0; index < this.skeletons.length; index++) {
  27243. if (this.skeletons[index].name === name) {
  27244. return this.skeletons[index];
  27245. }
  27246. }
  27247. return null;
  27248. };
  27249. /**
  27250. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27251. * @param id defines the id to search for
  27252. * @return the found morph target manager or null if not found at all.
  27253. */
  27254. Scene.prototype.getMorphTargetManagerById = function (id) {
  27255. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27256. if (this.morphTargetManagers[index].uniqueId === id) {
  27257. return this.morphTargetManagers[index];
  27258. }
  27259. }
  27260. return null;
  27261. };
  27262. /**
  27263. * Gets a boolean indicating if the given mesh is active
  27264. * @param mesh defines the mesh to look for
  27265. * @returns true if the mesh is in the active list
  27266. */
  27267. Scene.prototype.isActiveMesh = function (mesh) {
  27268. return (this._activeMeshes.indexOf(mesh) !== -1);
  27269. };
  27270. Object.defineProperty(Scene.prototype, "uid", {
  27271. /**
  27272. * Return a unique id as a string which can serve as an identifier for the scene
  27273. */
  27274. get: function () {
  27275. if (!this._uid) {
  27276. this._uid = BABYLON.Tools.RandomId();
  27277. }
  27278. return this._uid;
  27279. },
  27280. enumerable: true,
  27281. configurable: true
  27282. });
  27283. /**
  27284. * Add an externaly attached data from its key.
  27285. * This method call will fail and return false, if such key already exists.
  27286. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27287. * @param key the unique key that identifies the data
  27288. * @param data the data object to associate to the key for this Engine instance
  27289. * @return true if no such key were already present and the data was added successfully, false otherwise
  27290. */
  27291. Scene.prototype.addExternalData = function (key, data) {
  27292. if (!this._externalData) {
  27293. this._externalData = new BABYLON.StringDictionary();
  27294. }
  27295. return this._externalData.add(key, data);
  27296. };
  27297. /**
  27298. * Get an externaly attached data from its key
  27299. * @param key the unique key that identifies the data
  27300. * @return the associated data, if present (can be null), or undefined if not present
  27301. */
  27302. Scene.prototype.getExternalData = function (key) {
  27303. if (!this._externalData) {
  27304. return null;
  27305. }
  27306. return this._externalData.get(key);
  27307. };
  27308. /**
  27309. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27310. * @param key the unique key that identifies the data
  27311. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27312. * @return the associated data, can be null if the factory returned null.
  27313. */
  27314. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27315. if (!this._externalData) {
  27316. this._externalData = new BABYLON.StringDictionary();
  27317. }
  27318. return this._externalData.getOrAddWithFactory(key, factory);
  27319. };
  27320. /**
  27321. * Remove an externaly attached data from the Engine instance
  27322. * @param key the unique key that identifies the data
  27323. * @return true if the data was successfully removed, false if it doesn't exist
  27324. */
  27325. Scene.prototype.removeExternalData = function (key) {
  27326. return this._externalData.remove(key);
  27327. };
  27328. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27329. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27330. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27331. var step = _a[_i];
  27332. step.action(mesh, subMesh);
  27333. }
  27334. var material = subMesh.getMaterial();
  27335. if (material !== null && material !== undefined) {
  27336. // Render targets
  27337. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27338. if (this._processedMaterials.indexOf(material) === -1) {
  27339. this._processedMaterials.push(material);
  27340. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27341. }
  27342. }
  27343. // Dispatch
  27344. this._activeIndices.addCount(subMesh.indexCount, false);
  27345. this._renderingManager.dispatch(subMesh, mesh, material);
  27346. }
  27347. }
  27348. };
  27349. /**
  27350. * Clear the processed materials smart array preventing retention point in material dispose.
  27351. */
  27352. Scene.prototype.freeProcessedMaterials = function () {
  27353. this._processedMaterials.dispose();
  27354. };
  27355. /**
  27356. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27357. */
  27358. Scene.prototype.freeActiveMeshes = function () {
  27359. this._activeMeshes.dispose();
  27360. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27361. this.activeCamera._activeMeshes.dispose();
  27362. }
  27363. if (this.activeCameras) {
  27364. for (var i = 0; i < this.activeCameras.length; i++) {
  27365. var activeCamera = this.activeCameras[i];
  27366. if (activeCamera && activeCamera._activeMeshes) {
  27367. activeCamera._activeMeshes.dispose();
  27368. }
  27369. }
  27370. }
  27371. };
  27372. /**
  27373. * Clear the info related to rendering groups preventing retention points during dispose.
  27374. */
  27375. Scene.prototype.freeRenderingGroups = function () {
  27376. if (this._renderingManager) {
  27377. this._renderingManager.freeRenderingGroups();
  27378. }
  27379. if (this.textures) {
  27380. for (var i = 0; i < this.textures.length; i++) {
  27381. var texture = this.textures[i];
  27382. if (texture && texture.renderList) {
  27383. texture.freeRenderingGroups();
  27384. }
  27385. }
  27386. }
  27387. };
  27388. /** @hidden */
  27389. Scene.prototype._isInIntermediateRendering = function () {
  27390. return this._intermediateRendering;
  27391. };
  27392. /**
  27393. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27394. * @returns the current scene
  27395. */
  27396. Scene.prototype.freezeActiveMeshes = function () {
  27397. if (!this.activeCamera) {
  27398. return this;
  27399. }
  27400. if (!this._frustumPlanes) {
  27401. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27402. }
  27403. this._evaluateActiveMeshes();
  27404. this._activeMeshesFrozen = true;
  27405. return this;
  27406. };
  27407. /**
  27408. * Use this function to restart evaluating active meshes on every frame
  27409. * @returns the current scene
  27410. */
  27411. Scene.prototype.unfreezeActiveMeshes = function () {
  27412. this._activeMeshesFrozen = false;
  27413. return this;
  27414. };
  27415. Scene.prototype._evaluateActiveMeshes = function () {
  27416. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27417. return;
  27418. }
  27419. if (!this.activeCamera) {
  27420. return;
  27421. }
  27422. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27423. this.activeCamera._activeMeshes.reset();
  27424. this._activeMeshes.reset();
  27425. this._renderingManager.reset();
  27426. this._processedMaterials.reset();
  27427. this._activeParticleSystems.reset();
  27428. this._activeSkeletons.reset();
  27429. this._softwareSkinnedMeshes.reset();
  27430. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27431. var step = _a[_i];
  27432. step.action();
  27433. }
  27434. // Determine mesh candidates
  27435. var meshes = this.getActiveMeshCandidates();
  27436. // Check each mesh
  27437. var len = meshes.length;
  27438. for (var i = 0; i < len; i++) {
  27439. var mesh = meshes.data[i];
  27440. if (mesh.isBlocked) {
  27441. continue;
  27442. }
  27443. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27444. if (!mesh.isReady() || !mesh.isEnabled()) {
  27445. continue;
  27446. }
  27447. mesh.computeWorldMatrix();
  27448. // Intersections
  27449. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27450. this._meshesForIntersections.pushNoDuplicate(mesh);
  27451. }
  27452. // Switch to current LOD
  27453. var meshLOD = mesh.getLOD(this.activeCamera);
  27454. if (meshLOD === undefined || meshLOD === null) {
  27455. continue;
  27456. }
  27457. mesh._preActivate();
  27458. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27459. this._activeMeshes.push(mesh);
  27460. this.activeCamera._activeMeshes.push(mesh);
  27461. mesh._activate(this._renderId);
  27462. if (meshLOD !== mesh) {
  27463. meshLOD._activate(this._renderId);
  27464. }
  27465. this._activeMesh(mesh, meshLOD);
  27466. }
  27467. }
  27468. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27469. // Particle systems
  27470. if (this.particlesEnabled) {
  27471. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27472. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27473. var particleSystem = this.particleSystems[particleIndex];
  27474. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27475. continue;
  27476. }
  27477. var emitter = particleSystem.emitter;
  27478. if (!emitter.position || emitter.isEnabled()) {
  27479. this._activeParticleSystems.push(particleSystem);
  27480. particleSystem.animate();
  27481. this._renderingManager.dispatchParticles(particleSystem);
  27482. }
  27483. }
  27484. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27485. }
  27486. };
  27487. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27488. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27489. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27490. mesh.skeleton.prepare();
  27491. }
  27492. if (!mesh.computeBonesUsingShaders) {
  27493. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27494. }
  27495. }
  27496. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27497. var step = _a[_i];
  27498. step.action(sourceMesh, mesh);
  27499. }
  27500. if (mesh !== undefined && mesh !== null
  27501. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27502. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27503. var len = subMeshes.length;
  27504. for (var i = 0; i < len; i++) {
  27505. var subMesh = subMeshes.data[i];
  27506. this._evaluateSubMesh(subMesh, mesh);
  27507. }
  27508. }
  27509. };
  27510. /**
  27511. * Update the transform matrix to update from the current active camera
  27512. * @param force defines a boolean used to force the update even if cache is up to date
  27513. */
  27514. Scene.prototype.updateTransformMatrix = function (force) {
  27515. if (!this.activeCamera) {
  27516. return;
  27517. }
  27518. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27519. };
  27520. /**
  27521. * 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)
  27522. * @param alternateCamera defines the camera to use
  27523. */
  27524. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27525. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27526. };
  27527. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27528. if (camera && camera._skipRendering) {
  27529. return;
  27530. }
  27531. var engine = this._engine;
  27532. this.activeCamera = camera;
  27533. if (!this.activeCamera)
  27534. throw new Error("Active camera not set");
  27535. // Viewport
  27536. engine.setViewport(this.activeCamera.viewport);
  27537. // Camera
  27538. this.resetCachedMaterial();
  27539. this._renderId++;
  27540. this.updateTransformMatrix();
  27541. if (camera._alternateCamera) {
  27542. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27543. this._alternateRendering = true;
  27544. }
  27545. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27546. // Meshes
  27547. this._evaluateActiveMeshes();
  27548. // Software skinning
  27549. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27550. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27551. mesh.applySkeleton(mesh.skeleton);
  27552. }
  27553. // Render targets
  27554. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27555. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27556. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27557. }
  27558. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27559. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27560. }
  27561. // Collects render targets from external components.
  27562. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27563. var step = _a[_i];
  27564. step.action(this._renderTargets);
  27565. }
  27566. if (this.renderTargetsEnabled) {
  27567. this._intermediateRendering = true;
  27568. if (this._renderTargets.length > 0) {
  27569. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27570. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27571. var renderTarget = this._renderTargets.data[renderIndex];
  27572. if (renderTarget._shouldRender()) {
  27573. this._renderId++;
  27574. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27575. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27576. }
  27577. }
  27578. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27579. this._renderId++;
  27580. }
  27581. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27582. var step = _c[_b];
  27583. step.action(this.activeCamera);
  27584. }
  27585. this._intermediateRendering = false;
  27586. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27587. }
  27588. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27589. // Prepare Frame
  27590. if (this.postProcessManager) {
  27591. this.postProcessManager._prepareFrame();
  27592. }
  27593. // Before Camera Draw
  27594. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27595. var step = _e[_d];
  27596. step.action(this.activeCamera);
  27597. }
  27598. // Render
  27599. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27600. this._renderingManager.render(null, null, true, true);
  27601. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27602. // After Camera Draw
  27603. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27604. var step = _g[_f];
  27605. step.action(this.activeCamera);
  27606. }
  27607. // Finalize frame
  27608. if (this.postProcessManager) {
  27609. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27610. }
  27611. // Reset some special arrays
  27612. this._renderTargets.reset();
  27613. this._alternateRendering = false;
  27614. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27615. };
  27616. Scene.prototype._processSubCameras = function (camera) {
  27617. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27618. this._renderForCamera(camera);
  27619. return;
  27620. }
  27621. // rig cameras
  27622. for (var index = 0; index < camera._rigCameras.length; index++) {
  27623. this._renderForCamera(camera._rigCameras[index], camera);
  27624. }
  27625. this.activeCamera = camera;
  27626. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27627. };
  27628. Scene.prototype._checkIntersections = function () {
  27629. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27630. var sourceMesh = this._meshesForIntersections.data[index];
  27631. if (!sourceMesh.actionManager) {
  27632. continue;
  27633. }
  27634. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27635. var action = sourceMesh.actionManager.actions[actionIndex];
  27636. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27637. var parameters = action.getTriggerParameter();
  27638. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27639. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27640. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27641. if (areIntersecting && currentIntersectionInProgress === -1) {
  27642. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27643. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27644. sourceMesh._intersectionsInProgress.push(otherMesh);
  27645. }
  27646. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27647. sourceMesh._intersectionsInProgress.push(otherMesh);
  27648. }
  27649. }
  27650. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27651. //They intersected, and now they don't.
  27652. //is this trigger an exit trigger? execute an event.
  27653. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27654. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27655. }
  27656. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27657. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27658. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27659. return otherMesh === parameterMesh;
  27660. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27661. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27662. }
  27663. }
  27664. }
  27665. }
  27666. }
  27667. };
  27668. /**
  27669. * Render the scene
  27670. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27671. */
  27672. Scene.prototype.render = function (updateCameras) {
  27673. if (updateCameras === void 0) { updateCameras = true; }
  27674. if (this.isDisposed) {
  27675. return;
  27676. }
  27677. this._frameId++;
  27678. // Register components that have been associated lately to the scene.
  27679. this._registerTransientComponents();
  27680. this._activeParticles.fetchNewFrame();
  27681. this._totalVertices.fetchNewFrame();
  27682. this._activeIndices.fetchNewFrame();
  27683. this._activeBones.fetchNewFrame();
  27684. this._meshesForIntersections.reset();
  27685. this.resetCachedMaterial();
  27686. this.onBeforeAnimationsObservable.notifyObservers(this);
  27687. // Actions
  27688. if (this.actionManager) {
  27689. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27690. }
  27691. if (this._engine.isDeterministicLockStep()) {
  27692. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27693. var defaultFPS = (60.0 / 1000.0);
  27694. var defaultFrameTime = 1000 / 60; // frame time in MS
  27695. if (this._physicsEngine) {
  27696. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27697. }
  27698. var stepsTaken = 0;
  27699. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27700. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27701. internalSteps = Math.min(internalSteps, maxSubSteps);
  27702. do {
  27703. this.onBeforeStepObservable.notifyObservers(this);
  27704. // Animations
  27705. this._animationRatio = defaultFrameTime * defaultFPS;
  27706. this._animate();
  27707. this.onAfterAnimationsObservable.notifyObservers(this);
  27708. // Physics
  27709. if (this._physicsEngine) {
  27710. this.onBeforePhysicsObservable.notifyObservers(this);
  27711. this._physicsEngine._step(defaultFrameTime / 1000);
  27712. this.onAfterPhysicsObservable.notifyObservers(this);
  27713. }
  27714. this.onAfterStepObservable.notifyObservers(this);
  27715. this._currentStepId++;
  27716. stepsTaken++;
  27717. deltaTime -= defaultFrameTime;
  27718. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27719. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27720. }
  27721. else {
  27722. // Animations
  27723. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27724. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27725. this._animate();
  27726. this.onAfterAnimationsObservable.notifyObservers(this);
  27727. // Physics
  27728. if (this._physicsEngine) {
  27729. this.onBeforePhysicsObservable.notifyObservers(this);
  27730. this._physicsEngine._step(deltaTime / 1000.0);
  27731. this.onAfterPhysicsObservable.notifyObservers(this);
  27732. }
  27733. }
  27734. // Before camera update steps
  27735. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27736. var step = _a[_i];
  27737. step.action();
  27738. }
  27739. // Update Cameras
  27740. if (updateCameras) {
  27741. if (this.activeCameras.length > 0) {
  27742. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27743. var camera = this.activeCameras[cameraIndex];
  27744. camera.update();
  27745. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27746. // rig cameras
  27747. for (var index = 0; index < camera._rigCameras.length; index++) {
  27748. camera._rigCameras[index].update();
  27749. }
  27750. }
  27751. }
  27752. }
  27753. else if (this.activeCamera) {
  27754. this.activeCamera.update();
  27755. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27756. // rig cameras
  27757. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27758. this.activeCamera._rigCameras[index].update();
  27759. }
  27760. }
  27761. }
  27762. }
  27763. // Before render
  27764. this.onBeforeRenderObservable.notifyObservers(this);
  27765. // Customs render targets
  27766. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27767. var engine = this.getEngine();
  27768. var currentActiveCamera = this.activeCamera;
  27769. if (this.renderTargetsEnabled) {
  27770. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27771. this._intermediateRendering = true;
  27772. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27773. var renderTarget = this.customRenderTargets[customIndex];
  27774. if (renderTarget._shouldRender()) {
  27775. this._renderId++;
  27776. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27777. if (!this.activeCamera)
  27778. throw new Error("Active camera not set");
  27779. // Viewport
  27780. engine.setViewport(this.activeCamera.viewport);
  27781. // Camera
  27782. this.updateTransformMatrix();
  27783. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27784. }
  27785. }
  27786. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27787. this._intermediateRendering = false;
  27788. this._renderId++;
  27789. }
  27790. // Restore back buffer
  27791. if (this.customRenderTargets.length > 0) {
  27792. engine.restoreDefaultFramebuffer();
  27793. }
  27794. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27795. this.activeCamera = currentActiveCamera;
  27796. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27797. var step = _c[_b];
  27798. step.action();
  27799. }
  27800. // Clear
  27801. if (this.autoClearDepthAndStencil || this.autoClear) {
  27802. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27803. }
  27804. // Collects render targets from external components.
  27805. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27806. var step = _e[_d];
  27807. step.action(this._renderTargets);
  27808. }
  27809. // Multi-cameras?
  27810. if (this.activeCameras.length > 0) {
  27811. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27812. if (cameraIndex > 0) {
  27813. this._engine.clear(null, false, true, true);
  27814. }
  27815. this._processSubCameras(this.activeCameras[cameraIndex]);
  27816. }
  27817. }
  27818. else {
  27819. if (!this.activeCamera) {
  27820. throw new Error("No camera defined");
  27821. }
  27822. this._processSubCameras(this.activeCamera);
  27823. }
  27824. // Intersection checks
  27825. this._checkIntersections();
  27826. // Update the audio listener attached to the camera
  27827. if (BABYLON.AudioEngine) {
  27828. this._updateAudioParameters();
  27829. }
  27830. // After render
  27831. if (this.afterRender) {
  27832. this.afterRender();
  27833. }
  27834. this.onAfterRenderObservable.notifyObservers(this);
  27835. // Cleaning
  27836. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27837. var data = this._toBeDisposed.data[index];
  27838. if (data) {
  27839. data.dispose();
  27840. }
  27841. }
  27842. this._toBeDisposed.reset();
  27843. if (this.dumpNextRenderTargets) {
  27844. this.dumpNextRenderTargets = false;
  27845. }
  27846. this._activeBones.addCount(0, true);
  27847. this._activeIndices.addCount(0, true);
  27848. this._activeParticles.addCount(0, true);
  27849. };
  27850. Scene.prototype._updateAudioParameters = function () {
  27851. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27852. return;
  27853. }
  27854. var listeningCamera;
  27855. var audioEngine = BABYLON.Engine.audioEngine;
  27856. if (this.activeCameras.length > 0) {
  27857. listeningCamera = this.activeCameras[0];
  27858. }
  27859. else {
  27860. listeningCamera = this.activeCamera;
  27861. }
  27862. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27863. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27864. // for VR cameras
  27865. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27866. listeningCamera = listeningCamera.rigCameras[0];
  27867. }
  27868. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27869. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27870. cameraDirection.normalize();
  27871. // To avoid some errors on GearVR
  27872. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27873. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27874. }
  27875. var i;
  27876. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27877. var sound = this.mainSoundTrack.soundCollection[i];
  27878. if (sound.useCustomAttenuation) {
  27879. sound.updateDistanceFromListener();
  27880. }
  27881. }
  27882. for (i = 0; i < this.soundTracks.length; i++) {
  27883. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27884. sound = this.soundTracks[i].soundCollection[j];
  27885. if (sound.useCustomAttenuation) {
  27886. sound.updateDistanceFromListener();
  27887. }
  27888. }
  27889. }
  27890. }
  27891. };
  27892. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27893. // Audio
  27894. /**
  27895. * Gets or sets if audio support is enabled
  27896. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27897. */
  27898. get: function () {
  27899. return this._audioEnabled;
  27900. },
  27901. set: function (value) {
  27902. this._audioEnabled = value;
  27903. if (BABYLON.AudioEngine) {
  27904. if (this._audioEnabled) {
  27905. this._enableAudio();
  27906. }
  27907. else {
  27908. this._disableAudio();
  27909. }
  27910. }
  27911. },
  27912. enumerable: true,
  27913. configurable: true
  27914. });
  27915. Scene.prototype._disableAudio = function () {
  27916. var i;
  27917. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27918. this.mainSoundTrack.soundCollection[i].pause();
  27919. }
  27920. for (i = 0; i < this.soundTracks.length; i++) {
  27921. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27922. this.soundTracks[i].soundCollection[j].pause();
  27923. }
  27924. }
  27925. };
  27926. Scene.prototype._enableAudio = function () {
  27927. var i;
  27928. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27929. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27930. this.mainSoundTrack.soundCollection[i].play();
  27931. }
  27932. }
  27933. for (i = 0; i < this.soundTracks.length; i++) {
  27934. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27935. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27936. this.soundTracks[i].soundCollection[j].play();
  27937. }
  27938. }
  27939. }
  27940. };
  27941. Object.defineProperty(Scene.prototype, "headphone", {
  27942. /**
  27943. * Gets or sets if audio will be output to headphones
  27944. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27945. */
  27946. get: function () {
  27947. return this._headphone;
  27948. },
  27949. set: function (value) {
  27950. this._headphone = value;
  27951. if (BABYLON.AudioEngine) {
  27952. if (this._headphone) {
  27953. this._switchAudioModeForHeadphones();
  27954. }
  27955. else {
  27956. this._switchAudioModeForNormalSpeakers();
  27957. }
  27958. }
  27959. },
  27960. enumerable: true,
  27961. configurable: true
  27962. });
  27963. Scene.prototype._switchAudioModeForHeadphones = function () {
  27964. this.mainSoundTrack.switchPanningModelToHRTF();
  27965. for (var i = 0; i < this.soundTracks.length; i++) {
  27966. this.soundTracks[i].switchPanningModelToHRTF();
  27967. }
  27968. };
  27969. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27970. this.mainSoundTrack.switchPanningModelToEqualPower();
  27971. for (var i = 0; i < this.soundTracks.length; i++) {
  27972. this.soundTracks[i].switchPanningModelToEqualPower();
  27973. }
  27974. };
  27975. /**
  27976. * Freeze all materials
  27977. * A frozen material will not be updatable but should be faster to render
  27978. */
  27979. Scene.prototype.freezeMaterials = function () {
  27980. for (var i = 0; i < this.materials.length; i++) {
  27981. this.materials[i].freeze();
  27982. }
  27983. };
  27984. /**
  27985. * Unfreeze all materials
  27986. * A frozen material will not be updatable but should be faster to render
  27987. */
  27988. Scene.prototype.unfreezeMaterials = function () {
  27989. for (var i = 0; i < this.materials.length; i++) {
  27990. this.materials[i].unfreeze();
  27991. }
  27992. };
  27993. /**
  27994. * Releases all held ressources
  27995. */
  27996. Scene.prototype.dispose = function () {
  27997. this.beforeRender = null;
  27998. this.afterRender = null;
  27999. this.skeletons = [];
  28000. this.morphTargetManagers = [];
  28001. this._transientComponents = [];
  28002. this._isReadyForMeshStage.clear();
  28003. this._beforeEvaluateActiveMeshStage.clear();
  28004. this._evaluateSubMeshStage.clear();
  28005. this._activeMeshStage.clear();
  28006. this._cameraDrawRenderTargetStage.clear();
  28007. this._beforeCameraDrawStage.clear();
  28008. this._beforeRenderingGroupDrawStage.clear();
  28009. this._beforeRenderingMeshStage.clear();
  28010. this._afterRenderingMeshStage.clear();
  28011. this._afterRenderingGroupDrawStage.clear();
  28012. this._afterCameraDrawStage.clear();
  28013. this._beforeCameraUpdateStage.clear();
  28014. this._beforeClearStage.clear();
  28015. this._gatherRenderTargetsStage.clear();
  28016. this._gatherActiveCameraRenderTargetsStage.clear();
  28017. this._pointerMoveStage.clear();
  28018. this._pointerDownStage.clear();
  28019. this._pointerUpStage.clear();
  28020. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28021. var component = _a[_i];
  28022. component.dispose();
  28023. }
  28024. this.importedMeshesFiles = new Array();
  28025. this.stopAllAnimations();
  28026. this.resetCachedMaterial();
  28027. // Smart arrays
  28028. if (this.activeCamera) {
  28029. this.activeCamera._activeMeshes.dispose();
  28030. this.activeCamera = null;
  28031. }
  28032. this._activeMeshes.dispose();
  28033. this._renderingManager.dispose();
  28034. this._processedMaterials.dispose();
  28035. this._activeParticleSystems.dispose();
  28036. this._activeSkeletons.dispose();
  28037. this._softwareSkinnedMeshes.dispose();
  28038. this._renderTargets.dispose();
  28039. this._registeredForLateAnimationBindings.dispose();
  28040. this._meshesForIntersections.dispose();
  28041. this._toBeDisposed.dispose();
  28042. // Abort active requests
  28043. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28044. var request = _c[_b];
  28045. request.abort();
  28046. }
  28047. // Events
  28048. this.onDisposeObservable.notifyObservers(this);
  28049. this.onDisposeObservable.clear();
  28050. this.onBeforeRenderObservable.clear();
  28051. this.onAfterRenderObservable.clear();
  28052. this.onBeforeRenderTargetsRenderObservable.clear();
  28053. this.onAfterRenderTargetsRenderObservable.clear();
  28054. this.onAfterStepObservable.clear();
  28055. this.onBeforeStepObservable.clear();
  28056. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28057. this.onAfterActiveMeshesEvaluationObservable.clear();
  28058. this.onBeforeParticlesRenderingObservable.clear();
  28059. this.onAfterParticlesRenderingObservable.clear();
  28060. this.onBeforeDrawPhaseObservable.clear();
  28061. this.onAfterDrawPhaseObservable.clear();
  28062. this.onBeforePhysicsObservable.clear();
  28063. this.onAfterPhysicsObservable.clear();
  28064. this.onBeforeAnimationsObservable.clear();
  28065. this.onAfterAnimationsObservable.clear();
  28066. this.onDataLoadedObservable.clear();
  28067. this.onBeforeRenderingGroupObservable.clear();
  28068. this.onAfterRenderingGroupObservable.clear();
  28069. this.onMeshImportedObservable.clear();
  28070. this.detachControl();
  28071. // Release sounds & sounds tracks
  28072. if (BABYLON.AudioEngine) {
  28073. this.disposeSounds();
  28074. }
  28075. // Detach cameras
  28076. var canvas = this._engine.getRenderingCanvas();
  28077. if (canvas) {
  28078. var index;
  28079. for (index = 0; index < this.cameras.length; index++) {
  28080. this.cameras[index].detachControl(canvas);
  28081. }
  28082. }
  28083. // Release animation groups
  28084. while (this.animationGroups.length) {
  28085. this.animationGroups[0].dispose();
  28086. }
  28087. // Release lights
  28088. while (this.lights.length) {
  28089. this.lights[0].dispose();
  28090. }
  28091. // Release meshes
  28092. while (this.meshes.length) {
  28093. this.meshes[0].dispose(true);
  28094. }
  28095. while (this.transformNodes.length) {
  28096. this.removeTransformNode(this.transformNodes[0]);
  28097. }
  28098. // Release cameras
  28099. while (this.cameras.length) {
  28100. this.cameras[0].dispose();
  28101. }
  28102. // Release materials
  28103. if (this.defaultMaterial) {
  28104. this.defaultMaterial.dispose();
  28105. }
  28106. while (this.multiMaterials.length) {
  28107. this.multiMaterials[0].dispose();
  28108. }
  28109. while (this.materials.length) {
  28110. this.materials[0].dispose();
  28111. }
  28112. // Release particles
  28113. while (this.particleSystems.length) {
  28114. this.particleSystems[0].dispose();
  28115. }
  28116. // Release postProcesses
  28117. while (this.postProcesses.length) {
  28118. this.postProcesses[0].dispose();
  28119. }
  28120. // Release textures
  28121. while (this.textures.length) {
  28122. this.textures[0].dispose();
  28123. }
  28124. // Release UBO
  28125. this._sceneUbo.dispose();
  28126. if (this._alternateSceneUbo) {
  28127. this._alternateSceneUbo.dispose();
  28128. }
  28129. // Post-processes
  28130. this.postProcessManager.dispose();
  28131. // Physics
  28132. if (this._physicsEngine) {
  28133. this.disablePhysicsEngine();
  28134. }
  28135. // Remove from engine
  28136. index = this._engine.scenes.indexOf(this);
  28137. if (index > -1) {
  28138. this._engine.scenes.splice(index, 1);
  28139. }
  28140. this._engine.wipeCaches(true);
  28141. this._isDisposed = true;
  28142. };
  28143. Object.defineProperty(Scene.prototype, "isDisposed", {
  28144. /**
  28145. * Gets if the scene is already disposed
  28146. */
  28147. get: function () {
  28148. return this._isDisposed;
  28149. },
  28150. enumerable: true,
  28151. configurable: true
  28152. });
  28153. /**
  28154. * Releases sounds & soundtracks
  28155. */
  28156. Scene.prototype.disposeSounds = function () {
  28157. if (!this._mainSoundTrack) {
  28158. return;
  28159. }
  28160. this.mainSoundTrack.dispose();
  28161. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28162. this.soundTracks[scIndex].dispose();
  28163. }
  28164. };
  28165. /**
  28166. * Call this function to reduce memory footprint of the scene.
  28167. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28168. */
  28169. Scene.prototype.clearCachedVertexData = function () {
  28170. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28171. var mesh = this.meshes[meshIndex];
  28172. var geometry = mesh.geometry;
  28173. if (geometry) {
  28174. geometry._indices = [];
  28175. for (var vbName in geometry._vertexBuffers) {
  28176. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28177. continue;
  28178. }
  28179. geometry._vertexBuffers[vbName]._buffer._data = null;
  28180. }
  28181. }
  28182. }
  28183. };
  28184. /**
  28185. * This function will remove the local cached buffer data from texture.
  28186. * It will save memory but will prevent the texture from being rebuilt
  28187. */
  28188. Scene.prototype.cleanCachedTextureBuffer = function () {
  28189. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28190. var baseTexture = _a[_i];
  28191. var buffer = baseTexture._buffer;
  28192. if (buffer) {
  28193. baseTexture._buffer = null;
  28194. }
  28195. }
  28196. };
  28197. /**
  28198. * Get the world extend vectors with an optional filter
  28199. *
  28200. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28201. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28202. */
  28203. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28204. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28205. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28206. filterPredicate = filterPredicate || (function () { return true; });
  28207. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28208. mesh.computeWorldMatrix(true);
  28209. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28210. return;
  28211. }
  28212. var boundingInfo = mesh.getBoundingInfo();
  28213. var minBox = boundingInfo.boundingBox.minimumWorld;
  28214. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28215. BABYLON.Tools.CheckExtends(minBox, min, max);
  28216. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28217. });
  28218. return {
  28219. min: min,
  28220. max: max
  28221. };
  28222. };
  28223. // Picking
  28224. /**
  28225. * Creates a ray that can be used to pick in the scene
  28226. * @param x defines the x coordinate of the origin (on-screen)
  28227. * @param y defines the y coordinate of the origin (on-screen)
  28228. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28229. * @param camera defines the camera to use for the picking
  28230. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28231. * @returns a Ray
  28232. */
  28233. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28234. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28235. var result = BABYLON.Ray.Zero();
  28236. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28237. return result;
  28238. };
  28239. /**
  28240. * Creates a ray that can be used to pick in the scene
  28241. * @param x defines the x coordinate of the origin (on-screen)
  28242. * @param y defines the y coordinate of the origin (on-screen)
  28243. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28244. * @param result defines the ray where to store the picking ray
  28245. * @param camera defines the camera to use for the picking
  28246. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28247. * @returns the current scene
  28248. */
  28249. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28250. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28251. var engine = this._engine;
  28252. if (!camera) {
  28253. if (!this.activeCamera)
  28254. throw new Error("Active camera not set");
  28255. camera = this.activeCamera;
  28256. }
  28257. var cameraViewport = camera.viewport;
  28258. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28259. // Moving coordinates to local viewport world
  28260. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28261. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28262. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28263. return this;
  28264. };
  28265. /**
  28266. * Creates a ray that can be used to pick in the scene
  28267. * @param x defines the x coordinate of the origin (on-screen)
  28268. * @param y defines the y coordinate of the origin (on-screen)
  28269. * @param camera defines the camera to use for the picking
  28270. * @returns a Ray
  28271. */
  28272. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28273. var result = BABYLON.Ray.Zero();
  28274. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28275. return result;
  28276. };
  28277. /**
  28278. * Creates a ray that can be used to pick in the scene
  28279. * @param x defines the x coordinate of the origin (on-screen)
  28280. * @param y defines the y coordinate of the origin (on-screen)
  28281. * @param result defines the ray where to store the picking ray
  28282. * @param camera defines the camera to use for the picking
  28283. * @returns the current scene
  28284. */
  28285. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28286. if (!BABYLON.PickingInfo) {
  28287. return this;
  28288. }
  28289. var engine = this._engine;
  28290. if (!camera) {
  28291. if (!this.activeCamera)
  28292. throw new Error("Active camera not set");
  28293. camera = this.activeCamera;
  28294. }
  28295. var cameraViewport = camera.viewport;
  28296. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28297. var identity = BABYLON.Matrix.Identity();
  28298. // Moving coordinates to local viewport world
  28299. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28300. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28301. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28302. return this;
  28303. };
  28304. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28305. if (!BABYLON.PickingInfo) {
  28306. return null;
  28307. }
  28308. var pickingInfo = null;
  28309. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28310. var mesh = this.meshes[meshIndex];
  28311. if (predicate) {
  28312. if (!predicate(mesh)) {
  28313. continue;
  28314. }
  28315. }
  28316. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28317. continue;
  28318. }
  28319. var world = mesh.getWorldMatrix();
  28320. var ray = rayFunction(world);
  28321. var result = mesh.intersects(ray, fastCheck);
  28322. if (!result || !result.hit)
  28323. continue;
  28324. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28325. continue;
  28326. pickingInfo = result;
  28327. if (fastCheck) {
  28328. break;
  28329. }
  28330. }
  28331. return pickingInfo || new BABYLON.PickingInfo();
  28332. };
  28333. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28334. if (!BABYLON.PickingInfo) {
  28335. return null;
  28336. }
  28337. var pickingInfos = new Array();
  28338. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28339. var mesh = this.meshes[meshIndex];
  28340. if (predicate) {
  28341. if (!predicate(mesh)) {
  28342. continue;
  28343. }
  28344. }
  28345. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28346. continue;
  28347. }
  28348. var world = mesh.getWorldMatrix();
  28349. var ray = rayFunction(world);
  28350. var result = mesh.intersects(ray, false);
  28351. if (!result || !result.hit)
  28352. continue;
  28353. pickingInfos.push(result);
  28354. }
  28355. return pickingInfos;
  28356. };
  28357. /** Launch a ray to try to pick a mesh in the scene
  28358. * @param x position on screen
  28359. * @param y position on screen
  28360. * @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
  28361. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28362. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28363. * @returns a PickingInfo
  28364. */
  28365. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28366. var _this = this;
  28367. if (!BABYLON.PickingInfo) {
  28368. return null;
  28369. }
  28370. var result = this._internalPick(function (world) {
  28371. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28372. return _this._tempPickingRay;
  28373. }, predicate, fastCheck);
  28374. if (result) {
  28375. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28376. }
  28377. return result;
  28378. };
  28379. /** Use the given ray to pick a mesh in the scene
  28380. * @param ray The ray to use to pick meshes
  28381. * @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
  28382. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28383. * @returns a PickingInfo
  28384. */
  28385. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28386. var _this = this;
  28387. var result = this._internalPick(function (world) {
  28388. if (!_this._pickWithRayInverseMatrix) {
  28389. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28390. }
  28391. world.invertToRef(_this._pickWithRayInverseMatrix);
  28392. if (!_this._cachedRayForTransform) {
  28393. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28394. }
  28395. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28396. return _this._cachedRayForTransform;
  28397. }, predicate, fastCheck);
  28398. if (result) {
  28399. result.ray = ray;
  28400. }
  28401. return result;
  28402. };
  28403. /**
  28404. * Launch a ray to try to pick a mesh in the scene
  28405. * @param x X position on screen
  28406. * @param y Y position on screen
  28407. * @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
  28408. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28409. * @returns an array of PickingInfo
  28410. */
  28411. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28412. var _this = this;
  28413. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28414. };
  28415. /**
  28416. * Launch a ray to try to pick a mesh in the scene
  28417. * @param ray Ray to use
  28418. * @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
  28419. * @returns an array of PickingInfo
  28420. */
  28421. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28422. var _this = this;
  28423. return this._internalMultiPick(function (world) {
  28424. if (!_this._pickWithRayInverseMatrix) {
  28425. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28426. }
  28427. world.invertToRef(_this._pickWithRayInverseMatrix);
  28428. if (!_this._cachedRayForTransform) {
  28429. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28430. }
  28431. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28432. return _this._cachedRayForTransform;
  28433. }, predicate);
  28434. };
  28435. /**
  28436. * Force the value of meshUnderPointer
  28437. * @param mesh defines the mesh to use
  28438. */
  28439. Scene.prototype.setPointerOverMesh = function (mesh) {
  28440. if (this._pointerOverMesh === mesh) {
  28441. return;
  28442. }
  28443. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28444. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28445. }
  28446. this._pointerOverMesh = mesh;
  28447. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28448. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28449. }
  28450. };
  28451. /**
  28452. * Gets the mesh under the pointer
  28453. * @returns a Mesh or null if no mesh is under the pointer
  28454. */
  28455. Scene.prototype.getPointerOverMesh = function () {
  28456. return this._pointerOverMesh;
  28457. };
  28458. // Physics
  28459. /**
  28460. * Gets the current physics engine
  28461. * @returns a PhysicsEngine or null if none attached
  28462. */
  28463. Scene.prototype.getPhysicsEngine = function () {
  28464. return this._physicsEngine;
  28465. };
  28466. /**
  28467. * Enables physics to the current scene
  28468. * @param gravity defines the scene's gravity for the physics engine
  28469. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28470. * @return a boolean indicating if the physics engine was initialized
  28471. */
  28472. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28473. if (gravity === void 0) { gravity = null; }
  28474. if (this._physicsEngine) {
  28475. return true;
  28476. }
  28477. try {
  28478. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28479. return true;
  28480. }
  28481. catch (e) {
  28482. BABYLON.Tools.Error(e.message);
  28483. return false;
  28484. }
  28485. };
  28486. /**
  28487. * Disables and disposes the physics engine associated with the scene
  28488. */
  28489. Scene.prototype.disablePhysicsEngine = function () {
  28490. if (!this._physicsEngine) {
  28491. return;
  28492. }
  28493. this._physicsEngine.dispose();
  28494. this._physicsEngine = null;
  28495. };
  28496. /**
  28497. * Gets a boolean indicating if there is an active physics engine
  28498. * @returns a boolean indicating if there is an active physics engine
  28499. */
  28500. Scene.prototype.isPhysicsEnabled = function () {
  28501. return this._physicsEngine !== undefined;
  28502. };
  28503. /**
  28504. * Deletes a physics compound impostor
  28505. * @param compound defines the compound to delete
  28506. */
  28507. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28508. var mesh = compound.parts[0].mesh;
  28509. if (mesh.physicsImpostor) {
  28510. mesh.physicsImpostor.dispose( /*true*/);
  28511. mesh.physicsImpostor = null;
  28512. }
  28513. };
  28514. // Misc.
  28515. /** @hidden */
  28516. Scene.prototype._rebuildGeometries = function () {
  28517. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28518. var geometry = _a[_i];
  28519. geometry._rebuild();
  28520. }
  28521. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28522. var mesh = _c[_b];
  28523. mesh._rebuild();
  28524. }
  28525. if (this.postProcessManager) {
  28526. this.postProcessManager._rebuild();
  28527. }
  28528. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28529. var component = _e[_d];
  28530. component.rebuild();
  28531. }
  28532. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28533. var system = _g[_f];
  28534. system.rebuild();
  28535. }
  28536. };
  28537. /** @hidden */
  28538. Scene.prototype._rebuildTextures = function () {
  28539. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28540. var texture = _a[_i];
  28541. texture._rebuild();
  28542. }
  28543. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28544. };
  28545. // Tags
  28546. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28547. if (tagsQuery === undefined) {
  28548. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28549. return list;
  28550. }
  28551. var listByTags = [];
  28552. forEach = forEach || (function (item) { return; });
  28553. for (var i in list) {
  28554. var item = list[i];
  28555. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28556. listByTags.push(item);
  28557. forEach(item);
  28558. }
  28559. }
  28560. return listByTags;
  28561. };
  28562. /**
  28563. * Get a list of meshes by tags
  28564. * @param tagsQuery defines the tags query to use
  28565. * @param forEach defines a predicate used to filter results
  28566. * @returns an array of Mesh
  28567. */
  28568. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28569. return this._getByTags(this.meshes, tagsQuery, forEach);
  28570. };
  28571. /**
  28572. * Get a list of cameras by tags
  28573. * @param tagsQuery defines the tags query to use
  28574. * @param forEach defines a predicate used to filter results
  28575. * @returns an array of Camera
  28576. */
  28577. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28578. return this._getByTags(this.cameras, tagsQuery, forEach);
  28579. };
  28580. /**
  28581. * Get a list of lights by tags
  28582. * @param tagsQuery defines the tags query to use
  28583. * @param forEach defines a predicate used to filter results
  28584. * @returns an array of Light
  28585. */
  28586. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28587. return this._getByTags(this.lights, tagsQuery, forEach);
  28588. };
  28589. /**
  28590. * Get a list of materials by tags
  28591. * @param tagsQuery defines the tags query to use
  28592. * @param forEach defines a predicate used to filter results
  28593. * @returns an array of Material
  28594. */
  28595. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28596. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28597. };
  28598. /**
  28599. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28600. * This allowed control for front to back rendering or reversly depending of the special needs.
  28601. *
  28602. * @param renderingGroupId The rendering group id corresponding to its index
  28603. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28604. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28605. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28606. */
  28607. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28608. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28609. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28610. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28611. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28612. };
  28613. /**
  28614. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28615. *
  28616. * @param renderingGroupId The rendering group id corresponding to its index
  28617. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28618. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28619. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28620. */
  28621. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28622. if (depth === void 0) { depth = true; }
  28623. if (stencil === void 0) { stencil = true; }
  28624. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28625. };
  28626. /**
  28627. * Gets the current auto clear configuration for one rendering group of the rendering
  28628. * manager.
  28629. * @param index the rendering group index to get the information for
  28630. * @returns The auto clear setup for the requested rendering group
  28631. */
  28632. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28633. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28634. };
  28635. /**
  28636. * Will flag all materials as dirty to trigger new shader compilation
  28637. * @param flag defines the flag used to specify which material part must be marked as dirty
  28638. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28639. */
  28640. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28641. if (this.blockMaterialDirtyMechanism) {
  28642. return;
  28643. }
  28644. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28645. var material = _a[_i];
  28646. if (predicate && !predicate(material)) {
  28647. continue;
  28648. }
  28649. material.markAsDirty(flag);
  28650. }
  28651. };
  28652. /** @hidden */
  28653. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28654. var _this = this;
  28655. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28656. this._activeRequests.push(request);
  28657. request.onCompleteObservable.add(function (request) {
  28658. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28659. });
  28660. return request;
  28661. };
  28662. /** @hidden */
  28663. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28664. var _this = this;
  28665. return new Promise(function (resolve, reject) {
  28666. _this._loadFile(url, function (data) {
  28667. resolve(data);
  28668. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28669. reject(exception);
  28670. });
  28671. });
  28672. };
  28673. // Statics
  28674. Scene._uniqueIdCounter = 0;
  28675. /** The fog is deactivated */
  28676. Scene.FOGMODE_NONE = 0;
  28677. /** The fog density is following an exponential function */
  28678. Scene.FOGMODE_EXP = 1;
  28679. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28680. Scene.FOGMODE_EXP2 = 2;
  28681. /** The fog density is following a linear function. */
  28682. Scene.FOGMODE_LINEAR = 3;
  28683. /**
  28684. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28685. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28686. */
  28687. Scene.MinDeltaTime = 1.0;
  28688. /**
  28689. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28690. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28691. */
  28692. Scene.MaxDeltaTime = 1000.0;
  28693. /** The distance in pixel that you have to move to prevent some events */
  28694. Scene.DragMovementThreshold = 10; // in pixels
  28695. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28696. Scene.LongPressDelay = 500; // in milliseconds
  28697. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28698. Scene.DoubleClickDelay = 300; // in milliseconds
  28699. /** If you need to check double click without raising a single click at first click, enable this flag */
  28700. Scene.ExclusiveDoubleClickMode = false;
  28701. return Scene;
  28702. }(BABYLON.AbstractScene));
  28703. BABYLON.Scene = Scene;
  28704. })(BABYLON || (BABYLON = {}));
  28705. //# sourceMappingURL=babylon.scene.js.map
  28706. var BABYLON;
  28707. (function (BABYLON) {
  28708. /**
  28709. * Set of assets to keep when moving a scene into an asset container.
  28710. */
  28711. var KeepAssets = /** @class */ (function (_super) {
  28712. __extends(KeepAssets, _super);
  28713. function KeepAssets() {
  28714. return _super !== null && _super.apply(this, arguments) || this;
  28715. }
  28716. return KeepAssets;
  28717. }(BABYLON.AbstractScene));
  28718. BABYLON.KeepAssets = KeepAssets;
  28719. /**
  28720. * Container with a set of assets that can be added or removed from a scene.
  28721. */
  28722. var AssetContainer = /** @class */ (function (_super) {
  28723. __extends(AssetContainer, _super);
  28724. /**
  28725. * Instantiates an AssetContainer.
  28726. * @param scene The scene the AssetContainer belongs to.
  28727. */
  28728. function AssetContainer(scene) {
  28729. var _this = _super.call(this) || this;
  28730. _this.scene = scene;
  28731. return _this;
  28732. }
  28733. /**
  28734. * Adds all the assets from the container to the scene.
  28735. */
  28736. AssetContainer.prototype.addAllToScene = function () {
  28737. var _this = this;
  28738. this.cameras.forEach(function (o) {
  28739. _this.scene.addCamera(o);
  28740. });
  28741. this.lights.forEach(function (o) {
  28742. _this.scene.addLight(o);
  28743. });
  28744. this.meshes.forEach(function (o) {
  28745. _this.scene.addMesh(o);
  28746. });
  28747. this.skeletons.forEach(function (o) {
  28748. _this.scene.addSkeleton(o);
  28749. });
  28750. this.animations.forEach(function (o) {
  28751. _this.scene.addAnimation(o);
  28752. });
  28753. this.animationGroups.forEach(function (o) {
  28754. _this.scene.addAnimationGroup(o);
  28755. });
  28756. this.multiMaterials.forEach(function (o) {
  28757. _this.scene.addMultiMaterial(o);
  28758. });
  28759. this.materials.forEach(function (o) {
  28760. _this.scene.addMaterial(o);
  28761. });
  28762. this.morphTargetManagers.forEach(function (o) {
  28763. _this.scene.addMorphTargetManager(o);
  28764. });
  28765. this.geometries.forEach(function (o) {
  28766. _this.scene.addGeometry(o);
  28767. });
  28768. this.transformNodes.forEach(function (o) {
  28769. _this.scene.addTransformNode(o);
  28770. });
  28771. this.actionManagers.forEach(function (o) {
  28772. _this.scene.addActionManager(o);
  28773. });
  28774. this.sounds.forEach(function (o) {
  28775. o.play();
  28776. o.autoplay = true;
  28777. _this.scene.mainSoundTrack.AddSound(o);
  28778. });
  28779. this.textures.forEach(function (o) {
  28780. _this.scene.addTexture(o);
  28781. });
  28782. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28783. var component = _a[_i];
  28784. component.addFromContainer(this.scene);
  28785. }
  28786. };
  28787. /**
  28788. * Removes all the assets in the container from the scene
  28789. */
  28790. AssetContainer.prototype.removeAllFromScene = function () {
  28791. var _this = this;
  28792. this.cameras.forEach(function (o) {
  28793. _this.scene.removeCamera(o);
  28794. });
  28795. this.lights.forEach(function (o) {
  28796. _this.scene.removeLight(o);
  28797. });
  28798. this.meshes.forEach(function (o) {
  28799. _this.scene.removeMesh(o);
  28800. });
  28801. this.skeletons.forEach(function (o) {
  28802. _this.scene.removeSkeleton(o);
  28803. });
  28804. this.animations.forEach(function (o) {
  28805. _this.scene.removeAnimation(o);
  28806. });
  28807. this.animationGroups.forEach(function (o) {
  28808. _this.scene.removeAnimationGroup(o);
  28809. });
  28810. this.multiMaterials.forEach(function (o) {
  28811. _this.scene.removeMultiMaterial(o);
  28812. });
  28813. this.materials.forEach(function (o) {
  28814. _this.scene.removeMaterial(o);
  28815. });
  28816. this.morphTargetManagers.forEach(function (o) {
  28817. _this.scene.removeMorphTargetManager(o);
  28818. });
  28819. this.geometries.forEach(function (o) {
  28820. _this.scene.removeGeometry(o);
  28821. });
  28822. this.transformNodes.forEach(function (o) {
  28823. _this.scene.removeTransformNode(o);
  28824. });
  28825. this.actionManagers.forEach(function (o) {
  28826. _this.scene.removeActionManager(o);
  28827. });
  28828. this.sounds.forEach(function (o) {
  28829. o.stop();
  28830. o.autoplay = false;
  28831. _this.scene.mainSoundTrack.RemoveSound(o);
  28832. });
  28833. this.textures.forEach(function (o) {
  28834. _this.scene.removeTexture(o);
  28835. });
  28836. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28837. var component = _a[_i];
  28838. component.removeFromContainer(this.scene);
  28839. }
  28840. };
  28841. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28842. if (!sourceAssets) {
  28843. return;
  28844. }
  28845. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28846. var asset = sourceAssets_1[_i];
  28847. var move = true;
  28848. if (keepAssets) {
  28849. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28850. var keepAsset = keepAssets_1[_a];
  28851. if (asset === keepAsset) {
  28852. move = false;
  28853. break;
  28854. }
  28855. }
  28856. }
  28857. if (move) {
  28858. targetAssets.push(asset);
  28859. }
  28860. }
  28861. };
  28862. /**
  28863. * Removes all the assets contained in the scene and adds them to the container.
  28864. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28865. */
  28866. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28867. if (keepAssets === undefined) {
  28868. keepAssets = new KeepAssets();
  28869. }
  28870. for (var key in this) {
  28871. if (this.hasOwnProperty(key)) {
  28872. this[key] = this[key] || [];
  28873. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28874. }
  28875. }
  28876. this.removeAllFromScene();
  28877. };
  28878. /**
  28879. * 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.
  28880. * @returns the root mesh
  28881. */
  28882. AssetContainer.prototype.createRootMesh = function () {
  28883. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28884. this.meshes.forEach(function (m) {
  28885. if (!m.parent) {
  28886. rootMesh.addChild(m);
  28887. }
  28888. });
  28889. this.meshes.unshift(rootMesh);
  28890. return rootMesh;
  28891. };
  28892. return AssetContainer;
  28893. }(BABYLON.AbstractScene));
  28894. BABYLON.AssetContainer = AssetContainer;
  28895. })(BABYLON || (BABYLON = {}));
  28896. //# sourceMappingURL=babylon.assetContainer.js.map
  28897. var BABYLON;
  28898. (function (BABYLON) {
  28899. var Buffer = /** @class */ (function () {
  28900. /**
  28901. * Constructor
  28902. * @param engine the engine
  28903. * @param data the data to use for this buffer
  28904. * @param updatable whether the data is updatable
  28905. * @param stride the stride (optional)
  28906. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28907. * @param instanced whether the buffer is instanced (optional)
  28908. * @param useBytes set to true if the stride in in bytes (optional)
  28909. */
  28910. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28911. if (stride === void 0) { stride = 0; }
  28912. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28913. if (instanced === void 0) { instanced = false; }
  28914. if (useBytes === void 0) { useBytes = false; }
  28915. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28916. this._engine = engine.getScene().getEngine();
  28917. }
  28918. else {
  28919. this._engine = engine;
  28920. }
  28921. this._updatable = updatable;
  28922. this._instanced = instanced;
  28923. this._data = data;
  28924. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28925. if (!postponeInternalCreation) { // by default
  28926. this.create();
  28927. }
  28928. }
  28929. /**
  28930. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28931. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28932. * @param offset defines offset in the buffer (0 by default)
  28933. * @param size defines the size in floats of attributes (position is 3 for instance)
  28934. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28935. * @param instanced defines if the vertex buffer contains indexed data
  28936. * @param useBytes defines if the offset and stride are in bytes
  28937. * @returns the new vertex buffer
  28938. */
  28939. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28940. if (useBytes === void 0) { useBytes = false; }
  28941. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28942. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28943. // a lot of these parameters are ignored as they are overriden by the buffer
  28944. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28945. };
  28946. // Properties
  28947. Buffer.prototype.isUpdatable = function () {
  28948. return this._updatable;
  28949. };
  28950. Buffer.prototype.getData = function () {
  28951. return this._data;
  28952. };
  28953. Buffer.prototype.getBuffer = function () {
  28954. return this._buffer;
  28955. };
  28956. /**
  28957. * Gets the stride in float32 units (i.e. byte stride / 4).
  28958. * May not be an integer if the byte stride is not divisible by 4.
  28959. * DEPRECATED. Use byteStride instead.
  28960. * @returns the stride in float32 units
  28961. */
  28962. Buffer.prototype.getStrideSize = function () {
  28963. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28964. };
  28965. // Methods
  28966. Buffer.prototype.create = function (data) {
  28967. if (data === void 0) { data = null; }
  28968. if (!data && this._buffer) {
  28969. return; // nothing to do
  28970. }
  28971. data = data || this._data;
  28972. if (!data) {
  28973. return;
  28974. }
  28975. if (!this._buffer) { // create buffer
  28976. if (this._updatable) {
  28977. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28978. this._data = data;
  28979. }
  28980. else {
  28981. this._buffer = this._engine.createVertexBuffer(data);
  28982. }
  28983. }
  28984. else if (this._updatable) { // update buffer
  28985. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28986. this._data = data;
  28987. }
  28988. };
  28989. /** @hidden */
  28990. Buffer.prototype._rebuild = function () {
  28991. this._buffer = null;
  28992. this.create(this._data);
  28993. };
  28994. Buffer.prototype.update = function (data) {
  28995. this.create(data);
  28996. };
  28997. /**
  28998. * Updates the data directly.
  28999. * @param data the new data
  29000. * @param offset the new offset
  29001. * @param vertexCount the vertex count (optional)
  29002. * @param useBytes set to true if the offset is in bytes
  29003. */
  29004. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29005. if (useBytes === void 0) { useBytes = false; }
  29006. if (!this._buffer) {
  29007. return;
  29008. }
  29009. if (this._updatable) { // update buffer
  29010. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29011. this._data = null;
  29012. }
  29013. };
  29014. Buffer.prototype.dispose = function () {
  29015. if (!this._buffer) {
  29016. return;
  29017. }
  29018. if (this._engine._releaseBuffer(this._buffer)) {
  29019. this._buffer = null;
  29020. }
  29021. };
  29022. return Buffer;
  29023. }());
  29024. BABYLON.Buffer = Buffer;
  29025. })(BABYLON || (BABYLON = {}));
  29026. //# sourceMappingURL=babylon.buffer.js.map
  29027. var BABYLON;
  29028. (function (BABYLON) {
  29029. var VertexBuffer = /** @class */ (function () {
  29030. /**
  29031. * Constructor
  29032. * @param engine the engine
  29033. * @param data the data to use for this vertex buffer
  29034. * @param kind the vertex buffer kind
  29035. * @param updatable whether the data is updatable
  29036. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29037. * @param stride the stride (optional)
  29038. * @param instanced whether the buffer is instanced (optional)
  29039. * @param offset the offset of the data (optional)
  29040. * @param size the number of components (optional)
  29041. * @param type the type of the component (optional)
  29042. * @param normalized whether the data contains normalized data (optional)
  29043. * @param useBytes set to true if stride and offset are in bytes (optional)
  29044. */
  29045. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29046. if (normalized === void 0) { normalized = false; }
  29047. if (useBytes === void 0) { useBytes = false; }
  29048. if (data instanceof BABYLON.Buffer) {
  29049. this._buffer = data;
  29050. this._ownsBuffer = false;
  29051. }
  29052. else {
  29053. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29054. this._ownsBuffer = true;
  29055. }
  29056. this._kind = kind;
  29057. if (type == undefined) {
  29058. var data_1 = this.getData();
  29059. this.type = VertexBuffer.FLOAT;
  29060. if (data_1 instanceof Int8Array)
  29061. this.type = VertexBuffer.BYTE;
  29062. else if (data_1 instanceof Uint8Array)
  29063. this.type = VertexBuffer.UNSIGNED_BYTE;
  29064. else if (data_1 instanceof Int16Array)
  29065. this.type = VertexBuffer.SHORT;
  29066. else if (data_1 instanceof Uint16Array)
  29067. this.type = VertexBuffer.UNSIGNED_SHORT;
  29068. else if (data_1 instanceof Int32Array)
  29069. this.type = VertexBuffer.INT;
  29070. else if (data_1 instanceof Uint32Array)
  29071. this.type = VertexBuffer.UNSIGNED_INT;
  29072. }
  29073. else {
  29074. this.type = type;
  29075. }
  29076. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29077. if (useBytes) {
  29078. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29079. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29080. this.byteOffset = offset || 0;
  29081. }
  29082. else {
  29083. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29084. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29085. this.byteOffset = (offset || 0) * typeByteLength;
  29086. }
  29087. this.normalized = normalized;
  29088. this._instanced = instanced !== undefined ? instanced : false;
  29089. this._instanceDivisor = instanced ? 1 : 0;
  29090. }
  29091. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29092. /**
  29093. * Gets or sets the instance divisor when in instanced mode
  29094. */
  29095. get: function () {
  29096. return this._instanceDivisor;
  29097. },
  29098. set: function (value) {
  29099. this._instanceDivisor = value;
  29100. if (value == 0) {
  29101. this._instanced = false;
  29102. }
  29103. else {
  29104. this._instanced = true;
  29105. }
  29106. },
  29107. enumerable: true,
  29108. configurable: true
  29109. });
  29110. /** @hidden */
  29111. VertexBuffer.prototype._rebuild = function () {
  29112. if (!this._buffer) {
  29113. return;
  29114. }
  29115. this._buffer._rebuild();
  29116. };
  29117. /**
  29118. * Returns the kind of the VertexBuffer (string).
  29119. */
  29120. VertexBuffer.prototype.getKind = function () {
  29121. return this._kind;
  29122. };
  29123. // Properties
  29124. /**
  29125. * Boolean : is the VertexBuffer updatable ?
  29126. */
  29127. VertexBuffer.prototype.isUpdatable = function () {
  29128. return this._buffer.isUpdatable();
  29129. };
  29130. /**
  29131. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29132. */
  29133. VertexBuffer.prototype.getData = function () {
  29134. return this._buffer.getData();
  29135. };
  29136. /**
  29137. * Returns the WebGLBuffer associated to the VertexBuffer.
  29138. */
  29139. VertexBuffer.prototype.getBuffer = function () {
  29140. return this._buffer.getBuffer();
  29141. };
  29142. /**
  29143. * Returns the stride as a multiple of the type byte length.
  29144. * DEPRECATED. Use byteStride instead.
  29145. */
  29146. VertexBuffer.prototype.getStrideSize = function () {
  29147. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29148. };
  29149. /**
  29150. * Returns the offset as a multiple of the type byte length.
  29151. * DEPRECATED. Use byteOffset instead.
  29152. */
  29153. VertexBuffer.prototype.getOffset = function () {
  29154. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29155. };
  29156. /**
  29157. * Returns the number of components per vertex attribute (integer).
  29158. */
  29159. VertexBuffer.prototype.getSize = function () {
  29160. return this._size;
  29161. };
  29162. /**
  29163. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29164. */
  29165. VertexBuffer.prototype.getIsInstanced = function () {
  29166. return this._instanced;
  29167. };
  29168. /**
  29169. * Returns the instancing divisor, zero for non-instanced (integer).
  29170. */
  29171. VertexBuffer.prototype.getInstanceDivisor = function () {
  29172. return this._instanceDivisor;
  29173. };
  29174. // Methods
  29175. /**
  29176. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29177. * Returns the created WebGLBuffer.
  29178. */
  29179. VertexBuffer.prototype.create = function (data) {
  29180. return this._buffer.create(data);
  29181. };
  29182. /**
  29183. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29184. * This function will create a new buffer if the current one is not updatable
  29185. * Returns the updated WebGLBuffer.
  29186. */
  29187. VertexBuffer.prototype.update = function (data) {
  29188. return this._buffer.update(data);
  29189. };
  29190. /**
  29191. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29192. * Returns the directly updated WebGLBuffer.
  29193. * @param data the new data
  29194. * @param offset the new offset
  29195. * @param useBytes set to true if the offset is in bytes
  29196. */
  29197. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29198. if (useBytes === void 0) { useBytes = false; }
  29199. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29200. };
  29201. /**
  29202. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29203. */
  29204. VertexBuffer.prototype.dispose = function () {
  29205. if (this._ownsBuffer) {
  29206. this._buffer.dispose();
  29207. }
  29208. };
  29209. /**
  29210. * Enumerates each value of this vertex buffer as numbers.
  29211. * @param count the number of values to enumerate
  29212. * @param callback the callback function called for each value
  29213. */
  29214. VertexBuffer.prototype.forEach = function (count, callback) {
  29215. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29216. };
  29217. Object.defineProperty(VertexBuffer, "PositionKind", {
  29218. get: function () {
  29219. return VertexBuffer._PositionKind;
  29220. },
  29221. enumerable: true,
  29222. configurable: true
  29223. });
  29224. Object.defineProperty(VertexBuffer, "NormalKind", {
  29225. get: function () {
  29226. return VertexBuffer._NormalKind;
  29227. },
  29228. enumerable: true,
  29229. configurable: true
  29230. });
  29231. Object.defineProperty(VertexBuffer, "TangentKind", {
  29232. get: function () {
  29233. return VertexBuffer._TangentKind;
  29234. },
  29235. enumerable: true,
  29236. configurable: true
  29237. });
  29238. Object.defineProperty(VertexBuffer, "UVKind", {
  29239. get: function () {
  29240. return VertexBuffer._UVKind;
  29241. },
  29242. enumerable: true,
  29243. configurable: true
  29244. });
  29245. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29246. get: function () {
  29247. return VertexBuffer._UV2Kind;
  29248. },
  29249. enumerable: true,
  29250. configurable: true
  29251. });
  29252. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29253. get: function () {
  29254. return VertexBuffer._UV3Kind;
  29255. },
  29256. enumerable: true,
  29257. configurable: true
  29258. });
  29259. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29260. get: function () {
  29261. return VertexBuffer._UV4Kind;
  29262. },
  29263. enumerable: true,
  29264. configurable: true
  29265. });
  29266. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29267. get: function () {
  29268. return VertexBuffer._UV5Kind;
  29269. },
  29270. enumerable: true,
  29271. configurable: true
  29272. });
  29273. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29274. get: function () {
  29275. return VertexBuffer._UV6Kind;
  29276. },
  29277. enumerable: true,
  29278. configurable: true
  29279. });
  29280. Object.defineProperty(VertexBuffer, "ColorKind", {
  29281. get: function () {
  29282. return VertexBuffer._ColorKind;
  29283. },
  29284. enumerable: true,
  29285. configurable: true
  29286. });
  29287. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29288. get: function () {
  29289. return VertexBuffer._MatricesIndicesKind;
  29290. },
  29291. enumerable: true,
  29292. configurable: true
  29293. });
  29294. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29295. get: function () {
  29296. return VertexBuffer._MatricesWeightsKind;
  29297. },
  29298. enumerable: true,
  29299. configurable: true
  29300. });
  29301. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29302. get: function () {
  29303. return VertexBuffer._MatricesIndicesExtraKind;
  29304. },
  29305. enumerable: true,
  29306. configurable: true
  29307. });
  29308. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29309. get: function () {
  29310. return VertexBuffer._MatricesWeightsExtraKind;
  29311. },
  29312. enumerable: true,
  29313. configurable: true
  29314. });
  29315. /**
  29316. * Deduces the stride given a kind.
  29317. * @param kind The kind string to deduce
  29318. * @returns The deduced stride
  29319. */
  29320. VertexBuffer.DeduceStride = function (kind) {
  29321. switch (kind) {
  29322. case VertexBuffer.UVKind:
  29323. case VertexBuffer.UV2Kind:
  29324. case VertexBuffer.UV3Kind:
  29325. case VertexBuffer.UV4Kind:
  29326. case VertexBuffer.UV5Kind:
  29327. case VertexBuffer.UV6Kind:
  29328. return 2;
  29329. case VertexBuffer.NormalKind:
  29330. case VertexBuffer.PositionKind:
  29331. return 3;
  29332. case VertexBuffer.ColorKind:
  29333. case VertexBuffer.MatricesIndicesKind:
  29334. case VertexBuffer.MatricesIndicesExtraKind:
  29335. case VertexBuffer.MatricesWeightsKind:
  29336. case VertexBuffer.MatricesWeightsExtraKind:
  29337. case VertexBuffer.TangentKind:
  29338. return 4;
  29339. default:
  29340. throw new Error("Invalid kind '" + kind + "'");
  29341. }
  29342. };
  29343. /**
  29344. * Gets the byte length of the given type.
  29345. * @param type the type
  29346. * @returns the number of bytes
  29347. */
  29348. VertexBuffer.GetTypeByteLength = function (type) {
  29349. switch (type) {
  29350. case VertexBuffer.BYTE:
  29351. case VertexBuffer.UNSIGNED_BYTE:
  29352. return 1;
  29353. case VertexBuffer.SHORT:
  29354. case VertexBuffer.UNSIGNED_SHORT:
  29355. return 2;
  29356. case VertexBuffer.INT:
  29357. case VertexBuffer.FLOAT:
  29358. return 4;
  29359. default:
  29360. throw new Error("Invalid type '" + type + "'");
  29361. }
  29362. };
  29363. /**
  29364. * Enumerates each value of the given parameters as numbers.
  29365. * @param data the data to enumerate
  29366. * @param byteOffset the byte offset of the data
  29367. * @param byteStride the byte stride of the data
  29368. * @param componentCount the number of components per element
  29369. * @param componentType the type of the component
  29370. * @param count the total number of components
  29371. * @param normalized whether the data is normalized
  29372. * @param callback the callback function called for each value
  29373. */
  29374. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29375. if (data instanceof Array) {
  29376. var offset = byteOffset / 4;
  29377. var stride = byteStride / 4;
  29378. for (var index = 0; index < count; index += componentCount) {
  29379. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29380. callback(data[offset + componentIndex], index + componentIndex);
  29381. }
  29382. offset += stride;
  29383. }
  29384. }
  29385. else {
  29386. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29387. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29388. for (var index = 0; index < count; index += componentCount) {
  29389. var componentByteOffset = byteOffset;
  29390. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29391. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29392. callback(value, index + componentIndex);
  29393. componentByteOffset += componentByteLength;
  29394. }
  29395. byteOffset += byteStride;
  29396. }
  29397. }
  29398. };
  29399. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29400. switch (type) {
  29401. case VertexBuffer.BYTE: {
  29402. var value = dataView.getInt8(byteOffset);
  29403. if (normalized) {
  29404. value = Math.max(value / 127, -1);
  29405. }
  29406. return value;
  29407. }
  29408. case VertexBuffer.UNSIGNED_BYTE: {
  29409. var value = dataView.getUint8(byteOffset);
  29410. if (normalized) {
  29411. value = value / 255;
  29412. }
  29413. return value;
  29414. }
  29415. case VertexBuffer.SHORT: {
  29416. var value = dataView.getInt16(byteOffset, true);
  29417. if (normalized) {
  29418. value = Math.max(value / 16383, -1);
  29419. }
  29420. return value;
  29421. }
  29422. case VertexBuffer.UNSIGNED_SHORT: {
  29423. var value = dataView.getUint16(byteOffset, true);
  29424. if (normalized) {
  29425. value = value / 65535;
  29426. }
  29427. return value;
  29428. }
  29429. case VertexBuffer.FLOAT: {
  29430. return dataView.getFloat32(byteOffset, true);
  29431. }
  29432. default: {
  29433. throw new Error("Invalid component type " + type);
  29434. }
  29435. }
  29436. };
  29437. /**
  29438. * The byte type.
  29439. */
  29440. VertexBuffer.BYTE = 5120;
  29441. /**
  29442. * The unsigned byte type.
  29443. */
  29444. VertexBuffer.UNSIGNED_BYTE = 5121;
  29445. /**
  29446. * The short type.
  29447. */
  29448. VertexBuffer.SHORT = 5122;
  29449. /**
  29450. * The unsigned short type.
  29451. */
  29452. VertexBuffer.UNSIGNED_SHORT = 5123;
  29453. /**
  29454. * The integer type.
  29455. */
  29456. VertexBuffer.INT = 5124;
  29457. /**
  29458. * The unsigned integer type.
  29459. */
  29460. VertexBuffer.UNSIGNED_INT = 5125;
  29461. /**
  29462. * The float type.
  29463. */
  29464. VertexBuffer.FLOAT = 5126;
  29465. // Enums
  29466. VertexBuffer._PositionKind = "position";
  29467. VertexBuffer._NormalKind = "normal";
  29468. VertexBuffer._TangentKind = "tangent";
  29469. VertexBuffer._UVKind = "uv";
  29470. VertexBuffer._UV2Kind = "uv2";
  29471. VertexBuffer._UV3Kind = "uv3";
  29472. VertexBuffer._UV4Kind = "uv4";
  29473. VertexBuffer._UV5Kind = "uv5";
  29474. VertexBuffer._UV6Kind = "uv6";
  29475. VertexBuffer._ColorKind = "color";
  29476. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29477. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29478. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29479. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29480. return VertexBuffer;
  29481. }());
  29482. BABYLON.VertexBuffer = VertexBuffer;
  29483. })(BABYLON || (BABYLON = {}));
  29484. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29485. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29486. var BABYLON;
  29487. (function (BABYLON) {
  29488. /**
  29489. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29490. */
  29491. var DummyInternalTextureTracker = /** @class */ (function () {
  29492. function DummyInternalTextureTracker() {
  29493. /**
  29494. * Gets or set the previous tracker in the list
  29495. */
  29496. this.previous = null;
  29497. /**
  29498. * Gets or set the next tracker in the list
  29499. */
  29500. this.next = null;
  29501. }
  29502. return DummyInternalTextureTracker;
  29503. }());
  29504. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29505. })(BABYLON || (BABYLON = {}));
  29506. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29507. var BABYLON;
  29508. (function (BABYLON) {
  29509. /**
  29510. * Class used to store data associated with WebGL texture data for the engine
  29511. * This class should not be used directly
  29512. */
  29513. var InternalTexture = /** @class */ (function () {
  29514. /**
  29515. * Creates a new InternalTexture
  29516. * @param engine defines the engine to use
  29517. * @param dataSource defines the type of data that will be used
  29518. */
  29519. function InternalTexture(engine, dataSource) {
  29520. /**
  29521. * Observable called when the texture is loaded
  29522. */
  29523. this.onLoadedObservable = new BABYLON.Observable();
  29524. /**
  29525. * Gets or set the previous tracker in the list
  29526. */
  29527. this.previous = null;
  29528. /**
  29529. * Gets or set the next tracker in the list
  29530. */
  29531. this.next = null;
  29532. // Private
  29533. /** @hidden */
  29534. this._initialSlot = -1;
  29535. /** @hidden */
  29536. this._designatedSlot = -1;
  29537. /** @hidden */
  29538. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29539. /** @hidden */
  29540. this._comparisonFunction = 0;
  29541. /** @hidden */
  29542. this._sphericalPolynomial = null;
  29543. /** @hidden */
  29544. this._lodGenerationScale = 0;
  29545. /** @hidden */
  29546. this._lodGenerationOffset = 0;
  29547. /** @hidden */
  29548. this._isRGBD = false;
  29549. /** @hidden */
  29550. this._references = 1;
  29551. this._engine = engine;
  29552. this._dataSource = dataSource;
  29553. this._webGLTexture = engine._createTexture();
  29554. }
  29555. /**
  29556. * Gets the Engine the texture belongs to.
  29557. * @returns The babylon engine
  29558. */
  29559. InternalTexture.prototype.getEngine = function () {
  29560. return this._engine;
  29561. };
  29562. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29563. /**
  29564. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29565. */
  29566. get: function () {
  29567. return this._dataSource;
  29568. },
  29569. enumerable: true,
  29570. configurable: true
  29571. });
  29572. /**
  29573. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29574. */
  29575. InternalTexture.prototype.incrementReferences = function () {
  29576. this._references++;
  29577. };
  29578. /**
  29579. * Change the size of the texture (not the size of the content)
  29580. * @param width defines the new width
  29581. * @param height defines the new height
  29582. * @param depth defines the new depth (1 by default)
  29583. */
  29584. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29585. if (depth === void 0) { depth = 1; }
  29586. this.width = width;
  29587. this.height = height;
  29588. this.depth = depth;
  29589. this.baseWidth = width;
  29590. this.baseHeight = height;
  29591. this.baseDepth = depth;
  29592. this._size = width * height * depth;
  29593. };
  29594. /** @hidden */
  29595. InternalTexture.prototype._rebuild = function () {
  29596. var _this = this;
  29597. var proxy;
  29598. this.isReady = false;
  29599. this._cachedCoordinatesMode = null;
  29600. this._cachedWrapU = null;
  29601. this._cachedWrapV = null;
  29602. this._cachedAnisotropicFilteringLevel = null;
  29603. switch (this._dataSource) {
  29604. case InternalTexture.DATASOURCE_TEMP:
  29605. return;
  29606. case InternalTexture.DATASOURCE_URL:
  29607. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29608. _this.isReady = true;
  29609. }, null, this._buffer, undefined, this.format);
  29610. proxy._swapAndDie(this);
  29611. return;
  29612. case InternalTexture.DATASOURCE_RAW:
  29613. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29614. proxy._swapAndDie(this);
  29615. this.isReady = true;
  29616. return;
  29617. case InternalTexture.DATASOURCE_RAW3D:
  29618. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29619. proxy._swapAndDie(this);
  29620. this.isReady = true;
  29621. return;
  29622. case InternalTexture.DATASOURCE_DYNAMIC:
  29623. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29624. proxy._swapAndDie(this);
  29625. // The engine will make sure to update content so no need to flag it as isReady = true
  29626. return;
  29627. case InternalTexture.DATASOURCE_RENDERTARGET:
  29628. var options = new BABYLON.RenderTargetCreationOptions();
  29629. options.generateDepthBuffer = this._generateDepthBuffer;
  29630. options.generateMipMaps = this.generateMipMaps;
  29631. options.generateStencilBuffer = this._generateStencilBuffer;
  29632. options.samplingMode = this.samplingMode;
  29633. options.type = this.type;
  29634. if (this.isCube) {
  29635. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29636. }
  29637. else {
  29638. var size = {
  29639. width: this.width,
  29640. height: this.height
  29641. };
  29642. proxy = this._engine.createRenderTargetTexture(size, options);
  29643. }
  29644. proxy._swapAndDie(this);
  29645. this.isReady = true;
  29646. return;
  29647. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29648. var depthTextureOptions = {
  29649. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29650. comparisonFunction: this._comparisonFunction,
  29651. generateStencil: this._generateStencilBuffer,
  29652. isCube: this.isCube
  29653. };
  29654. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29655. proxy._swapAndDie(this);
  29656. this.isReady = true;
  29657. return;
  29658. case InternalTexture.DATASOURCE_CUBE:
  29659. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29660. _this.isReady = true;
  29661. }, null, this.format, this._extension);
  29662. proxy._swapAndDie(this);
  29663. return;
  29664. case InternalTexture.DATASOURCE_CUBERAW:
  29665. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29666. proxy._swapAndDie(this);
  29667. this.isReady = true;
  29668. return;
  29669. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29670. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29671. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29672. _this.isReady = true;
  29673. });
  29674. proxy._swapAndDie(this);
  29675. return;
  29676. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29677. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29678. if (proxy) {
  29679. proxy._swapAndDie(_this);
  29680. }
  29681. _this.isReady = true;
  29682. }, null, this.format, this._extension);
  29683. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29684. return;
  29685. }
  29686. };
  29687. /** @hidden */
  29688. InternalTexture.prototype._swapAndDie = function (target) {
  29689. target._webGLTexture = this._webGLTexture;
  29690. if (this._framebuffer) {
  29691. target._framebuffer = this._framebuffer;
  29692. }
  29693. if (this._depthStencilBuffer) {
  29694. target._depthStencilBuffer = this._depthStencilBuffer;
  29695. }
  29696. if (this._lodTextureHigh) {
  29697. if (target._lodTextureHigh) {
  29698. target._lodTextureHigh.dispose();
  29699. }
  29700. target._lodTextureHigh = this._lodTextureHigh;
  29701. }
  29702. if (this._lodTextureMid) {
  29703. if (target._lodTextureMid) {
  29704. target._lodTextureMid.dispose();
  29705. }
  29706. target._lodTextureMid = this._lodTextureMid;
  29707. }
  29708. if (this._lodTextureLow) {
  29709. if (target._lodTextureLow) {
  29710. target._lodTextureLow.dispose();
  29711. }
  29712. target._lodTextureLow = this._lodTextureLow;
  29713. }
  29714. var cache = this._engine.getLoadedTexturesCache();
  29715. var index = cache.indexOf(this);
  29716. if (index !== -1) {
  29717. cache.splice(index, 1);
  29718. }
  29719. };
  29720. /**
  29721. * Dispose the current allocated resources
  29722. */
  29723. InternalTexture.prototype.dispose = function () {
  29724. if (!this._webGLTexture) {
  29725. return;
  29726. }
  29727. this._references--;
  29728. if (this._references === 0) {
  29729. this._engine._releaseTexture(this);
  29730. this._webGLTexture = null;
  29731. this.previous = null;
  29732. this.next = null;
  29733. }
  29734. };
  29735. /**
  29736. * The source of the texture data is unknown
  29737. */
  29738. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29739. /**
  29740. * Texture data comes from an URL
  29741. */
  29742. InternalTexture.DATASOURCE_URL = 1;
  29743. /**
  29744. * Texture data is only used for temporary storage
  29745. */
  29746. InternalTexture.DATASOURCE_TEMP = 2;
  29747. /**
  29748. * Texture data comes from raw data (ArrayBuffer)
  29749. */
  29750. InternalTexture.DATASOURCE_RAW = 3;
  29751. /**
  29752. * Texture content is dynamic (video or dynamic texture)
  29753. */
  29754. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29755. /**
  29756. * Texture content is generated by rendering to it
  29757. */
  29758. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29759. /**
  29760. * Texture content is part of a multi render target process
  29761. */
  29762. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29763. /**
  29764. * Texture data comes from a cube data file
  29765. */
  29766. InternalTexture.DATASOURCE_CUBE = 7;
  29767. /**
  29768. * Texture data comes from a raw cube data
  29769. */
  29770. InternalTexture.DATASOURCE_CUBERAW = 8;
  29771. /**
  29772. * Texture data come from a prefiltered cube data file
  29773. */
  29774. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29775. /**
  29776. * Texture content is raw 3D data
  29777. */
  29778. InternalTexture.DATASOURCE_RAW3D = 10;
  29779. /**
  29780. * Texture content is a depth texture
  29781. */
  29782. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29783. /**
  29784. * Texture data comes from a raw cube data encoded with RGBD
  29785. */
  29786. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29787. return InternalTexture;
  29788. }());
  29789. BABYLON.InternalTexture = InternalTexture;
  29790. })(BABYLON || (BABYLON = {}));
  29791. //# sourceMappingURL=babylon.internalTexture.js.map
  29792. var BABYLON;
  29793. (function (BABYLON) {
  29794. var BaseTexture = /** @class */ (function () {
  29795. function BaseTexture(scene) {
  29796. this._hasAlpha = false;
  29797. this.getAlphaFromRGB = false;
  29798. this.level = 1;
  29799. this.coordinatesIndex = 0;
  29800. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29801. /**
  29802. * | Value | Type | Description |
  29803. * | ----- | ------------------ | ----------- |
  29804. * | 0 | CLAMP_ADDRESSMODE | |
  29805. * | 1 | WRAP_ADDRESSMODE | |
  29806. * | 2 | MIRROR_ADDRESSMODE | |
  29807. */
  29808. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29809. /**
  29810. * | Value | Type | Description |
  29811. * | ----- | ------------------ | ----------- |
  29812. * | 0 | CLAMP_ADDRESSMODE | |
  29813. * | 1 | WRAP_ADDRESSMODE | |
  29814. * | 2 | MIRROR_ADDRESSMODE | |
  29815. */
  29816. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29817. /**
  29818. * | Value | Type | Description |
  29819. * | ----- | ------------------ | ----------- |
  29820. * | 0 | CLAMP_ADDRESSMODE | |
  29821. * | 1 | WRAP_ADDRESSMODE | |
  29822. * | 2 | MIRROR_ADDRESSMODE | |
  29823. */
  29824. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29825. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29826. this.isCube = false;
  29827. this.is3D = false;
  29828. this.gammaSpace = true;
  29829. this.invertZ = false;
  29830. this.lodLevelInAlpha = false;
  29831. this.isRenderTarget = false;
  29832. this.animations = new Array();
  29833. /**
  29834. * An event triggered when the texture is disposed.
  29835. */
  29836. this.onDisposeObservable = new BABYLON.Observable();
  29837. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29838. this._cachedSize = BABYLON.Size.Zero();
  29839. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29840. if (this._scene) {
  29841. this._scene.textures.push(this);
  29842. }
  29843. this._uid = null;
  29844. }
  29845. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29846. get: function () {
  29847. return this._hasAlpha;
  29848. },
  29849. set: function (value) {
  29850. if (this._hasAlpha === value) {
  29851. return;
  29852. }
  29853. this._hasAlpha = value;
  29854. if (this._scene) {
  29855. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29856. }
  29857. },
  29858. enumerable: true,
  29859. configurable: true
  29860. });
  29861. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29862. get: function () {
  29863. return this._coordinatesMode;
  29864. },
  29865. /**
  29866. * How a texture is mapped.
  29867. *
  29868. * | Value | Type | Description |
  29869. * | ----- | ----------------------------------- | ----------- |
  29870. * | 0 | EXPLICIT_MODE | |
  29871. * | 1 | SPHERICAL_MODE | |
  29872. * | 2 | PLANAR_MODE | |
  29873. * | 3 | CUBIC_MODE | |
  29874. * | 4 | PROJECTION_MODE | |
  29875. * | 5 | SKYBOX_MODE | |
  29876. * | 6 | INVCUBIC_MODE | |
  29877. * | 7 | EQUIRECTANGULAR_MODE | |
  29878. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29879. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29880. */
  29881. set: function (value) {
  29882. if (this._coordinatesMode === value) {
  29883. return;
  29884. }
  29885. this._coordinatesMode = value;
  29886. if (this._scene) {
  29887. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29888. }
  29889. },
  29890. enumerable: true,
  29891. configurable: true
  29892. });
  29893. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29894. /**
  29895. * Gets whether or not the texture contains RGBD data.
  29896. */
  29897. get: function () {
  29898. return this._texture != null && this._texture._isRGBD;
  29899. },
  29900. enumerable: true,
  29901. configurable: true
  29902. });
  29903. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29904. get: function () {
  29905. if (this._texture)
  29906. return this._texture._lodGenerationOffset;
  29907. return 0.0;
  29908. },
  29909. set: function (value) {
  29910. if (this._texture)
  29911. this._texture._lodGenerationOffset = value;
  29912. },
  29913. enumerable: true,
  29914. configurable: true
  29915. });
  29916. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29917. get: function () {
  29918. if (this._texture)
  29919. return this._texture._lodGenerationScale;
  29920. return 0.0;
  29921. },
  29922. set: function (value) {
  29923. if (this._texture)
  29924. this._texture._lodGenerationScale = value;
  29925. },
  29926. enumerable: true,
  29927. configurable: true
  29928. });
  29929. Object.defineProperty(BaseTexture.prototype, "uid", {
  29930. get: function () {
  29931. if (!this._uid) {
  29932. this._uid = BABYLON.Tools.RandomId();
  29933. }
  29934. return this._uid;
  29935. },
  29936. enumerable: true,
  29937. configurable: true
  29938. });
  29939. BaseTexture.prototype.toString = function () {
  29940. return this.name;
  29941. };
  29942. BaseTexture.prototype.getClassName = function () {
  29943. return "BaseTexture";
  29944. };
  29945. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29946. set: function (callback) {
  29947. if (this._onDisposeObserver) {
  29948. this.onDisposeObservable.remove(this._onDisposeObserver);
  29949. }
  29950. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29951. },
  29952. enumerable: true,
  29953. configurable: true
  29954. });
  29955. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29956. get: function () {
  29957. return true;
  29958. },
  29959. enumerable: true,
  29960. configurable: true
  29961. });
  29962. BaseTexture.prototype.getScene = function () {
  29963. return this._scene;
  29964. };
  29965. BaseTexture.prototype.getTextureMatrix = function () {
  29966. return BABYLON.Matrix.IdentityReadOnly;
  29967. };
  29968. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29969. return BABYLON.Matrix.IdentityReadOnly;
  29970. };
  29971. BaseTexture.prototype.getInternalTexture = function () {
  29972. return this._texture;
  29973. };
  29974. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29975. return !this.isBlocking || this.isReady();
  29976. };
  29977. BaseTexture.prototype.isReady = function () {
  29978. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29979. this.delayLoad();
  29980. return false;
  29981. }
  29982. if (this._texture) {
  29983. return this._texture.isReady;
  29984. }
  29985. return false;
  29986. };
  29987. BaseTexture.prototype.getSize = function () {
  29988. if (this._texture) {
  29989. if (this._texture.width) {
  29990. this._cachedSize.width = this._texture.width;
  29991. this._cachedSize.height = this._texture.height;
  29992. return this._cachedSize;
  29993. }
  29994. if (this._texture._size) {
  29995. this._cachedSize.width = this._texture._size;
  29996. this._cachedSize.height = this._texture._size;
  29997. return this._cachedSize;
  29998. }
  29999. }
  30000. return this._cachedSize;
  30001. };
  30002. BaseTexture.prototype.getBaseSize = function () {
  30003. if (!this.isReady() || !this._texture)
  30004. return BABYLON.Size.Zero();
  30005. if (this._texture._size) {
  30006. return new BABYLON.Size(this._texture._size, this._texture._size);
  30007. }
  30008. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30009. };
  30010. BaseTexture.prototype.scale = function (ratio) {
  30011. };
  30012. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30013. get: function () {
  30014. return false;
  30015. },
  30016. enumerable: true,
  30017. configurable: true
  30018. });
  30019. /** @hidden */
  30020. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30021. if (!this._scene) {
  30022. return null;
  30023. }
  30024. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30025. for (var index = 0; index < texturesCache.length; index++) {
  30026. var texturesCacheEntry = texturesCache[index];
  30027. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30028. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30029. texturesCacheEntry.incrementReferences();
  30030. return texturesCacheEntry;
  30031. }
  30032. }
  30033. }
  30034. return null;
  30035. };
  30036. /** @hidden */
  30037. BaseTexture.prototype._rebuild = function () {
  30038. };
  30039. BaseTexture.prototype.delayLoad = function () {
  30040. };
  30041. BaseTexture.prototype.clone = function () {
  30042. return null;
  30043. };
  30044. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30045. get: function () {
  30046. if (!this._texture) {
  30047. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30048. }
  30049. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30050. },
  30051. enumerable: true,
  30052. configurable: true
  30053. });
  30054. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30055. get: function () {
  30056. if (!this._texture) {
  30057. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30058. }
  30059. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30060. },
  30061. enumerable: true,
  30062. configurable: true
  30063. });
  30064. /**
  30065. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30066. * This will returns an RGBA array buffer containing either in values (0-255) or
  30067. * float values (0-1) depending of the underlying buffer type.
  30068. * @param faceIndex The face of the texture to read (in case of cube texture)
  30069. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30070. * @returns The Array buffer containing the pixels data.
  30071. */
  30072. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30073. if (faceIndex === void 0) { faceIndex = 0; }
  30074. if (level === void 0) { level = 0; }
  30075. if (!this._texture) {
  30076. return null;
  30077. }
  30078. var size = this.getSize();
  30079. var width = size.width;
  30080. var height = size.height;
  30081. var scene = this.getScene();
  30082. if (!scene) {
  30083. return null;
  30084. }
  30085. var engine = scene.getEngine();
  30086. if (level != 0) {
  30087. width = width / Math.pow(2, level);
  30088. height = height / Math.pow(2, level);
  30089. width = Math.round(width);
  30090. height = Math.round(height);
  30091. }
  30092. if (this._texture.isCube) {
  30093. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30094. }
  30095. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30096. };
  30097. BaseTexture.prototype.releaseInternalTexture = function () {
  30098. if (this._texture) {
  30099. this._texture.dispose();
  30100. this._texture = null;
  30101. }
  30102. };
  30103. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30104. get: function () {
  30105. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30106. return null;
  30107. }
  30108. if (!this._texture._sphericalPolynomial) {
  30109. this._texture._sphericalPolynomial =
  30110. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30111. }
  30112. return this._texture._sphericalPolynomial;
  30113. },
  30114. set: function (value) {
  30115. if (this._texture) {
  30116. this._texture._sphericalPolynomial = value;
  30117. }
  30118. },
  30119. enumerable: true,
  30120. configurable: true
  30121. });
  30122. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30123. get: function () {
  30124. if (this._texture) {
  30125. return this._texture._lodTextureHigh;
  30126. }
  30127. return null;
  30128. },
  30129. enumerable: true,
  30130. configurable: true
  30131. });
  30132. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30133. get: function () {
  30134. if (this._texture) {
  30135. return this._texture._lodTextureMid;
  30136. }
  30137. return null;
  30138. },
  30139. enumerable: true,
  30140. configurable: true
  30141. });
  30142. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30143. get: function () {
  30144. if (this._texture) {
  30145. return this._texture._lodTextureLow;
  30146. }
  30147. return null;
  30148. },
  30149. enumerable: true,
  30150. configurable: true
  30151. });
  30152. BaseTexture.prototype.dispose = function () {
  30153. if (!this._scene) {
  30154. return;
  30155. }
  30156. // Animations
  30157. this._scene.stopAnimation(this);
  30158. // Remove from scene
  30159. this._scene._removePendingData(this);
  30160. var index = this._scene.textures.indexOf(this);
  30161. if (index >= 0) {
  30162. this._scene.textures.splice(index, 1);
  30163. }
  30164. if (this._texture === undefined) {
  30165. return;
  30166. }
  30167. // Release
  30168. this.releaseInternalTexture();
  30169. // Callback
  30170. this.onDisposeObservable.notifyObservers(this);
  30171. this.onDisposeObservable.clear();
  30172. };
  30173. BaseTexture.prototype.serialize = function () {
  30174. if (!this.name) {
  30175. return null;
  30176. }
  30177. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30178. // Animations
  30179. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30180. return serializationObject;
  30181. };
  30182. BaseTexture.WhenAllReady = function (textures, callback) {
  30183. var numRemaining = textures.length;
  30184. if (numRemaining === 0) {
  30185. callback();
  30186. return;
  30187. }
  30188. var _loop_1 = function () {
  30189. texture = textures[i];
  30190. if (texture.isReady()) {
  30191. if (--numRemaining === 0) {
  30192. callback();
  30193. }
  30194. }
  30195. else {
  30196. onLoadObservable = texture.onLoadObservable;
  30197. var onLoadCallback_1 = function () {
  30198. onLoadObservable.removeCallback(onLoadCallback_1);
  30199. if (--numRemaining === 0) {
  30200. callback();
  30201. }
  30202. };
  30203. onLoadObservable.add(onLoadCallback_1);
  30204. }
  30205. };
  30206. var texture, onLoadObservable;
  30207. for (var i = 0; i < textures.length; i++) {
  30208. _loop_1();
  30209. }
  30210. };
  30211. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30212. __decorate([
  30213. BABYLON.serialize()
  30214. ], BaseTexture.prototype, "name", void 0);
  30215. __decorate([
  30216. BABYLON.serialize("hasAlpha")
  30217. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30218. __decorate([
  30219. BABYLON.serialize()
  30220. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30221. __decorate([
  30222. BABYLON.serialize()
  30223. ], BaseTexture.prototype, "level", void 0);
  30224. __decorate([
  30225. BABYLON.serialize()
  30226. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30227. __decorate([
  30228. BABYLON.serialize("coordinatesMode")
  30229. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30230. __decorate([
  30231. BABYLON.serialize()
  30232. ], BaseTexture.prototype, "wrapU", void 0);
  30233. __decorate([
  30234. BABYLON.serialize()
  30235. ], BaseTexture.prototype, "wrapV", void 0);
  30236. __decorate([
  30237. BABYLON.serialize()
  30238. ], BaseTexture.prototype, "wrapR", void 0);
  30239. __decorate([
  30240. BABYLON.serialize()
  30241. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30242. __decorate([
  30243. BABYLON.serialize()
  30244. ], BaseTexture.prototype, "isCube", void 0);
  30245. __decorate([
  30246. BABYLON.serialize()
  30247. ], BaseTexture.prototype, "is3D", void 0);
  30248. __decorate([
  30249. BABYLON.serialize()
  30250. ], BaseTexture.prototype, "gammaSpace", void 0);
  30251. __decorate([
  30252. BABYLON.serialize()
  30253. ], BaseTexture.prototype, "invertZ", void 0);
  30254. __decorate([
  30255. BABYLON.serialize()
  30256. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30257. __decorate([
  30258. BABYLON.serialize()
  30259. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30260. __decorate([
  30261. BABYLON.serialize()
  30262. ], BaseTexture.prototype, "lodGenerationScale", null);
  30263. __decorate([
  30264. BABYLON.serialize()
  30265. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30266. return BaseTexture;
  30267. }());
  30268. BABYLON.BaseTexture = BaseTexture;
  30269. })(BABYLON || (BABYLON = {}));
  30270. //# sourceMappingURL=babylon.baseTexture.js.map
  30271. var BABYLON;
  30272. (function (BABYLON) {
  30273. var Texture = /** @class */ (function (_super) {
  30274. __extends(Texture, _super);
  30275. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30276. if (noMipmap === void 0) { noMipmap = false; }
  30277. if (invertY === void 0) { invertY = true; }
  30278. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30279. if (onLoad === void 0) { onLoad = null; }
  30280. if (onError === void 0) { onError = null; }
  30281. if (buffer === void 0) { buffer = null; }
  30282. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30283. var _this = _super.call(this, scene) || this;
  30284. _this.uOffset = 0;
  30285. _this.vOffset = 0;
  30286. _this.uScale = 1.0;
  30287. _this.vScale = 1.0;
  30288. _this.uAng = 0;
  30289. _this.vAng = 0;
  30290. _this.wAng = 0;
  30291. /**
  30292. * Defines the center of rotation (U)
  30293. */
  30294. _this.uRotationCenter = 0.5;
  30295. /**
  30296. * Defines the center of rotation (V)
  30297. */
  30298. _this.vRotationCenter = 0.5;
  30299. /**
  30300. * Defines the center of rotation (W)
  30301. */
  30302. _this.wRotationCenter = 0.5;
  30303. _this._isBlocking = true;
  30304. _this.name = url || "";
  30305. _this.url = url;
  30306. _this._noMipmap = noMipmap;
  30307. _this._invertY = invertY;
  30308. _this._samplingMode = samplingMode;
  30309. _this._buffer = buffer;
  30310. _this._deleteBuffer = deleteBuffer;
  30311. if (format) {
  30312. _this._format = format;
  30313. }
  30314. scene = _this.getScene();
  30315. if (!scene) {
  30316. return _this;
  30317. }
  30318. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30319. var load = function () {
  30320. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30321. _this.onLoadObservable.notifyObservers(_this);
  30322. }
  30323. if (onLoad) {
  30324. onLoad();
  30325. }
  30326. if (!_this.isBlocking && scene) {
  30327. scene.resetCachedMaterial();
  30328. }
  30329. };
  30330. if (!_this.url) {
  30331. _this._delayedOnLoad = load;
  30332. _this._delayedOnError = onError;
  30333. return _this;
  30334. }
  30335. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30336. if (!_this._texture) {
  30337. if (!scene.useDelayedTextureLoading) {
  30338. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30339. if (deleteBuffer) {
  30340. delete _this._buffer;
  30341. }
  30342. }
  30343. else {
  30344. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30345. _this._delayedOnLoad = load;
  30346. _this._delayedOnError = onError;
  30347. }
  30348. }
  30349. else {
  30350. if (_this._texture.isReady) {
  30351. BABYLON.Tools.SetImmediate(function () { return load(); });
  30352. }
  30353. else {
  30354. _this._texture.onLoadedObservable.add(load);
  30355. }
  30356. }
  30357. return _this;
  30358. }
  30359. Object.defineProperty(Texture.prototype, "noMipmap", {
  30360. get: function () {
  30361. return this._noMipmap;
  30362. },
  30363. enumerable: true,
  30364. configurable: true
  30365. });
  30366. Object.defineProperty(Texture.prototype, "isBlocking", {
  30367. get: function () {
  30368. return this._isBlocking;
  30369. },
  30370. set: function (value) {
  30371. this._isBlocking = value;
  30372. },
  30373. enumerable: true,
  30374. configurable: true
  30375. });
  30376. Object.defineProperty(Texture.prototype, "samplingMode", {
  30377. get: function () {
  30378. return this._samplingMode;
  30379. },
  30380. enumerable: true,
  30381. configurable: true
  30382. });
  30383. /**
  30384. * Update the url (and optional buffer) of this texture if url was null during construction.
  30385. * @param url the url of the texture
  30386. * @param buffer the buffer of the texture (defaults to null)
  30387. */
  30388. Texture.prototype.updateURL = function (url, buffer) {
  30389. if (buffer === void 0) { buffer = null; }
  30390. if (this.url) {
  30391. throw new Error("URL is already set");
  30392. }
  30393. this.url = url;
  30394. this._buffer = buffer;
  30395. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30396. this.delayLoad();
  30397. };
  30398. Texture.prototype.delayLoad = function () {
  30399. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30400. return;
  30401. }
  30402. var scene = this.getScene();
  30403. if (!scene) {
  30404. return;
  30405. }
  30406. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30407. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30408. if (!this._texture) {
  30409. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30410. if (this._deleteBuffer) {
  30411. delete this._buffer;
  30412. }
  30413. }
  30414. else {
  30415. if (this._delayedOnLoad) {
  30416. if (this._texture.isReady) {
  30417. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30418. }
  30419. else {
  30420. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30421. }
  30422. }
  30423. }
  30424. this._delayedOnLoad = null;
  30425. this._delayedOnError = null;
  30426. };
  30427. /**
  30428. * Default is Trilinear mode.
  30429. *
  30430. * | Value | Type | Description |
  30431. * | ----- | ------------------ | ----------- |
  30432. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30433. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30434. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30435. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30436. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30437. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30438. * | 7 | NEAREST_LINEAR | |
  30439. * | 8 | NEAREST_NEAREST | |
  30440. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30441. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30442. * | 11 | LINEAR_LINEAR | |
  30443. * | 12 | LINEAR_NEAREST | |
  30444. *
  30445. * > _mag_: magnification filter (close to the viewer)
  30446. * > _min_: minification filter (far from the viewer)
  30447. * > _mip_: filter used between mip map levels
  30448. *
  30449. */
  30450. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30451. if (!this._texture) {
  30452. return;
  30453. }
  30454. var scene = this.getScene();
  30455. if (!scene) {
  30456. return;
  30457. }
  30458. this._samplingMode = samplingMode;
  30459. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30460. };
  30461. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30462. x *= this.uScale;
  30463. y *= this.vScale;
  30464. x -= this.uRotationCenter * this.uScale;
  30465. y -= this.vRotationCenter * this.vScale;
  30466. z -= this.wRotationCenter;
  30467. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30468. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30469. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30470. t.z += this.wRotationCenter;
  30471. };
  30472. Texture.prototype.getTextureMatrix = function () {
  30473. var _this = this;
  30474. if (this.uOffset === this._cachedUOffset &&
  30475. this.vOffset === this._cachedVOffset &&
  30476. this.uScale === this._cachedUScale &&
  30477. this.vScale === this._cachedVScale &&
  30478. this.uAng === this._cachedUAng &&
  30479. this.vAng === this._cachedVAng &&
  30480. this.wAng === this._cachedWAng) {
  30481. return this._cachedTextureMatrix;
  30482. }
  30483. this._cachedUOffset = this.uOffset;
  30484. this._cachedVOffset = this.vOffset;
  30485. this._cachedUScale = this.uScale;
  30486. this._cachedVScale = this.vScale;
  30487. this._cachedUAng = this.uAng;
  30488. this._cachedVAng = this.vAng;
  30489. this._cachedWAng = this.wAng;
  30490. if (!this._cachedTextureMatrix) {
  30491. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30492. this._rowGenerationMatrix = new BABYLON.Matrix();
  30493. this._t0 = BABYLON.Vector3.Zero();
  30494. this._t1 = BABYLON.Vector3.Zero();
  30495. this._t2 = BABYLON.Vector3.Zero();
  30496. }
  30497. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30498. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30499. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30500. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30501. this._t1.subtractInPlace(this._t0);
  30502. this._t2.subtractInPlace(this._t0);
  30503. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30504. this._cachedTextureMatrix.m[0] = this._t1.x;
  30505. this._cachedTextureMatrix.m[1] = this._t1.y;
  30506. this._cachedTextureMatrix.m[2] = this._t1.z;
  30507. this._cachedTextureMatrix.m[4] = this._t2.x;
  30508. this._cachedTextureMatrix.m[5] = this._t2.y;
  30509. this._cachedTextureMatrix.m[6] = this._t2.z;
  30510. this._cachedTextureMatrix.m[8] = this._t0.x;
  30511. this._cachedTextureMatrix.m[9] = this._t0.y;
  30512. this._cachedTextureMatrix.m[10] = this._t0.z;
  30513. var scene = this.getScene();
  30514. if (!scene) {
  30515. return this._cachedTextureMatrix;
  30516. }
  30517. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30518. return mat.hasTexture(_this);
  30519. });
  30520. return this._cachedTextureMatrix;
  30521. };
  30522. Texture.prototype.getReflectionTextureMatrix = function () {
  30523. var _this = this;
  30524. var scene = this.getScene();
  30525. if (!scene) {
  30526. return this._cachedTextureMatrix;
  30527. }
  30528. if (this.uOffset === this._cachedUOffset &&
  30529. this.vOffset === this._cachedVOffset &&
  30530. this.uScale === this._cachedUScale &&
  30531. this.vScale === this._cachedVScale &&
  30532. this.coordinatesMode === this._cachedCoordinatesMode) {
  30533. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30534. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30535. return this._cachedTextureMatrix;
  30536. }
  30537. }
  30538. else {
  30539. return this._cachedTextureMatrix;
  30540. }
  30541. }
  30542. if (!this._cachedTextureMatrix) {
  30543. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30544. }
  30545. if (!this._projectionModeMatrix) {
  30546. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30547. }
  30548. this._cachedUOffset = this.uOffset;
  30549. this._cachedVOffset = this.vOffset;
  30550. this._cachedUScale = this.uScale;
  30551. this._cachedVScale = this.vScale;
  30552. this._cachedCoordinatesMode = this.coordinatesMode;
  30553. switch (this.coordinatesMode) {
  30554. case Texture.PLANAR_MODE:
  30555. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30556. this._cachedTextureMatrix[0] = this.uScale;
  30557. this._cachedTextureMatrix[5] = this.vScale;
  30558. this._cachedTextureMatrix[12] = this.uOffset;
  30559. this._cachedTextureMatrix[13] = this.vOffset;
  30560. break;
  30561. case Texture.PROJECTION_MODE:
  30562. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30563. this._projectionModeMatrix.m[0] = 0.5;
  30564. this._projectionModeMatrix.m[5] = -0.5;
  30565. this._projectionModeMatrix.m[10] = 0.0;
  30566. this._projectionModeMatrix.m[12] = 0.5;
  30567. this._projectionModeMatrix.m[13] = 0.5;
  30568. this._projectionModeMatrix.m[14] = 1.0;
  30569. this._projectionModeMatrix.m[15] = 1.0;
  30570. var projectionMatrix = scene.getProjectionMatrix();
  30571. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30572. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30573. break;
  30574. default:
  30575. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30576. break;
  30577. }
  30578. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30579. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30580. });
  30581. return this._cachedTextureMatrix;
  30582. };
  30583. Texture.prototype.clone = function () {
  30584. var _this = this;
  30585. return BABYLON.SerializationHelper.Clone(function () {
  30586. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30587. }, this);
  30588. };
  30589. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30590. get: function () {
  30591. if (!this._onLoadObservable) {
  30592. this._onLoadObservable = new BABYLON.Observable();
  30593. }
  30594. return this._onLoadObservable;
  30595. },
  30596. enumerable: true,
  30597. configurable: true
  30598. });
  30599. Texture.prototype.serialize = function () {
  30600. var serializationObject = _super.prototype.serialize.call(this);
  30601. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30602. serializationObject.base64String = this._buffer;
  30603. serializationObject.name = serializationObject.name.replace("data:", "");
  30604. }
  30605. serializationObject.invertY = this._invertY;
  30606. serializationObject.samplingMode = this.samplingMode;
  30607. return serializationObject;
  30608. };
  30609. Texture.prototype.getClassName = function () {
  30610. return "Texture";
  30611. };
  30612. Texture.prototype.dispose = function () {
  30613. _super.prototype.dispose.call(this);
  30614. if (this._onLoadObservable) {
  30615. this._onLoadObservable.clear();
  30616. this._onLoadObservable = null;
  30617. }
  30618. this._delayedOnLoad = null;
  30619. this._delayedOnError = null;
  30620. };
  30621. // Statics
  30622. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30623. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30624. if (onLoad === void 0) { onLoad = null; }
  30625. if (onError === void 0) { onError = null; }
  30626. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30627. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30628. };
  30629. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30630. if (parsedTexture.customType) {
  30631. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30632. // Update Sampling Mode
  30633. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30634. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30635. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30636. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30637. }
  30638. }
  30639. return parsedCustomTexture;
  30640. }
  30641. if (parsedTexture.isCube) {
  30642. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30643. }
  30644. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30645. return null;
  30646. }
  30647. var texture = BABYLON.SerializationHelper.Parse(function () {
  30648. var generateMipMaps = true;
  30649. if (parsedTexture.noMipmap) {
  30650. generateMipMaps = false;
  30651. }
  30652. if (parsedTexture.mirrorPlane) {
  30653. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30654. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30655. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30656. return mirrorTexture;
  30657. }
  30658. else if (parsedTexture.isRenderTarget) {
  30659. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30660. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30661. return renderTargetTexture;
  30662. }
  30663. else {
  30664. var texture;
  30665. if (parsedTexture.base64String) {
  30666. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30667. }
  30668. else {
  30669. var url = rootUrl + parsedTexture.name;
  30670. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30671. url = parsedTexture.url;
  30672. }
  30673. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30674. }
  30675. return texture;
  30676. }
  30677. }, parsedTexture, scene);
  30678. // Update Sampling Mode
  30679. if (parsedTexture.samplingMode) {
  30680. var sampling = parsedTexture.samplingMode;
  30681. if (texture._samplingMode !== sampling) {
  30682. texture.updateSamplingMode(sampling);
  30683. }
  30684. }
  30685. // Animations
  30686. if (parsedTexture.animations) {
  30687. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30688. var parsedAnimation = parsedTexture.animations[animationIndex];
  30689. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30690. }
  30691. }
  30692. return texture;
  30693. };
  30694. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30695. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30696. if (noMipmap === void 0) { noMipmap = false; }
  30697. if (invertY === void 0) { invertY = true; }
  30698. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30699. if (onLoad === void 0) { onLoad = null; }
  30700. if (onError === void 0) { onError = null; }
  30701. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30702. if (name.substr(0, 5) !== "data:") {
  30703. name = "data:" + name;
  30704. }
  30705. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30706. };
  30707. // Constants
  30708. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30709. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30710. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30711. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30712. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30713. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30714. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30715. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30716. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30717. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30718. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30719. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30720. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30721. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30722. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30723. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30724. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30725. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30726. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30727. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30728. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30729. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30730. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30731. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30732. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30733. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30734. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30735. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30736. /**
  30737. * 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
  30738. */
  30739. Texture.UseSerializedUrlIfAny = false;
  30740. __decorate([
  30741. BABYLON.serialize()
  30742. ], Texture.prototype, "url", void 0);
  30743. __decorate([
  30744. BABYLON.serialize()
  30745. ], Texture.prototype, "uOffset", void 0);
  30746. __decorate([
  30747. BABYLON.serialize()
  30748. ], Texture.prototype, "vOffset", void 0);
  30749. __decorate([
  30750. BABYLON.serialize()
  30751. ], Texture.prototype, "uScale", void 0);
  30752. __decorate([
  30753. BABYLON.serialize()
  30754. ], Texture.prototype, "vScale", void 0);
  30755. __decorate([
  30756. BABYLON.serialize()
  30757. ], Texture.prototype, "uAng", void 0);
  30758. __decorate([
  30759. BABYLON.serialize()
  30760. ], Texture.prototype, "vAng", void 0);
  30761. __decorate([
  30762. BABYLON.serialize()
  30763. ], Texture.prototype, "wAng", void 0);
  30764. __decorate([
  30765. BABYLON.serialize()
  30766. ], Texture.prototype, "uRotationCenter", void 0);
  30767. __decorate([
  30768. BABYLON.serialize()
  30769. ], Texture.prototype, "vRotationCenter", void 0);
  30770. __decorate([
  30771. BABYLON.serialize()
  30772. ], Texture.prototype, "wRotationCenter", void 0);
  30773. __decorate([
  30774. BABYLON.serialize()
  30775. ], Texture.prototype, "isBlocking", null);
  30776. return Texture;
  30777. }(BABYLON.BaseTexture));
  30778. BABYLON.Texture = Texture;
  30779. })(BABYLON || (BABYLON = {}));
  30780. //# sourceMappingURL=babylon.texture.js.map
  30781. var BABYLON;
  30782. (function (BABYLON) {
  30783. /**
  30784. * @hidden
  30785. **/
  30786. var _InstancesBatch = /** @class */ (function () {
  30787. function _InstancesBatch() {
  30788. this.mustReturn = false;
  30789. this.visibleInstances = new Array();
  30790. this.renderSelf = new Array();
  30791. }
  30792. return _InstancesBatch;
  30793. }());
  30794. BABYLON._InstancesBatch = _InstancesBatch;
  30795. var Mesh = /** @class */ (function (_super) {
  30796. __extends(Mesh, _super);
  30797. /**
  30798. * @constructor
  30799. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30800. * @param {Scene} scene The scene to add this mesh to.
  30801. * @param {Node} parent The parent of this mesh, if it has one
  30802. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30803. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30804. * When false, achieved by calling a clone(), also passing False.
  30805. * This will make creation of children, recursive.
  30806. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30807. */
  30808. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30809. if (scene === void 0) { scene = null; }
  30810. if (parent === void 0) { parent = null; }
  30811. if (source === void 0) { source = null; }
  30812. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30813. var _this = _super.call(this, name, scene) || this;
  30814. // Members
  30815. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30816. _this.instances = new Array();
  30817. _this._LODLevels = new Array();
  30818. /** @hidden */
  30819. _this._visibleInstances = {};
  30820. _this._renderIdForInstances = new Array();
  30821. _this._batchCache = new _InstancesBatch();
  30822. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30823. // Use by builder only to know what orientation were the mesh build in.
  30824. /** @hidden */
  30825. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30826. _this.overrideMaterialSideOrientation = null;
  30827. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30828. // Will be used to save a source mesh reference, If any
  30829. _this._source = null;
  30830. scene = _this.getScene();
  30831. if (source) {
  30832. // Geometry
  30833. if (source._geometry) {
  30834. source._geometry.applyToMesh(_this);
  30835. }
  30836. // Deep copy
  30837. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30838. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30839. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30840. ], ["_poseMatrix"]);
  30841. // Source mesh
  30842. _this._source = source;
  30843. // Construction Params
  30844. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30845. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30846. var myAnyThis = _this;
  30847. var myAnySource = source;
  30848. myAnyThis._closePath = myAnySource._closePath;
  30849. myAnyThis._idx = myAnySource._idx;
  30850. myAnyThis.dashSize = myAnySource.dashSize;
  30851. myAnyThis.gapSize = myAnySource.gapSize;
  30852. myAnyThis.path3D = myAnySource.path3D;
  30853. myAnyThis.pathArray = myAnySource.pathArray;
  30854. myAnyThis.arc = myAnySource.arc;
  30855. myAnyThis.radius = myAnySource.radius;
  30856. // Animation ranges
  30857. if (_this._source._ranges) {
  30858. var ranges = _this._source._ranges;
  30859. for (var name in ranges) {
  30860. if (!ranges.hasOwnProperty(name)) {
  30861. continue;
  30862. }
  30863. if (!ranges[name]) {
  30864. continue;
  30865. }
  30866. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30867. }
  30868. }
  30869. // Metadata
  30870. if (source.metadata && source.metadata.clone) {
  30871. _this.metadata = source.metadata.clone();
  30872. }
  30873. else {
  30874. _this.metadata = source.metadata;
  30875. }
  30876. // Tags
  30877. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30878. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30879. }
  30880. // Parent
  30881. _this.parent = source.parent;
  30882. // Pivot
  30883. _this.setPivotMatrix(source.getPivotMatrix());
  30884. _this.id = name + "." + source.id;
  30885. // Material
  30886. _this.material = source.material;
  30887. var index;
  30888. if (!doNotCloneChildren) {
  30889. // Children
  30890. var directDescendants = source.getDescendants(true);
  30891. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30892. var child = directDescendants[index_1];
  30893. if (child.clone) {
  30894. child.clone(name + "." + child.name, _this);
  30895. }
  30896. }
  30897. }
  30898. // Physics clone
  30899. var physicsEngine = _this.getScene().getPhysicsEngine();
  30900. if (clonePhysicsImpostor && physicsEngine) {
  30901. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30902. if (impostor) {
  30903. _this.physicsImpostor = impostor.clone(_this);
  30904. }
  30905. }
  30906. // Particles
  30907. for (index = 0; index < scene.particleSystems.length; index++) {
  30908. var system = scene.particleSystems[index];
  30909. if (system.emitter === source) {
  30910. system.clone(system.name, _this);
  30911. }
  30912. }
  30913. _this.refreshBoundingInfo();
  30914. _this.computeWorldMatrix(true);
  30915. }
  30916. // Parent
  30917. if (parent !== null) {
  30918. _this.parent = parent;
  30919. }
  30920. return _this;
  30921. }
  30922. Object.defineProperty(Mesh, "FRONTSIDE", {
  30923. /**
  30924. * Mesh side orientation : usually the external or front surface
  30925. */
  30926. get: function () {
  30927. return Mesh._FRONTSIDE;
  30928. },
  30929. enumerable: true,
  30930. configurable: true
  30931. });
  30932. Object.defineProperty(Mesh, "BACKSIDE", {
  30933. /**
  30934. * Mesh side orientation : usually the internal or back surface
  30935. */
  30936. get: function () {
  30937. return Mesh._BACKSIDE;
  30938. },
  30939. enumerable: true,
  30940. configurable: true
  30941. });
  30942. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30943. /**
  30944. * Mesh side orientation : both internal and external or front and back surfaces
  30945. */
  30946. get: function () {
  30947. return Mesh._DOUBLESIDE;
  30948. },
  30949. enumerable: true,
  30950. configurable: true
  30951. });
  30952. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30953. /**
  30954. * Mesh side orientation : by default, `FRONTSIDE`
  30955. */
  30956. get: function () {
  30957. return Mesh._DEFAULTSIDE;
  30958. },
  30959. enumerable: true,
  30960. configurable: true
  30961. });
  30962. Object.defineProperty(Mesh, "NO_CAP", {
  30963. /**
  30964. * Mesh cap setting : no cap
  30965. */
  30966. get: function () {
  30967. return Mesh._NO_CAP;
  30968. },
  30969. enumerable: true,
  30970. configurable: true
  30971. });
  30972. Object.defineProperty(Mesh, "CAP_START", {
  30973. /**
  30974. * Mesh cap setting : one cap at the beginning of the mesh
  30975. */
  30976. get: function () {
  30977. return Mesh._CAP_START;
  30978. },
  30979. enumerable: true,
  30980. configurable: true
  30981. });
  30982. Object.defineProperty(Mesh, "CAP_END", {
  30983. /**
  30984. * Mesh cap setting : one cap at the end of the mesh
  30985. */
  30986. get: function () {
  30987. return Mesh._CAP_END;
  30988. },
  30989. enumerable: true,
  30990. configurable: true
  30991. });
  30992. Object.defineProperty(Mesh, "CAP_ALL", {
  30993. /**
  30994. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30995. */
  30996. get: function () {
  30997. return Mesh._CAP_ALL;
  30998. },
  30999. enumerable: true,
  31000. configurable: true
  31001. });
  31002. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31003. /**
  31004. * An event triggered before rendering the mesh
  31005. */
  31006. get: function () {
  31007. if (!this._onBeforeRenderObservable) {
  31008. this._onBeforeRenderObservable = new BABYLON.Observable();
  31009. }
  31010. return this._onBeforeRenderObservable;
  31011. },
  31012. enumerable: true,
  31013. configurable: true
  31014. });
  31015. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31016. /**
  31017. * An event triggered after rendering the mesh
  31018. */
  31019. get: function () {
  31020. if (!this._onAfterRenderObservable) {
  31021. this._onAfterRenderObservable = new BABYLON.Observable();
  31022. }
  31023. return this._onAfterRenderObservable;
  31024. },
  31025. enumerable: true,
  31026. configurable: true
  31027. });
  31028. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31029. /**
  31030. * An event triggered before drawing the mesh
  31031. */
  31032. get: function () {
  31033. if (!this._onBeforeDrawObservable) {
  31034. this._onBeforeDrawObservable = new BABYLON.Observable();
  31035. }
  31036. return this._onBeforeDrawObservable;
  31037. },
  31038. enumerable: true,
  31039. configurable: true
  31040. });
  31041. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31042. set: function (callback) {
  31043. if (this._onBeforeDrawObserver) {
  31044. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31045. }
  31046. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31047. },
  31048. enumerable: true,
  31049. configurable: true
  31050. });
  31051. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31052. get: function () {
  31053. return this._morphTargetManager;
  31054. },
  31055. set: function (value) {
  31056. if (this._morphTargetManager === value) {
  31057. return;
  31058. }
  31059. this._morphTargetManager = value;
  31060. this._syncGeometryWithMorphTargetManager();
  31061. },
  31062. enumerable: true,
  31063. configurable: true
  31064. });
  31065. Object.defineProperty(Mesh.prototype, "source", {
  31066. get: function () {
  31067. return this._source;
  31068. },
  31069. enumerable: true,
  31070. configurable: true
  31071. });
  31072. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31073. get: function () {
  31074. return this._unIndexed;
  31075. },
  31076. set: function (value) {
  31077. if (this._unIndexed !== value) {
  31078. this._unIndexed = value;
  31079. this._markSubMeshesAsAttributesDirty();
  31080. }
  31081. },
  31082. enumerable: true,
  31083. configurable: true
  31084. });
  31085. // Methods
  31086. /**
  31087. * Returns the string "Mesh".
  31088. */
  31089. Mesh.prototype.getClassName = function () {
  31090. return "Mesh";
  31091. };
  31092. /**
  31093. * Returns a string.
  31094. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31095. */
  31096. Mesh.prototype.toString = function (fullDetails) {
  31097. var ret = _super.prototype.toString.call(this, fullDetails);
  31098. ret += ", n vertices: " + this.getTotalVertices();
  31099. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31100. if (this.animations) {
  31101. for (var i = 0; i < this.animations.length; i++) {
  31102. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31103. }
  31104. }
  31105. if (fullDetails) {
  31106. if (this._geometry) {
  31107. var ib = this.getIndices();
  31108. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31109. if (vb && ib) {
  31110. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31111. }
  31112. }
  31113. else {
  31114. ret += ", flat shading: UNKNOWN";
  31115. }
  31116. }
  31117. return ret;
  31118. };
  31119. /** @hidden */
  31120. Mesh.prototype._unBindEffect = function () {
  31121. _super.prototype._unBindEffect.call(this);
  31122. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31123. var instance = _a[_i];
  31124. instance._unBindEffect();
  31125. }
  31126. };
  31127. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31128. /**
  31129. * True if the mesh has some Levels Of Details (LOD).
  31130. * Returns a boolean.
  31131. */
  31132. get: function () {
  31133. return this._LODLevels.length > 0;
  31134. },
  31135. enumerable: true,
  31136. configurable: true
  31137. });
  31138. /**
  31139. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31140. * @returns an array of {BABYLON.MeshLODLevel}
  31141. */
  31142. Mesh.prototype.getLODLevels = function () {
  31143. return this._LODLevels;
  31144. };
  31145. Mesh.prototype._sortLODLevels = function () {
  31146. this._LODLevels.sort(function (a, b) {
  31147. if (a.distance < b.distance) {
  31148. return 1;
  31149. }
  31150. if (a.distance > b.distance) {
  31151. return -1;
  31152. }
  31153. return 0;
  31154. });
  31155. };
  31156. /**
  31157. * Add a mesh as LOD level triggered at the given distance.
  31158. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31159. * @param distance The distance from the center of the object to show this level
  31160. * @param mesh The mesh to be added as LOD level (can be null)
  31161. * @return This mesh (for chaining)
  31162. */
  31163. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31164. if (mesh && mesh._masterMesh) {
  31165. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31166. return this;
  31167. }
  31168. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31169. this._LODLevels.push(level);
  31170. if (mesh) {
  31171. mesh._masterMesh = this;
  31172. }
  31173. this._sortLODLevels();
  31174. return this;
  31175. };
  31176. /**
  31177. * Returns the LOD level mesh at the passed distance or null if not found.
  31178. * It is related to the method `addLODLevel(distance, mesh)`.
  31179. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31180. * Returns an object Mesh or `null`.
  31181. */
  31182. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31183. for (var index = 0; index < this._LODLevels.length; index++) {
  31184. var level = this._LODLevels[index];
  31185. if (level.distance === distance) {
  31186. return level.mesh;
  31187. }
  31188. }
  31189. return null;
  31190. };
  31191. /**
  31192. * Remove a mesh from the LOD array
  31193. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31194. * @param {Mesh} mesh The mesh to be removed.
  31195. * @return {Mesh} This mesh (for chaining)
  31196. */
  31197. Mesh.prototype.removeLODLevel = function (mesh) {
  31198. for (var index = 0; index < this._LODLevels.length; index++) {
  31199. if (this._LODLevels[index].mesh === mesh) {
  31200. this._LODLevels.splice(index, 1);
  31201. if (mesh) {
  31202. mesh._masterMesh = null;
  31203. }
  31204. }
  31205. }
  31206. this._sortLODLevels();
  31207. return this;
  31208. };
  31209. /**
  31210. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31211. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31212. */
  31213. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31214. if (!this._LODLevels || this._LODLevels.length === 0) {
  31215. return this;
  31216. }
  31217. var bSphere;
  31218. if (boundingSphere) {
  31219. bSphere = boundingSphere;
  31220. }
  31221. else {
  31222. var boundingInfo = this.getBoundingInfo();
  31223. bSphere = boundingInfo.boundingSphere;
  31224. }
  31225. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31226. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31227. if (this.onLODLevelSelection) {
  31228. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31229. }
  31230. return this;
  31231. }
  31232. for (var index = 0; index < this._LODLevels.length; index++) {
  31233. var level = this._LODLevels[index];
  31234. if (level.distance < distanceToCamera) {
  31235. if (level.mesh) {
  31236. level.mesh._preActivate();
  31237. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31238. }
  31239. if (this.onLODLevelSelection) {
  31240. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31241. }
  31242. return level.mesh;
  31243. }
  31244. }
  31245. if (this.onLODLevelSelection) {
  31246. this.onLODLevelSelection(distanceToCamera, this, this);
  31247. }
  31248. return this;
  31249. };
  31250. Object.defineProperty(Mesh.prototype, "geometry", {
  31251. /**
  31252. * Returns the mesh internal Geometry object.
  31253. */
  31254. get: function () {
  31255. return this._geometry;
  31256. },
  31257. enumerable: true,
  31258. configurable: true
  31259. });
  31260. /**
  31261. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31262. */
  31263. Mesh.prototype.getTotalVertices = function () {
  31264. if (this._geometry === null || this._geometry === undefined) {
  31265. return 0;
  31266. }
  31267. return this._geometry.getTotalVertices();
  31268. };
  31269. /**
  31270. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31271. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31272. * You can force the copy with forceCopy === true
  31273. * Returns null if the mesh has no geometry or no vertex buffer.
  31274. * Possible `kind` values :
  31275. * - BABYLON.VertexBuffer.PositionKind
  31276. * - BABYLON.VertexBuffer.UVKind
  31277. * - BABYLON.VertexBuffer.UV2Kind
  31278. * - BABYLON.VertexBuffer.UV3Kind
  31279. * - BABYLON.VertexBuffer.UV4Kind
  31280. * - BABYLON.VertexBuffer.UV5Kind
  31281. * - BABYLON.VertexBuffer.UV6Kind
  31282. * - BABYLON.VertexBuffer.ColorKind
  31283. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31284. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31285. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31286. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31287. */
  31288. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31289. if (!this._geometry) {
  31290. return null;
  31291. }
  31292. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31293. };
  31294. /**
  31295. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31296. * Returns `null` if the mesh has no geometry.
  31297. * Possible `kind` values :
  31298. * - BABYLON.VertexBuffer.PositionKind
  31299. * - BABYLON.VertexBuffer.UVKind
  31300. * - BABYLON.VertexBuffer.UV2Kind
  31301. * - BABYLON.VertexBuffer.UV3Kind
  31302. * - BABYLON.VertexBuffer.UV4Kind
  31303. * - BABYLON.VertexBuffer.UV5Kind
  31304. * - BABYLON.VertexBuffer.UV6Kind
  31305. * - BABYLON.VertexBuffer.ColorKind
  31306. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31307. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31308. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31309. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31310. */
  31311. Mesh.prototype.getVertexBuffer = function (kind) {
  31312. if (!this._geometry) {
  31313. return null;
  31314. }
  31315. return this._geometry.getVertexBuffer(kind);
  31316. };
  31317. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31318. if (!this._geometry) {
  31319. if (this._delayInfo) {
  31320. return this._delayInfo.indexOf(kind) !== -1;
  31321. }
  31322. return false;
  31323. }
  31324. return this._geometry.isVerticesDataPresent(kind);
  31325. };
  31326. /**
  31327. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31328. * Possible `kind` values :
  31329. * - BABYLON.VertexBuffer.PositionKind
  31330. * - BABYLON.VertexBuffer.UVKind
  31331. * - BABYLON.VertexBuffer.UV2Kind
  31332. * - BABYLON.VertexBuffer.UV3Kind
  31333. * - BABYLON.VertexBuffer.UV4Kind
  31334. * - BABYLON.VertexBuffer.UV5Kind
  31335. * - BABYLON.VertexBuffer.UV6Kind
  31336. * - BABYLON.VertexBuffer.ColorKind
  31337. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31338. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31339. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31340. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31341. */
  31342. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31343. if (!this._geometry) {
  31344. if (this._delayInfo) {
  31345. return this._delayInfo.indexOf(kind) !== -1;
  31346. }
  31347. return false;
  31348. }
  31349. return this._geometry.isVertexBufferUpdatable(kind);
  31350. };
  31351. /**
  31352. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31353. * Possible `kind` values :
  31354. * - BABYLON.VertexBuffer.PositionKind
  31355. * - BABYLON.VertexBuffer.UVKind
  31356. * - BABYLON.VertexBuffer.UV2Kind
  31357. * - BABYLON.VertexBuffer.UV3Kind
  31358. * - BABYLON.VertexBuffer.UV4Kind
  31359. * - BABYLON.VertexBuffer.UV5Kind
  31360. * - BABYLON.VertexBuffer.UV6Kind
  31361. * - BABYLON.VertexBuffer.ColorKind
  31362. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31363. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31364. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31365. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31366. */
  31367. Mesh.prototype.getVerticesDataKinds = function () {
  31368. if (!this._geometry) {
  31369. var result = new Array();
  31370. if (this._delayInfo) {
  31371. this._delayInfo.forEach(function (kind, index, array) {
  31372. result.push(kind);
  31373. });
  31374. }
  31375. return result;
  31376. }
  31377. return this._geometry.getVerticesDataKinds();
  31378. };
  31379. /**
  31380. * Returns a positive integer : the total number of indices in this mesh geometry.
  31381. * Returns zero if the mesh has no geometry.
  31382. */
  31383. Mesh.prototype.getTotalIndices = function () {
  31384. if (!this._geometry) {
  31385. return 0;
  31386. }
  31387. return this._geometry.getTotalIndices();
  31388. };
  31389. /**
  31390. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31391. * @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.
  31392. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31393. * @returns the indices array or an empty array if the mesh has no geometry
  31394. */
  31395. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31396. if (!this._geometry) {
  31397. return [];
  31398. }
  31399. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31400. };
  31401. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31402. get: function () {
  31403. return this._masterMesh !== null && this._masterMesh !== undefined;
  31404. },
  31405. enumerable: true,
  31406. configurable: true
  31407. });
  31408. /**
  31409. * Determine if the current mesh is ready to be rendered
  31410. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31411. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31412. * @returns true if all associated assets are ready (material, textures, shaders)
  31413. */
  31414. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31415. if (completeCheck === void 0) { completeCheck = false; }
  31416. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31417. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31418. return false;
  31419. }
  31420. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31421. return false;
  31422. }
  31423. if (!this.subMeshes || this.subMeshes.length === 0) {
  31424. return true;
  31425. }
  31426. if (!completeCheck) {
  31427. return true;
  31428. }
  31429. var engine = this.getEngine();
  31430. var scene = this.getScene();
  31431. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31432. this.computeWorldMatrix();
  31433. var mat = this.material || scene.defaultMaterial;
  31434. if (mat) {
  31435. if (mat.storeEffectOnSubMeshes) {
  31436. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31437. var subMesh = _a[_i];
  31438. var effectiveMaterial = subMesh.getMaterial();
  31439. if (effectiveMaterial) {
  31440. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31441. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31442. return false;
  31443. }
  31444. }
  31445. else {
  31446. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31447. return false;
  31448. }
  31449. }
  31450. }
  31451. }
  31452. }
  31453. else {
  31454. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31455. return false;
  31456. }
  31457. }
  31458. }
  31459. // Shadows
  31460. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31461. var light = _c[_b];
  31462. var generator = light.getShadowGenerator();
  31463. if (generator) {
  31464. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31465. var subMesh = _e[_d];
  31466. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31467. return false;
  31468. }
  31469. }
  31470. }
  31471. }
  31472. // LOD
  31473. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31474. var lod = _g[_f];
  31475. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31476. return false;
  31477. }
  31478. }
  31479. return true;
  31480. };
  31481. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31482. /**
  31483. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31484. * This property is pertinent only for updatable parametric shapes.
  31485. */
  31486. get: function () {
  31487. return this._areNormalsFrozen;
  31488. },
  31489. enumerable: true,
  31490. configurable: true
  31491. });
  31492. /**
  31493. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31494. * It has no effect at all on other shapes.
  31495. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31496. * Returns the Mesh.
  31497. */
  31498. Mesh.prototype.freezeNormals = function () {
  31499. this._areNormalsFrozen = true;
  31500. return this;
  31501. };
  31502. /**
  31503. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31504. * It has no effect at all on other shapes.
  31505. * It reactivates the mesh normals computation if it was previously frozen.
  31506. * Returns the Mesh.
  31507. */
  31508. Mesh.prototype.unfreezeNormals = function () {
  31509. this._areNormalsFrozen = false;
  31510. return this;
  31511. };
  31512. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31513. /**
  31514. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31515. */
  31516. set: function (count) {
  31517. this._overridenInstanceCount = count;
  31518. },
  31519. enumerable: true,
  31520. configurable: true
  31521. });
  31522. // Methods
  31523. /** @hidden */
  31524. Mesh.prototype._preActivate = function () {
  31525. var sceneRenderId = this.getScene().getRenderId();
  31526. if (this._preActivateId === sceneRenderId) {
  31527. return this;
  31528. }
  31529. this._preActivateId = sceneRenderId;
  31530. this._visibleInstances = null;
  31531. return this;
  31532. };
  31533. /** @hidden */
  31534. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31535. if (this._visibleInstances) {
  31536. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31537. }
  31538. return this;
  31539. };
  31540. /** @hidden */
  31541. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31542. if (!this._visibleInstances) {
  31543. this._visibleInstances = {};
  31544. this._visibleInstances.defaultRenderId = renderId;
  31545. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31546. }
  31547. if (!this._visibleInstances[renderId]) {
  31548. this._visibleInstances[renderId] = new Array();
  31549. }
  31550. this._visibleInstances[renderId].push(instance);
  31551. return this;
  31552. };
  31553. /**
  31554. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31555. * This means the mesh underlying bounding box and sphere are recomputed.
  31556. * Returns the Mesh.
  31557. */
  31558. Mesh.prototype.refreshBoundingInfo = function () {
  31559. return this._refreshBoundingInfo(false);
  31560. };
  31561. /** @hidden */
  31562. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31563. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31564. return this;
  31565. }
  31566. var data = this._getPositionData(applySkeleton);
  31567. if (data) {
  31568. var bias = this.geometry ? this.geometry.boundingBias : null;
  31569. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31570. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31571. }
  31572. if (this.subMeshes) {
  31573. for (var index = 0; index < this.subMeshes.length; index++) {
  31574. this.subMeshes[index].refreshBoundingInfo();
  31575. }
  31576. }
  31577. this._updateBoundingInfo();
  31578. return this;
  31579. };
  31580. Mesh.prototype._getPositionData = function (applySkeleton) {
  31581. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31582. if (data && applySkeleton && this.skeleton) {
  31583. data = BABYLON.Tools.Slice(data);
  31584. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31585. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31586. if (matricesWeightsData && matricesIndicesData) {
  31587. var needExtras = this.numBoneInfluencers > 4;
  31588. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31589. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31590. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31591. var tempVector = BABYLON.Tmp.Vector3[0];
  31592. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31593. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31594. var matWeightIdx = 0;
  31595. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31596. finalMatrix.reset();
  31597. var inf;
  31598. var weight;
  31599. for (inf = 0; inf < 4; inf++) {
  31600. weight = matricesWeightsData[matWeightIdx + inf];
  31601. if (weight > 0) {
  31602. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31603. finalMatrix.addToSelf(tempMatrix);
  31604. }
  31605. }
  31606. if (needExtras) {
  31607. for (inf = 0; inf < 4; inf++) {
  31608. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31609. if (weight > 0) {
  31610. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31611. finalMatrix.addToSelf(tempMatrix);
  31612. }
  31613. }
  31614. }
  31615. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31616. tempVector.toArray(data, index);
  31617. }
  31618. }
  31619. }
  31620. return data;
  31621. };
  31622. /** @hidden */
  31623. Mesh.prototype._createGlobalSubMesh = function (force) {
  31624. var totalVertices = this.getTotalVertices();
  31625. if (!totalVertices || !this.getIndices()) {
  31626. return null;
  31627. }
  31628. // Check if we need to recreate the submeshes
  31629. if (this.subMeshes && this.subMeshes.length > 0) {
  31630. var ib = this.getIndices();
  31631. if (!ib) {
  31632. return null;
  31633. }
  31634. var totalIndices = ib.length;
  31635. var needToRecreate = false;
  31636. if (force) {
  31637. needToRecreate = true;
  31638. }
  31639. else {
  31640. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31641. var submesh = _a[_i];
  31642. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31643. needToRecreate = true;
  31644. break;
  31645. }
  31646. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31647. needToRecreate = true;
  31648. break;
  31649. }
  31650. }
  31651. }
  31652. if (!needToRecreate) {
  31653. return this.subMeshes[0];
  31654. }
  31655. }
  31656. this.releaseSubMeshes();
  31657. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31658. };
  31659. Mesh.prototype.subdivide = function (count) {
  31660. if (count < 1) {
  31661. return;
  31662. }
  31663. var totalIndices = this.getTotalIndices();
  31664. var subdivisionSize = (totalIndices / count) | 0;
  31665. var offset = 0;
  31666. // Ensure that subdivisionSize is a multiple of 3
  31667. while (subdivisionSize % 3 !== 0) {
  31668. subdivisionSize++;
  31669. }
  31670. this.releaseSubMeshes();
  31671. for (var index = 0; index < count; index++) {
  31672. if (offset >= totalIndices) {
  31673. break;
  31674. }
  31675. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31676. offset += subdivisionSize;
  31677. }
  31678. this.synchronizeInstances();
  31679. };
  31680. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31681. if (updatable === void 0) { updatable = false; }
  31682. if (!this._geometry) {
  31683. var vertexData = new BABYLON.VertexData();
  31684. vertexData.set(data, kind);
  31685. var scene = this.getScene();
  31686. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31687. }
  31688. else {
  31689. this._geometry.setVerticesData(kind, data, updatable, stride);
  31690. }
  31691. return this;
  31692. };
  31693. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31694. if (updatable === void 0) { updatable = true; }
  31695. var vb = this.getVertexBuffer(kind);
  31696. if (!vb || vb.isUpdatable() === updatable) {
  31697. return;
  31698. }
  31699. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31700. };
  31701. /**
  31702. * Sets the mesh VertexBuffer.
  31703. * Returns the Mesh.
  31704. */
  31705. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31706. if (!this._geometry) {
  31707. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31708. }
  31709. this._geometry.setVerticesBuffer(buffer);
  31710. return this;
  31711. };
  31712. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31713. if (!this._geometry) {
  31714. return this;
  31715. }
  31716. if (!makeItUnique) {
  31717. this._geometry.updateVerticesData(kind, data, updateExtends);
  31718. }
  31719. else {
  31720. this.makeGeometryUnique();
  31721. this.updateVerticesData(kind, data, updateExtends, false);
  31722. }
  31723. return this;
  31724. };
  31725. /**
  31726. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31727. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31728. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31729. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31730. * Returns the Mesh.
  31731. */
  31732. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31733. if (computeNormals === void 0) { computeNormals = true; }
  31734. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31735. if (!positions) {
  31736. return this;
  31737. }
  31738. positionFunction(positions);
  31739. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31740. if (computeNormals) {
  31741. var indices = this.getIndices();
  31742. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31743. if (!normals) {
  31744. return this;
  31745. }
  31746. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31747. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31748. }
  31749. return this;
  31750. };
  31751. /**
  31752. * Creates a un-shared specific occurence of the geometry for the mesh.
  31753. * Returns the Mesh.
  31754. */
  31755. Mesh.prototype.makeGeometryUnique = function () {
  31756. if (!this._geometry) {
  31757. return this;
  31758. }
  31759. var oldGeometry = this._geometry;
  31760. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31761. oldGeometry.releaseForMesh(this, true);
  31762. geometry.applyToMesh(this);
  31763. return this;
  31764. };
  31765. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31766. if (totalVertices === void 0) { totalVertices = null; }
  31767. if (updatable === void 0) { updatable = false; }
  31768. if (!this._geometry) {
  31769. var vertexData = new BABYLON.VertexData();
  31770. vertexData.indices = indices;
  31771. var scene = this.getScene();
  31772. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31773. }
  31774. else {
  31775. this._geometry.setIndices(indices, totalVertices, updatable);
  31776. }
  31777. return this;
  31778. };
  31779. /**
  31780. * Update the current index buffer
  31781. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31782. * Returns the Mesh.
  31783. */
  31784. Mesh.prototype.updateIndices = function (indices, offset) {
  31785. if (!this._geometry) {
  31786. return this;
  31787. }
  31788. this._geometry.updateIndices(indices, offset);
  31789. return this;
  31790. };
  31791. /**
  31792. * Invert the geometry to move from a right handed system to a left handed one.
  31793. * Returns the Mesh.
  31794. */
  31795. Mesh.prototype.toLeftHanded = function () {
  31796. if (!this._geometry) {
  31797. return this;
  31798. }
  31799. this._geometry.toLeftHanded();
  31800. return this;
  31801. };
  31802. /** @hidden */
  31803. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31804. if (!this._geometry) {
  31805. return this;
  31806. }
  31807. var engine = this.getScene().getEngine();
  31808. // Wireframe
  31809. var indexToBind;
  31810. if (this._unIndexed) {
  31811. indexToBind = null;
  31812. }
  31813. else {
  31814. switch (fillMode) {
  31815. case BABYLON.Material.PointFillMode:
  31816. indexToBind = null;
  31817. break;
  31818. case BABYLON.Material.WireFrameFillMode:
  31819. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31820. break;
  31821. default:
  31822. case BABYLON.Material.TriangleFillMode:
  31823. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31824. break;
  31825. }
  31826. }
  31827. // VBOs
  31828. this._geometry._bind(effect, indexToBind);
  31829. return this;
  31830. };
  31831. /** @hidden */
  31832. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31833. if (alternate === void 0) { alternate = false; }
  31834. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31835. return this;
  31836. }
  31837. if (this._onBeforeDrawObservable) {
  31838. this._onBeforeDrawObservable.notifyObservers(this);
  31839. }
  31840. var scene = this.getScene();
  31841. var engine = scene.getEngine();
  31842. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31843. // or triangles as points
  31844. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31845. }
  31846. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31847. // Triangles as wireframe
  31848. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31849. }
  31850. else {
  31851. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31852. }
  31853. if (scene._isAlternateRenderingEnabled && !alternate) {
  31854. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31855. if (!effect || !scene.activeCamera) {
  31856. return this;
  31857. }
  31858. scene._switchToAlternateCameraConfiguration(true);
  31859. this._effectiveMaterial.bindView(effect);
  31860. this._effectiveMaterial.bindViewProjection(effect);
  31861. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31862. this._draw(subMesh, fillMode, instancesCount, true);
  31863. engine.setViewport(scene.activeCamera.viewport);
  31864. scene._switchToAlternateCameraConfiguration(false);
  31865. this._effectiveMaterial.bindView(effect);
  31866. this._effectiveMaterial.bindViewProjection(effect);
  31867. }
  31868. return this;
  31869. };
  31870. /**
  31871. * Registers for this mesh a javascript function called just before the rendering process.
  31872. * This function is passed the current mesh.
  31873. * Return the Mesh.
  31874. */
  31875. Mesh.prototype.registerBeforeRender = function (func) {
  31876. this.onBeforeRenderObservable.add(func);
  31877. return this;
  31878. };
  31879. /**
  31880. * Disposes a previously registered javascript function called before the rendering.
  31881. * This function is passed the current mesh.
  31882. * Returns the Mesh.
  31883. */
  31884. Mesh.prototype.unregisterBeforeRender = function (func) {
  31885. this.onBeforeRenderObservable.removeCallback(func);
  31886. return this;
  31887. };
  31888. /**
  31889. * Registers for this mesh a javascript function called just after the rendering is complete.
  31890. * This function is passed the current mesh.
  31891. * Returns the Mesh.
  31892. */
  31893. Mesh.prototype.registerAfterRender = function (func) {
  31894. this.onAfterRenderObservable.add(func);
  31895. return this;
  31896. };
  31897. /**
  31898. * Disposes a previously registered javascript function called after the rendering.
  31899. * This function is passed the current mesh.
  31900. * Return the Mesh.
  31901. */
  31902. Mesh.prototype.unregisterAfterRender = function (func) {
  31903. this.onAfterRenderObservable.removeCallback(func);
  31904. return this;
  31905. };
  31906. /** @hidden */
  31907. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31908. var scene = this.getScene();
  31909. this._batchCache.mustReturn = false;
  31910. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31911. this._batchCache.visibleInstances[subMeshId] = null;
  31912. if (this._visibleInstances) {
  31913. var currentRenderId = scene.getRenderId();
  31914. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31915. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31916. var selfRenderId = this._renderId;
  31917. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31918. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31919. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31920. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31921. }
  31922. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31923. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31924. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31925. this._batchCache.mustReturn = true;
  31926. return this._batchCache;
  31927. }
  31928. if (currentRenderId !== selfRenderId) {
  31929. this._batchCache.renderSelf[subMeshId] = false;
  31930. }
  31931. }
  31932. this._renderIdForInstances[subMeshId] = currentRenderId;
  31933. }
  31934. return this._batchCache;
  31935. };
  31936. /** @hidden */
  31937. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31938. var visibleInstances = batch.visibleInstances[subMesh._id];
  31939. if (!visibleInstances) {
  31940. return this;
  31941. }
  31942. var matricesCount = visibleInstances.length + 1;
  31943. var bufferSize = matricesCount * 16 * 4;
  31944. var currentInstancesBufferSize = this._instancesBufferSize;
  31945. var instancesBuffer = this._instancesBuffer;
  31946. while (this._instancesBufferSize < bufferSize) {
  31947. this._instancesBufferSize *= 2;
  31948. }
  31949. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31950. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31951. }
  31952. var offset = 0;
  31953. var instancesCount = 0;
  31954. var world = this.getWorldMatrix();
  31955. if (batch.renderSelf[subMesh._id]) {
  31956. world.copyToArray(this._instancesData, offset);
  31957. offset += 16;
  31958. instancesCount++;
  31959. }
  31960. if (visibleInstances) {
  31961. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31962. var instance = visibleInstances[instanceIndex];
  31963. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31964. offset += 16;
  31965. instancesCount++;
  31966. }
  31967. }
  31968. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31969. if (instancesBuffer) {
  31970. instancesBuffer.dispose();
  31971. }
  31972. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31973. this._instancesBuffer = instancesBuffer;
  31974. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31975. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31976. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31977. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31978. }
  31979. else {
  31980. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31981. }
  31982. this._bind(subMesh, effect, fillMode);
  31983. this._draw(subMesh, fillMode, instancesCount);
  31984. engine.unbindInstanceAttributes();
  31985. return this;
  31986. };
  31987. /** @hidden */
  31988. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31989. var scene = this.getScene();
  31990. var engine = scene.getEngine();
  31991. if (hardwareInstancedRendering) {
  31992. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31993. }
  31994. else {
  31995. if (batch.renderSelf[subMesh._id]) {
  31996. // Draw
  31997. if (onBeforeDraw) {
  31998. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31999. }
  32000. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32001. }
  32002. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32003. if (visibleInstancesForSubMesh) {
  32004. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32005. var instance = visibleInstancesForSubMesh[instanceIndex];
  32006. // World
  32007. var world = instance.getWorldMatrix();
  32008. if (onBeforeDraw) {
  32009. onBeforeDraw(true, world, effectiveMaterial);
  32010. }
  32011. // Draw
  32012. this._draw(subMesh, fillMode);
  32013. }
  32014. }
  32015. }
  32016. return this;
  32017. };
  32018. /**
  32019. * 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
  32020. * @param subMesh defines the subMesh to render
  32021. * @param enableAlphaMode defines if alpha mode can be changed
  32022. * @returns the current mesh
  32023. */
  32024. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32025. this._checkOcclusionQuery();
  32026. if (this._isOccluded) {
  32027. return this;
  32028. }
  32029. var scene = this.getScene();
  32030. // Managing instances
  32031. var batch = this._getInstancesRenderList(subMesh._id);
  32032. if (batch.mustReturn) {
  32033. return this;
  32034. }
  32035. // Checking geometry state
  32036. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32037. return this;
  32038. }
  32039. if (this._onBeforeRenderObservable) {
  32040. this._onBeforeRenderObservable.notifyObservers(this);
  32041. }
  32042. var engine = scene.getEngine();
  32043. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32044. // Material
  32045. var material = subMesh.getMaterial();
  32046. if (!material) {
  32047. return this;
  32048. }
  32049. this._effectiveMaterial = material;
  32050. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32051. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32052. return this;
  32053. }
  32054. }
  32055. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32056. return this;
  32057. }
  32058. // Alpha mode
  32059. if (enableAlphaMode) {
  32060. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32061. }
  32062. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32063. var step = _a[_i];
  32064. step.action(this, subMesh, batch);
  32065. }
  32066. var effect;
  32067. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32068. effect = subMesh.effect;
  32069. }
  32070. else {
  32071. effect = this._effectiveMaterial.getEffect();
  32072. }
  32073. if (!effect) {
  32074. return this;
  32075. }
  32076. var sideOrientation = this.overrideMaterialSideOrientation;
  32077. if (sideOrientation == null) {
  32078. sideOrientation = this._effectiveMaterial.sideOrientation;
  32079. if (this._getWorldMatrixDeterminant() < 0) {
  32080. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32081. }
  32082. }
  32083. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32084. if (this._effectiveMaterial.forceDepthWrite) {
  32085. engine.setDepthWrite(true);
  32086. }
  32087. // Bind
  32088. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32089. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32090. this._bind(subMesh, effect, fillMode);
  32091. }
  32092. var world = this.getWorldMatrix();
  32093. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32094. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32095. }
  32096. else {
  32097. this._effectiveMaterial.bind(world, this);
  32098. }
  32099. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32100. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32101. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32102. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32103. }
  32104. // Draw
  32105. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32106. // Unbind
  32107. this._effectiveMaterial.unbind();
  32108. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32109. var step = _c[_b];
  32110. step.action(this, subMesh, batch);
  32111. }
  32112. if (this._onAfterRenderObservable) {
  32113. this._onAfterRenderObservable.notifyObservers(this);
  32114. }
  32115. return this;
  32116. };
  32117. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32118. if (isInstance && effectiveMaterial) {
  32119. effectiveMaterial.bindOnlyWorldMatrix(world);
  32120. }
  32121. };
  32122. /**
  32123. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32124. */
  32125. Mesh.prototype.getEmittedParticleSystems = function () {
  32126. var results = new Array();
  32127. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32128. var particleSystem = this.getScene().particleSystems[index];
  32129. if (particleSystem.emitter === this) {
  32130. results.push(particleSystem);
  32131. }
  32132. }
  32133. return results;
  32134. };
  32135. /**
  32136. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32137. */
  32138. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32139. var results = new Array();
  32140. var descendants = this.getDescendants();
  32141. descendants.push(this);
  32142. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32143. var particleSystem = this.getScene().particleSystems[index];
  32144. var emitter = particleSystem.emitter;
  32145. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32146. results.push(particleSystem);
  32147. }
  32148. }
  32149. return results;
  32150. };
  32151. /**
  32152. * Normalize matrix weights so that all vertices have a total weight set to 1
  32153. */
  32154. Mesh.prototype.cleanMatrixWeights = function () {
  32155. var epsilon = 1e-3;
  32156. var noInfluenceBoneIndex = 0.0;
  32157. if (this.skeleton) {
  32158. noInfluenceBoneIndex = this.skeleton.bones.length;
  32159. }
  32160. else {
  32161. return;
  32162. }
  32163. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32164. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32165. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32166. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32167. var influencers = this.numBoneInfluencers;
  32168. var size = matricesWeights.length;
  32169. for (var i = 0; i < size; i += 4) {
  32170. var weight = 0.0;
  32171. var firstZeroWeight = -1;
  32172. for (var j = 0; j < 4; j++) {
  32173. var w = matricesWeights[i + j];
  32174. weight += w;
  32175. if (w < epsilon && firstZeroWeight < 0) {
  32176. firstZeroWeight = j;
  32177. }
  32178. }
  32179. if (matricesWeightsExtra) {
  32180. for (var j = 0; j < 4; j++) {
  32181. var w = matricesWeightsExtra[i + j];
  32182. weight += w;
  32183. if (w < epsilon && firstZeroWeight < 0) {
  32184. firstZeroWeight = j + 4;
  32185. }
  32186. }
  32187. }
  32188. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32189. firstZeroWeight = influencers - 1;
  32190. }
  32191. if (weight > epsilon) {
  32192. var mweight = 1.0 / weight;
  32193. for (var j = 0; j < 4; j++) {
  32194. matricesWeights[i + j] *= mweight;
  32195. }
  32196. if (matricesWeightsExtra) {
  32197. for (var j = 0; j < 4; j++) {
  32198. matricesWeightsExtra[i + j] *= mweight;
  32199. }
  32200. }
  32201. }
  32202. else {
  32203. if (firstZeroWeight >= 4) {
  32204. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32205. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32206. }
  32207. else {
  32208. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32209. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32210. }
  32211. }
  32212. }
  32213. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32214. if (matricesIndicesExtra) {
  32215. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32216. }
  32217. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32218. if (matricesWeightsExtra) {
  32219. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32220. }
  32221. };
  32222. /** @hidden */
  32223. Mesh.prototype._checkDelayState = function () {
  32224. var scene = this.getScene();
  32225. if (this._geometry) {
  32226. this._geometry.load(scene);
  32227. }
  32228. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32229. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32230. this._queueLoad(scene);
  32231. }
  32232. return this;
  32233. };
  32234. Mesh.prototype._queueLoad = function (scene) {
  32235. var _this = this;
  32236. scene._addPendingData(this);
  32237. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32238. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32239. if (data instanceof ArrayBuffer) {
  32240. _this._delayLoadingFunction(data, _this);
  32241. }
  32242. else {
  32243. _this._delayLoadingFunction(JSON.parse(data), _this);
  32244. }
  32245. _this.instances.forEach(function (instance) {
  32246. instance._syncSubMeshes();
  32247. });
  32248. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32249. scene._removePendingData(_this);
  32250. }, function () { }, scene.database, getBinaryData);
  32251. return this;
  32252. };
  32253. /**
  32254. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32255. * A mesh is in the frustum if its bounding box intersects the frustum
  32256. * @param frustumPlanes defines the frustum to test
  32257. * @returns true if the mesh is in the frustum planes
  32258. */
  32259. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32260. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32261. return false;
  32262. }
  32263. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32264. return false;
  32265. }
  32266. this._checkDelayState();
  32267. return true;
  32268. };
  32269. /**
  32270. * Sets the mesh material by the material or multiMaterial `id` property.
  32271. * The material `id` is a string identifying the material or the multiMaterial.
  32272. * This method returns the Mesh.
  32273. */
  32274. Mesh.prototype.setMaterialByID = function (id) {
  32275. var materials = this.getScene().materials;
  32276. var index;
  32277. for (index = materials.length - 1; index > -1; index--) {
  32278. if (materials[index].id === id) {
  32279. this.material = materials[index];
  32280. return this;
  32281. }
  32282. }
  32283. // Multi
  32284. var multiMaterials = this.getScene().multiMaterials;
  32285. for (index = multiMaterials.length - 1; index > -1; index--) {
  32286. if (multiMaterials[index].id === id) {
  32287. this.material = multiMaterials[index];
  32288. return this;
  32289. }
  32290. }
  32291. return this;
  32292. };
  32293. /**
  32294. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32295. */
  32296. Mesh.prototype.getAnimatables = function () {
  32297. var results = new Array();
  32298. if (this.material) {
  32299. results.push(this.material);
  32300. }
  32301. if (this.skeleton) {
  32302. results.push(this.skeleton);
  32303. }
  32304. return results;
  32305. };
  32306. /**
  32307. * Modifies the mesh geometry according to the passed transformation matrix.
  32308. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32309. * The mesh normals are modified using the same transformation.
  32310. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32311. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32312. * Returns the Mesh.
  32313. */
  32314. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32315. // Position
  32316. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32317. return this;
  32318. }
  32319. var submeshes = this.subMeshes.splice(0);
  32320. this._resetPointsArrayCache();
  32321. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32322. var temp = new Array();
  32323. var index;
  32324. for (index = 0; index < data.length; index += 3) {
  32325. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32326. }
  32327. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32328. // Normals
  32329. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32330. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32331. temp = [];
  32332. for (index = 0; index < data.length; index += 3) {
  32333. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32334. }
  32335. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32336. }
  32337. // flip faces?
  32338. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32339. this.flipFaces();
  32340. }
  32341. // Restore submeshes
  32342. this.releaseSubMeshes();
  32343. this.subMeshes = submeshes;
  32344. return this;
  32345. };
  32346. /**
  32347. * Modifies the mesh geometry according to its own current World Matrix.
  32348. * The mesh World Matrix is then reset.
  32349. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32350. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32351. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32352. * Returns the Mesh.
  32353. */
  32354. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32355. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32356. this.scaling.copyFromFloats(1, 1, 1);
  32357. this.position.copyFromFloats(0, 0, 0);
  32358. this.rotation.copyFromFloats(0, 0, 0);
  32359. //only if quaternion is already set
  32360. if (this.rotationQuaternion) {
  32361. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32362. }
  32363. this._worldMatrix = BABYLON.Matrix.Identity();
  32364. return this;
  32365. };
  32366. Object.defineProperty(Mesh.prototype, "_positions", {
  32367. // Cache
  32368. get: function () {
  32369. if (this._geometry) {
  32370. return this._geometry._positions;
  32371. }
  32372. return null;
  32373. },
  32374. enumerable: true,
  32375. configurable: true
  32376. });
  32377. /** @hidden */
  32378. Mesh.prototype._resetPointsArrayCache = function () {
  32379. if (this._geometry) {
  32380. this._geometry._resetPointsArrayCache();
  32381. }
  32382. return this;
  32383. };
  32384. /** @hidden */
  32385. Mesh.prototype._generatePointsArray = function () {
  32386. if (this._geometry) {
  32387. return this._geometry._generatePointsArray();
  32388. }
  32389. return false;
  32390. };
  32391. /**
  32392. * Returns a new Mesh object generated from the current mesh properties.
  32393. * This method must not get confused with createInstance().
  32394. * The parameter `name` is a string, the name given to the new mesh.
  32395. * The optional parameter `newParent` can be any Node object (default `null`).
  32396. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32397. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32398. */
  32399. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32400. if (name === void 0) { name = ""; }
  32401. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32402. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32403. };
  32404. /**
  32405. * Releases resources associated with this mesh.
  32406. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32407. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32408. */
  32409. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32410. var _this = this;
  32411. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32412. this.morphTargetManager = null;
  32413. if (this._geometry) {
  32414. this._geometry.releaseForMesh(this, true);
  32415. }
  32416. if (this._onBeforeDrawObservable) {
  32417. this._onBeforeDrawObservable.clear();
  32418. }
  32419. if (this._onBeforeRenderObservable) {
  32420. this._onBeforeRenderObservable.clear();
  32421. }
  32422. if (this._onAfterRenderObservable) {
  32423. this._onAfterRenderObservable.clear();
  32424. }
  32425. // Sources
  32426. var meshes = this.getScene().meshes;
  32427. meshes.forEach(function (abstractMesh) {
  32428. var mesh = abstractMesh;
  32429. if (mesh._source && mesh._source === _this) {
  32430. mesh._source = null;
  32431. }
  32432. });
  32433. this._source = null;
  32434. // Instances
  32435. if (this._instancesBuffer) {
  32436. this._instancesBuffer.dispose();
  32437. this._instancesBuffer = null;
  32438. }
  32439. while (this.instances.length) {
  32440. this.instances[0].dispose();
  32441. }
  32442. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32443. };
  32444. /**
  32445. * Modifies the mesh geometry according to a displacement map.
  32446. * 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.
  32447. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32448. * This method returns nothing.
  32449. * @param url is a string, the URL from the image file is to be downloaded.
  32450. * @param minHeight is the lower limit of the displacement.
  32451. * @param maxHeight is the upper limit of the displacement.
  32452. * @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.
  32453. * @param uvOffset is an optional vector2 used to offset UV.
  32454. * @param uvScale is an optional vector2 used to scale UV.
  32455. * @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.
  32456. * @returns the Mesh.
  32457. */
  32458. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32459. var _this = this;
  32460. if (forceUpdate === void 0) { forceUpdate = false; }
  32461. var scene = this.getScene();
  32462. var onload = function (img) {
  32463. // Getting height map data
  32464. var canvas = document.createElement("canvas");
  32465. var context = canvas.getContext("2d");
  32466. var heightMapWidth = img.width;
  32467. var heightMapHeight = img.height;
  32468. canvas.width = heightMapWidth;
  32469. canvas.height = heightMapHeight;
  32470. context.drawImage(img, 0, 0);
  32471. // Create VertexData from map data
  32472. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32473. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32474. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32475. //execute success callback, if set
  32476. if (onSuccess) {
  32477. onSuccess(_this);
  32478. }
  32479. };
  32480. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32481. return this;
  32482. };
  32483. /**
  32484. * Modifies the mesh geometry according to a displacementMap buffer.
  32485. * 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.
  32486. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32487. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32488. * @param heightMapWidth is the width of the buffer image.
  32489. * @param heightMapHeight is the height of the buffer image.
  32490. * @param minHeight is the lower limit of the displacement.
  32491. * @param maxHeight is the upper limit of the displacement.
  32492. * @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.
  32493. * @param uvOffset is an optional vector2 used to offset UV.
  32494. * @param uvScale is an optional vector2 used to scale UV.
  32495. * @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.
  32496. * @returns the Mesh.
  32497. */
  32498. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32499. if (forceUpdate === void 0) { forceUpdate = false; }
  32500. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32501. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32502. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32503. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32504. return this;
  32505. }
  32506. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32507. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32508. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32509. var position = BABYLON.Vector3.Zero();
  32510. var normal = BABYLON.Vector3.Zero();
  32511. var uv = BABYLON.Vector2.Zero();
  32512. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32513. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32514. for (var index = 0; index < positions.length; index += 3) {
  32515. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32516. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32517. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32518. // Compute height
  32519. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32520. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32521. var pos = (u + v * heightMapWidth) * 4;
  32522. var r = buffer[pos] / 255.0;
  32523. var g = buffer[pos + 1] / 255.0;
  32524. var b = buffer[pos + 2] / 255.0;
  32525. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32526. normal.normalize();
  32527. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32528. position = position.add(normal);
  32529. position.toArray(positions, index);
  32530. }
  32531. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32532. if (forceUpdate) {
  32533. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32534. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32535. }
  32536. else {
  32537. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32538. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32539. }
  32540. return this;
  32541. };
  32542. /**
  32543. * Modify the mesh to get a flat shading rendering.
  32544. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32545. * This method returns the Mesh.
  32546. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32547. */
  32548. Mesh.prototype.convertToFlatShadedMesh = function () {
  32549. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32550. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32551. var kinds = this.getVerticesDataKinds();
  32552. var vbs = {};
  32553. var data = {};
  32554. var newdata = {};
  32555. var updatableNormals = false;
  32556. var kindIndex;
  32557. var kind;
  32558. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32559. kind = kinds[kindIndex];
  32560. var vertexBuffer = this.getVertexBuffer(kind);
  32561. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32562. updatableNormals = vertexBuffer.isUpdatable();
  32563. kinds.splice(kindIndex, 1);
  32564. kindIndex--;
  32565. continue;
  32566. }
  32567. vbs[kind] = vertexBuffer;
  32568. data[kind] = vbs[kind].getData();
  32569. newdata[kind] = [];
  32570. }
  32571. // Save previous submeshes
  32572. var previousSubmeshes = this.subMeshes.slice(0);
  32573. var indices = this.getIndices();
  32574. var totalIndices = this.getTotalIndices();
  32575. // Generating unique vertices per face
  32576. var index;
  32577. for (index = 0; index < totalIndices; index++) {
  32578. var vertexIndex = indices[index];
  32579. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32580. kind = kinds[kindIndex];
  32581. var stride = vbs[kind].getStrideSize();
  32582. for (var offset = 0; offset < stride; offset++) {
  32583. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32584. }
  32585. }
  32586. }
  32587. // Updating faces & normal
  32588. var normals = [];
  32589. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32590. for (index = 0; index < totalIndices; index += 3) {
  32591. indices[index] = index;
  32592. indices[index + 1] = index + 1;
  32593. indices[index + 2] = index + 2;
  32594. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32595. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32596. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32597. var p1p2 = p1.subtract(p2);
  32598. var p3p2 = p3.subtract(p2);
  32599. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32600. // Store same normals for every vertex
  32601. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32602. normals.push(normal.x);
  32603. normals.push(normal.y);
  32604. normals.push(normal.z);
  32605. }
  32606. }
  32607. this.setIndices(indices);
  32608. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32609. // Updating vertex buffers
  32610. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32611. kind = kinds[kindIndex];
  32612. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32613. }
  32614. // Updating submeshes
  32615. this.releaseSubMeshes();
  32616. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32617. var previousOne = previousSubmeshes[submeshIndex];
  32618. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32619. }
  32620. this.synchronizeInstances();
  32621. return this;
  32622. };
  32623. /**
  32624. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32625. * In other words, more vertices, no more indices and a single bigger VBO.
  32626. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32627. * Returns the Mesh.
  32628. */
  32629. Mesh.prototype.convertToUnIndexedMesh = function () {
  32630. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32631. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32632. var kinds = this.getVerticesDataKinds();
  32633. var vbs = {};
  32634. var data = {};
  32635. var newdata = {};
  32636. var kindIndex;
  32637. var kind;
  32638. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32639. kind = kinds[kindIndex];
  32640. var vertexBuffer = this.getVertexBuffer(kind);
  32641. vbs[kind] = vertexBuffer;
  32642. data[kind] = vbs[kind].getData();
  32643. newdata[kind] = [];
  32644. }
  32645. // Save previous submeshes
  32646. var previousSubmeshes = this.subMeshes.slice(0);
  32647. var indices = this.getIndices();
  32648. var totalIndices = this.getTotalIndices();
  32649. // Generating unique vertices per face
  32650. var index;
  32651. for (index = 0; index < totalIndices; index++) {
  32652. var vertexIndex = indices[index];
  32653. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32654. kind = kinds[kindIndex];
  32655. var stride = vbs[kind].getStrideSize();
  32656. for (var offset = 0; offset < stride; offset++) {
  32657. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32658. }
  32659. }
  32660. }
  32661. // Updating indices
  32662. for (index = 0; index < totalIndices; index += 3) {
  32663. indices[index] = index;
  32664. indices[index + 1] = index + 1;
  32665. indices[index + 2] = index + 2;
  32666. }
  32667. this.setIndices(indices);
  32668. // Updating vertex buffers
  32669. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32670. kind = kinds[kindIndex];
  32671. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32672. }
  32673. // Updating submeshes
  32674. this.releaseSubMeshes();
  32675. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32676. var previousOne = previousSubmeshes[submeshIndex];
  32677. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32678. }
  32679. this._unIndexed = true;
  32680. this.synchronizeInstances();
  32681. return this;
  32682. };
  32683. /**
  32684. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32685. * This method returns the Mesh.
  32686. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32687. */
  32688. Mesh.prototype.flipFaces = function (flipNormals) {
  32689. if (flipNormals === void 0) { flipNormals = false; }
  32690. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32691. var i;
  32692. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32693. for (i = 0; i < vertex_data.normals.length; i++) {
  32694. vertex_data.normals[i] *= -1;
  32695. }
  32696. }
  32697. if (vertex_data.indices) {
  32698. var temp;
  32699. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32700. // reassign indices
  32701. temp = vertex_data.indices[i + 1];
  32702. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32703. vertex_data.indices[i + 2] = temp;
  32704. }
  32705. }
  32706. vertex_data.applyToMesh(this);
  32707. return this;
  32708. };
  32709. // Instances
  32710. /**
  32711. * Creates a new InstancedMesh object from the mesh model.
  32712. * An instance shares the same properties and the same material than its model.
  32713. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32714. * Only these properties of each instance can then be set individually :
  32715. * - position
  32716. * - rotation
  32717. * - rotationQuaternion
  32718. * - setPivotMatrix
  32719. * - scaling
  32720. *
  32721. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32722. * Warning : this method is not supported for Line mesh and LineSystem
  32723. */
  32724. Mesh.prototype.createInstance = function (name) {
  32725. return new BABYLON.InstancedMesh(name, this);
  32726. };
  32727. /**
  32728. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32729. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32730. * This method returns the Mesh.
  32731. */
  32732. Mesh.prototype.synchronizeInstances = function () {
  32733. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32734. var instance = this.instances[instanceIndex];
  32735. instance._syncSubMeshes();
  32736. }
  32737. return this;
  32738. };
  32739. /**
  32740. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32741. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32742. * This should be used together with the simplification to avoid disappearing triangles.
  32743. * Returns the Mesh.
  32744. * @param successCallback an optional success callback to be called after the optimization finished.
  32745. */
  32746. Mesh.prototype.optimizeIndices = function (successCallback) {
  32747. var _this = this;
  32748. var indices = this.getIndices();
  32749. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32750. if (!positions || !indices) {
  32751. return this;
  32752. }
  32753. var vectorPositions = new Array();
  32754. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32755. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32756. }
  32757. var dupes = new Array();
  32758. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32759. var realPos = vectorPositions.length - 1 - iteration;
  32760. var testedPosition = vectorPositions[realPos];
  32761. for (var j = 0; j < realPos; ++j) {
  32762. var againstPosition = vectorPositions[j];
  32763. if (testedPosition.equals(againstPosition)) {
  32764. dupes[realPos] = j;
  32765. break;
  32766. }
  32767. }
  32768. }, function () {
  32769. for (var i = 0; i < indices.length; ++i) {
  32770. indices[i] = dupes[indices[i]] || indices[i];
  32771. }
  32772. //indices are now reordered
  32773. var originalSubMeshes = _this.subMeshes.slice(0);
  32774. _this.setIndices(indices);
  32775. _this.subMeshes = originalSubMeshes;
  32776. if (successCallback) {
  32777. successCallback(_this);
  32778. }
  32779. });
  32780. return this;
  32781. };
  32782. Mesh.prototype.serialize = function (serializationObject) {
  32783. serializationObject.name = this.name;
  32784. serializationObject.id = this.id;
  32785. serializationObject.type = this.getClassName();
  32786. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32787. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32788. }
  32789. serializationObject.position = this.position.asArray();
  32790. if (this.rotationQuaternion) {
  32791. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32792. }
  32793. else if (this.rotation) {
  32794. serializationObject.rotation = this.rotation.asArray();
  32795. }
  32796. serializationObject.scaling = this.scaling.asArray();
  32797. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32798. serializationObject.isEnabled = this.isEnabled(false);
  32799. serializationObject.isVisible = this.isVisible;
  32800. serializationObject.infiniteDistance = this.infiniteDistance;
  32801. serializationObject.pickable = this.isPickable;
  32802. serializationObject.receiveShadows = this.receiveShadows;
  32803. serializationObject.billboardMode = this.billboardMode;
  32804. serializationObject.visibility = this.visibility;
  32805. serializationObject.checkCollisions = this.checkCollisions;
  32806. serializationObject.isBlocker = this.isBlocker;
  32807. // Parent
  32808. if (this.parent) {
  32809. serializationObject.parentId = this.parent.id;
  32810. }
  32811. // Geometry
  32812. serializationObject.isUnIndexed = this.isUnIndexed;
  32813. var geometry = this._geometry;
  32814. if (geometry) {
  32815. var geometryId = geometry.id;
  32816. serializationObject.geometryId = geometryId;
  32817. // SubMeshes
  32818. serializationObject.subMeshes = [];
  32819. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32820. var subMesh = this.subMeshes[subIndex];
  32821. serializationObject.subMeshes.push({
  32822. materialIndex: subMesh.materialIndex,
  32823. verticesStart: subMesh.verticesStart,
  32824. verticesCount: subMesh.verticesCount,
  32825. indexStart: subMesh.indexStart,
  32826. indexCount: subMesh.indexCount
  32827. });
  32828. }
  32829. }
  32830. // Material
  32831. if (this.material) {
  32832. serializationObject.materialId = this.material.id;
  32833. }
  32834. else {
  32835. this.material = null;
  32836. }
  32837. // Morph targets
  32838. if (this.morphTargetManager) {
  32839. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32840. }
  32841. // Skeleton
  32842. if (this.skeleton) {
  32843. serializationObject.skeletonId = this.skeleton.id;
  32844. }
  32845. // Physics
  32846. //TODO implement correct serialization for physics impostors.
  32847. var impostor = this.getPhysicsImpostor();
  32848. if (impostor) {
  32849. serializationObject.physicsMass = impostor.getParam("mass");
  32850. serializationObject.physicsFriction = impostor.getParam("friction");
  32851. serializationObject.physicsRestitution = impostor.getParam("mass");
  32852. serializationObject.physicsImpostor = impostor.type;
  32853. }
  32854. // Metadata
  32855. if (this.metadata) {
  32856. serializationObject.metadata = this.metadata;
  32857. }
  32858. // Instances
  32859. serializationObject.instances = [];
  32860. for (var index = 0; index < this.instances.length; index++) {
  32861. var instance = this.instances[index];
  32862. if (instance.doNotSerialize) {
  32863. continue;
  32864. }
  32865. var serializationInstance = {
  32866. name: instance.name,
  32867. id: instance.id,
  32868. position: instance.position.asArray(),
  32869. scaling: instance.scaling.asArray()
  32870. };
  32871. if (instance.parent) {
  32872. serializationInstance.parentId = instance.parent.id;
  32873. }
  32874. if (instance.rotationQuaternion) {
  32875. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32876. }
  32877. else if (instance.rotation) {
  32878. serializationInstance.rotation = instance.rotation.asArray();
  32879. }
  32880. serializationObject.instances.push(serializationInstance);
  32881. // Animations
  32882. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32883. serializationInstance.ranges = instance.serializeAnimationRanges();
  32884. }
  32885. //
  32886. // Animations
  32887. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32888. serializationObject.ranges = this.serializeAnimationRanges();
  32889. // Layer mask
  32890. serializationObject.layerMask = this.layerMask;
  32891. // Alpha
  32892. serializationObject.alphaIndex = this.alphaIndex;
  32893. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32894. // Overlay
  32895. serializationObject.overlayAlpha = this.overlayAlpha;
  32896. serializationObject.overlayColor = this.overlayColor.asArray();
  32897. serializationObject.renderOverlay = this.renderOverlay;
  32898. // Fog
  32899. serializationObject.applyFog = this.applyFog;
  32900. // Action Manager
  32901. if (this.actionManager) {
  32902. serializationObject.actions = this.actionManager.serialize(this.name);
  32903. }
  32904. };
  32905. /** @hidden */
  32906. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32907. if (!this.geometry) {
  32908. return;
  32909. }
  32910. this._markSubMeshesAsAttributesDirty();
  32911. var morphTargetManager = this._morphTargetManager;
  32912. if (morphTargetManager && morphTargetManager.vertexCount) {
  32913. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32914. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32915. this.morphTargetManager = null;
  32916. return;
  32917. }
  32918. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32919. var morphTarget = morphTargetManager.getActiveTarget(index);
  32920. var positions = morphTarget.getPositions();
  32921. if (!positions) {
  32922. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32923. return;
  32924. }
  32925. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32926. var normals = morphTarget.getNormals();
  32927. if (normals) {
  32928. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32929. }
  32930. var tangents = morphTarget.getTangents();
  32931. if (tangents) {
  32932. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32933. }
  32934. }
  32935. }
  32936. else {
  32937. var index = 0;
  32938. // Positions
  32939. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32940. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32941. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32942. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32943. }
  32944. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32945. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32946. }
  32947. index++;
  32948. }
  32949. }
  32950. };
  32951. // Statics
  32952. /**
  32953. * Returns a new Mesh object parsed from the source provided.
  32954. * The parameter `parsedMesh` is the source.
  32955. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32956. */
  32957. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32958. var mesh;
  32959. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32960. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32961. }
  32962. else {
  32963. mesh = new Mesh(parsedMesh.name, scene);
  32964. }
  32965. mesh.id = parsedMesh.id;
  32966. if (BABYLON.Tags) {
  32967. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32968. }
  32969. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32970. if (parsedMesh.metadata !== undefined) {
  32971. mesh.metadata = parsedMesh.metadata;
  32972. }
  32973. if (parsedMesh.rotationQuaternion) {
  32974. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32975. }
  32976. else if (parsedMesh.rotation) {
  32977. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32978. }
  32979. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32980. if (parsedMesh.localMatrix) {
  32981. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32982. }
  32983. else if (parsedMesh.pivotMatrix) {
  32984. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32985. }
  32986. mesh.setEnabled(parsedMesh.isEnabled);
  32987. mesh.isVisible = parsedMesh.isVisible;
  32988. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32989. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32990. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32991. if (parsedMesh.applyFog !== undefined) {
  32992. mesh.applyFog = parsedMesh.applyFog;
  32993. }
  32994. if (parsedMesh.pickable !== undefined) {
  32995. mesh.isPickable = parsedMesh.pickable;
  32996. }
  32997. if (parsedMesh.alphaIndex !== undefined) {
  32998. mesh.alphaIndex = parsedMesh.alphaIndex;
  32999. }
  33000. mesh.receiveShadows = parsedMesh.receiveShadows;
  33001. mesh.billboardMode = parsedMesh.billboardMode;
  33002. if (parsedMesh.visibility !== undefined) {
  33003. mesh.visibility = parsedMesh.visibility;
  33004. }
  33005. mesh.checkCollisions = parsedMesh.checkCollisions;
  33006. if (parsedMesh.isBlocker !== undefined) {
  33007. mesh.isBlocker = parsedMesh.isBlocker;
  33008. }
  33009. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33010. // freezeWorldMatrix
  33011. if (parsedMesh.freezeWorldMatrix) {
  33012. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33013. }
  33014. // Parent
  33015. if (parsedMesh.parentId) {
  33016. mesh._waitingParentId = parsedMesh.parentId;
  33017. }
  33018. // Actions
  33019. if (parsedMesh.actions !== undefined) {
  33020. mesh._waitingActions = parsedMesh.actions;
  33021. }
  33022. // Overlay
  33023. if (parsedMesh.overlayAlpha !== undefined) {
  33024. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33025. }
  33026. if (parsedMesh.overlayColor !== undefined) {
  33027. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33028. }
  33029. if (parsedMesh.renderOverlay !== undefined) {
  33030. mesh.renderOverlay = parsedMesh.renderOverlay;
  33031. }
  33032. // Geometry
  33033. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33034. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33035. if (parsedMesh.delayLoadingFile) {
  33036. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33037. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33038. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33039. if (parsedMesh._binaryInfo) {
  33040. mesh._binaryInfo = parsedMesh._binaryInfo;
  33041. }
  33042. mesh._delayInfo = [];
  33043. if (parsedMesh.hasUVs) {
  33044. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33045. }
  33046. if (parsedMesh.hasUVs2) {
  33047. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33048. }
  33049. if (parsedMesh.hasUVs3) {
  33050. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33051. }
  33052. if (parsedMesh.hasUVs4) {
  33053. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33054. }
  33055. if (parsedMesh.hasUVs5) {
  33056. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33057. }
  33058. if (parsedMesh.hasUVs6) {
  33059. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33060. }
  33061. if (parsedMesh.hasColors) {
  33062. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33063. }
  33064. if (parsedMesh.hasMatricesIndices) {
  33065. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33066. }
  33067. if (parsedMesh.hasMatricesWeights) {
  33068. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33069. }
  33070. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33071. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33072. mesh._checkDelayState();
  33073. }
  33074. }
  33075. else {
  33076. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33077. }
  33078. // Material
  33079. if (parsedMesh.materialId) {
  33080. mesh.setMaterialByID(parsedMesh.materialId);
  33081. }
  33082. else {
  33083. mesh.material = null;
  33084. }
  33085. // Morph targets
  33086. if (parsedMesh.morphTargetManagerId > -1) {
  33087. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33088. }
  33089. // Skeleton
  33090. if (parsedMesh.skeletonId > -1) {
  33091. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33092. if (parsedMesh.numBoneInfluencers) {
  33093. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33094. }
  33095. }
  33096. // Animations
  33097. if (parsedMesh.animations) {
  33098. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33099. var parsedAnimation = parsedMesh.animations[animationIndex];
  33100. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33101. }
  33102. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33103. }
  33104. if (parsedMesh.autoAnimate) {
  33105. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33106. }
  33107. // Layer Mask
  33108. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33109. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33110. }
  33111. else {
  33112. mesh.layerMask = 0x0FFFFFFF;
  33113. }
  33114. // Physics
  33115. if (parsedMesh.physicsImpostor) {
  33116. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33117. mass: parsedMesh.physicsMass,
  33118. friction: parsedMesh.physicsFriction,
  33119. restitution: parsedMesh.physicsRestitution
  33120. }, scene);
  33121. }
  33122. // Instances
  33123. if (parsedMesh.instances) {
  33124. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33125. var parsedInstance = parsedMesh.instances[index];
  33126. var instance = mesh.createInstance(parsedInstance.name);
  33127. if (parsedInstance.id) {
  33128. instance.id = parsedInstance.id;
  33129. }
  33130. if (BABYLON.Tags) {
  33131. if (parsedInstance.tags) {
  33132. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33133. }
  33134. else {
  33135. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33136. }
  33137. }
  33138. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33139. if (parsedInstance.parentId) {
  33140. instance._waitingParentId = parsedInstance.parentId;
  33141. }
  33142. if (parsedInstance.rotationQuaternion) {
  33143. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33144. }
  33145. else if (parsedInstance.rotation) {
  33146. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33147. }
  33148. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33149. instance.checkCollisions = mesh.checkCollisions;
  33150. if (parsedMesh.animations) {
  33151. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33152. parsedAnimation = parsedMesh.animations[animationIndex];
  33153. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33154. }
  33155. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33156. if (parsedMesh.autoAnimate) {
  33157. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33158. }
  33159. }
  33160. }
  33161. }
  33162. return mesh;
  33163. };
  33164. /**
  33165. * Creates a ribbon mesh.
  33166. * Please consider using the same method from the MeshBuilder class instead.
  33167. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33168. *
  33169. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33170. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33171. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33172. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33173. * 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.
  33174. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33175. * 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
  33176. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33177. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33179. */
  33180. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33181. if (closeArray === void 0) { closeArray = false; }
  33182. if (updatable === void 0) { updatable = false; }
  33183. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33184. pathArray: pathArray,
  33185. closeArray: closeArray,
  33186. closePath: closePath,
  33187. offset: offset,
  33188. updatable: updatable,
  33189. sideOrientation: sideOrientation,
  33190. instance: instance
  33191. }, scene);
  33192. };
  33193. /**
  33194. * Creates a plane polygonal mesh. By default, this is a disc.
  33195. * Please consider using the same method from the MeshBuilder class instead.
  33196. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33197. * 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.
  33198. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33199. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33201. */
  33202. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33203. if (scene === void 0) { scene = null; }
  33204. var options = {
  33205. radius: radius,
  33206. tessellation: tessellation,
  33207. sideOrientation: sideOrientation,
  33208. updatable: updatable
  33209. };
  33210. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33211. };
  33212. /**
  33213. * Creates a box mesh.
  33214. * Please consider using the same method from the MeshBuilder class instead.
  33215. * The parameter `size` sets the size (float) of each box side (default 1).
  33216. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33217. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33219. */
  33220. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33221. if (scene === void 0) { scene = null; }
  33222. var options = {
  33223. size: size,
  33224. sideOrientation: sideOrientation,
  33225. updatable: updatable
  33226. };
  33227. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33228. };
  33229. /**
  33230. * Creates a sphere mesh.
  33231. * Please consider using the same method from the MeshBuilder class instead.
  33232. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33233. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33234. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33235. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33237. */
  33238. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33239. var options = {
  33240. segments: segments,
  33241. diameterX: diameter,
  33242. diameterY: diameter,
  33243. diameterZ: diameter,
  33244. sideOrientation: sideOrientation,
  33245. updatable: updatable
  33246. };
  33247. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33248. };
  33249. /**
  33250. * Creates a cylinder or a cone mesh.
  33251. * Please consider using the same method from the MeshBuilder class instead.
  33252. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33253. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33254. * 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.
  33255. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33256. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33257. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33258. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33260. */
  33261. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33262. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33263. if (scene !== undefined) {
  33264. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33265. updatable = scene;
  33266. }
  33267. scene = subdivisions;
  33268. subdivisions = 1;
  33269. }
  33270. var options = {
  33271. height: height,
  33272. diameterTop: diameterTop,
  33273. diameterBottom: diameterBottom,
  33274. tessellation: tessellation,
  33275. subdivisions: subdivisions,
  33276. sideOrientation: sideOrientation,
  33277. updatable: updatable
  33278. };
  33279. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33280. };
  33281. // Torus (Code from SharpDX.org)
  33282. /**
  33283. * Creates a torus mesh.
  33284. * Please consider using the same method from the MeshBuilder class instead.
  33285. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33286. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33287. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33288. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33289. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33291. */
  33292. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33293. var options = {
  33294. diameter: diameter,
  33295. thickness: thickness,
  33296. tessellation: tessellation,
  33297. sideOrientation: sideOrientation,
  33298. updatable: updatable
  33299. };
  33300. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33301. };
  33302. /**
  33303. * Creates a torus knot mesh.
  33304. * Please consider using the same method from the MeshBuilder class instead.
  33305. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33306. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33307. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33308. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33309. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33310. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33311. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33312. */
  33313. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33314. var options = {
  33315. radius: radius,
  33316. tube: tube,
  33317. radialSegments: radialSegments,
  33318. tubularSegments: tubularSegments,
  33319. p: p,
  33320. q: q,
  33321. sideOrientation: sideOrientation,
  33322. updatable: updatable
  33323. };
  33324. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33325. };
  33326. /**
  33327. * Creates a line mesh.
  33328. * Please consider using the same method from the MeshBuilder class instead.
  33329. * 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.
  33330. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33331. * The parameter `points` is an array successive Vector3.
  33332. * 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
  33333. * When updating an instance, remember that only point positions can change, not the number of points.
  33334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33335. */
  33336. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33337. if (scene === void 0) { scene = null; }
  33338. if (updatable === void 0) { updatable = false; }
  33339. if (instance === void 0) { instance = null; }
  33340. var options = {
  33341. points: points,
  33342. updatable: updatable,
  33343. instance: instance
  33344. };
  33345. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33346. };
  33347. /**
  33348. * Creates a dashed line mesh.
  33349. * Please consider using the same method from the MeshBuilder class instead.
  33350. * 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.
  33351. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33352. * The parameter `points` is an array successive Vector3.
  33353. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33354. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33355. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33356. * 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
  33357. * When updating an instance, remember that only point positions can change, not the number of points.
  33358. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33359. */
  33360. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33361. if (scene === void 0) { scene = null; }
  33362. var options = {
  33363. points: points,
  33364. dashSize: dashSize,
  33365. gapSize: gapSize,
  33366. dashNb: dashNb,
  33367. updatable: updatable,
  33368. instance: instance
  33369. };
  33370. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33371. };
  33372. /**
  33373. * Creates a polygon mesh.
  33374. * Please consider using the same method from the MeshBuilder class instead.
  33375. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33376. * 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.
  33377. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33378. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33379. * Remember you can only change the shape positions, not their number when updating a polygon.
  33380. */
  33381. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33382. var options = {
  33383. shape: shape,
  33384. holes: holes,
  33385. updatable: updatable,
  33386. sideOrientation: sideOrientation
  33387. };
  33388. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33389. };
  33390. /**
  33391. * Creates an extruded polygon mesh, with depth in the Y direction.
  33392. * Please consider using the same method from the MeshBuilder class instead.
  33393. */
  33394. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33395. var options = {
  33396. shape: shape,
  33397. holes: holes,
  33398. depth: depth,
  33399. updatable: updatable,
  33400. sideOrientation: sideOrientation
  33401. };
  33402. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33403. };
  33404. /**
  33405. * Creates an extruded shape mesh.
  33406. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33407. * Please consider using the same method from the MeshBuilder class instead.
  33408. *
  33409. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33410. * 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
  33411. * extruded along the Z axis.
  33412. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33413. * 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.
  33414. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33415. * 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
  33416. * 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
  33417. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33418. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33419. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33420. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33421. */
  33422. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33423. if (scene === void 0) { scene = null; }
  33424. var options = {
  33425. shape: shape,
  33426. path: path,
  33427. scale: scale,
  33428. rotation: rotation,
  33429. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33430. sideOrientation: sideOrientation,
  33431. instance: instance,
  33432. updatable: updatable
  33433. };
  33434. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33435. };
  33436. /**
  33437. * Creates an custom extruded shape mesh.
  33438. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33439. * Please consider using the same method from the MeshBuilder class instead.
  33440. *
  33441. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33442. * 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
  33443. * extruded along the Z axis.
  33444. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33445. * 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
  33446. * and the distance of this point from the begining of the path :
  33447. * ```javascript
  33448. * var rotationFunction = function(i, distance) {
  33449. * // do things
  33450. * return rotationValue; }
  33451. * ```
  33452. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33453. * 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
  33454. * and the distance of this point from the begining of the path :
  33455. * ```javascript
  33456. * var scaleFunction = function(i, distance) {
  33457. * // do things
  33458. * return scaleValue;}
  33459. * ```
  33460. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33461. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33462. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33463. * 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
  33464. * 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
  33465. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33467. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33469. */
  33470. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33471. var options = {
  33472. shape: shape,
  33473. path: path,
  33474. scaleFunction: scaleFunction,
  33475. rotationFunction: rotationFunction,
  33476. ribbonCloseArray: ribbonCloseArray,
  33477. ribbonClosePath: ribbonClosePath,
  33478. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33479. sideOrientation: sideOrientation,
  33480. instance: instance,
  33481. updatable: updatable
  33482. };
  33483. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33484. };
  33485. /**
  33486. * Creates lathe mesh.
  33487. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33488. * Please consider using the same method from the MeshBuilder class instead.
  33489. * 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
  33490. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33491. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33492. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33494. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33496. */
  33497. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33498. var options = {
  33499. shape: shape,
  33500. radius: radius,
  33501. tessellation: tessellation,
  33502. sideOrientation: sideOrientation,
  33503. updatable: updatable
  33504. };
  33505. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33506. };
  33507. /**
  33508. * Creates a plane mesh.
  33509. * Please consider using the same method from the MeshBuilder class instead.
  33510. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33511. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33512. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33514. */
  33515. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33516. var options = {
  33517. size: size,
  33518. width: size,
  33519. height: size,
  33520. sideOrientation: sideOrientation,
  33521. updatable: updatable
  33522. };
  33523. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33524. };
  33525. /**
  33526. * Creates a ground mesh.
  33527. * Please consider using the same method from the MeshBuilder class instead.
  33528. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33529. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33530. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33531. */
  33532. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33533. var options = {
  33534. width: width,
  33535. height: height,
  33536. subdivisions: subdivisions,
  33537. updatable: updatable
  33538. };
  33539. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33540. };
  33541. /**
  33542. * Creates a tiled ground mesh.
  33543. * Please consider using the same method from the MeshBuilder class instead.
  33544. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33545. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33546. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33547. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33548. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33549. * numbers of subdivisions on the ground width and height of each tile.
  33550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33551. */
  33552. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33553. var options = {
  33554. xmin: xmin,
  33555. zmin: zmin,
  33556. xmax: xmax,
  33557. zmax: zmax,
  33558. subdivisions: subdivisions,
  33559. precision: precision,
  33560. updatable: updatable
  33561. };
  33562. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33563. };
  33564. /**
  33565. * Creates a ground mesh from a height map.
  33566. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33567. * Please consider using the same method from the MeshBuilder class instead.
  33568. * The parameter `url` sets the URL of the height map image resource.
  33569. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33570. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33571. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33572. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33573. * 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).
  33574. * This function is passed the newly built mesh :
  33575. * ```javascript
  33576. * function(mesh) { // do things
  33577. * return; }
  33578. * ```
  33579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33580. */
  33581. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33582. var options = {
  33583. width: width,
  33584. height: height,
  33585. subdivisions: subdivisions,
  33586. minHeight: minHeight,
  33587. maxHeight: maxHeight,
  33588. updatable: updatable,
  33589. onReady: onReady
  33590. };
  33591. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33592. };
  33593. /**
  33594. * Creates a tube mesh.
  33595. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33596. * Please consider using the same method from the MeshBuilder class instead.
  33597. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33598. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33599. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33600. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33601. * 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.
  33602. * It must return a radius value (positive float) :
  33603. * ```javascript
  33604. * var radiusFunction = function(i, distance) {
  33605. * // do things
  33606. * return radius; }
  33607. * ```
  33608. * 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
  33609. * 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
  33610. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33611. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33612. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33613. */
  33614. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33615. var options = {
  33616. path: path,
  33617. radius: radius,
  33618. tessellation: tessellation,
  33619. radiusFunction: radiusFunction,
  33620. arc: 1,
  33621. cap: cap,
  33622. updatable: updatable,
  33623. sideOrientation: sideOrientation,
  33624. instance: instance
  33625. };
  33626. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33627. };
  33628. /**
  33629. * Creates a polyhedron mesh.
  33630. * Please consider using the same method from the MeshBuilder class instead.
  33631. * 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
  33632. * to choose the wanted type.
  33633. * The parameter `size` (positive float, default 1) sets the polygon size.
  33634. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33635. * 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`.
  33636. * 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
  33637. * 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)`).
  33638. * 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
  33639. * 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.
  33640. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33641. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33643. */
  33644. Mesh.CreatePolyhedron = function (name, options, scene) {
  33645. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33646. };
  33647. /**
  33648. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33649. * Please consider using the same method from the MeshBuilder class instead.
  33650. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33651. * 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`).
  33652. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33653. * 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.
  33654. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33655. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33656. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33657. */
  33658. Mesh.CreateIcoSphere = function (name, options, scene) {
  33659. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33660. };
  33661. /**
  33662. * Creates a decal mesh.
  33663. * Please consider using the same method from the MeshBuilder class instead.
  33664. * 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.
  33665. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33666. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33667. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33668. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33669. */
  33670. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33671. var options = {
  33672. position: position,
  33673. normal: normal,
  33674. size: size,
  33675. angle: angle
  33676. };
  33677. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33678. };
  33679. // Skeletons
  33680. /**
  33681. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33682. */
  33683. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33684. if (!this._sourcePositions) {
  33685. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33686. if (!source) {
  33687. return this._sourcePositions;
  33688. }
  33689. this._sourcePositions = new Float32Array(source);
  33690. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33691. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33692. }
  33693. }
  33694. return this._sourcePositions;
  33695. };
  33696. /**
  33697. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33698. */
  33699. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33700. if (!this._sourceNormals) {
  33701. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33702. if (!source) {
  33703. return this._sourceNormals;
  33704. }
  33705. this._sourceNormals = new Float32Array(source);
  33706. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33707. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33708. }
  33709. }
  33710. return this._sourceNormals;
  33711. };
  33712. /**
  33713. * Updates the vertex buffer by applying transformation from the bones.
  33714. * Returns the Mesh.
  33715. *
  33716. * @param {skeleton} skeleton to apply
  33717. */
  33718. Mesh.prototype.applySkeleton = function (skeleton) {
  33719. if (!this.geometry) {
  33720. return this;
  33721. }
  33722. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33723. return this;
  33724. }
  33725. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33726. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33727. return this;
  33728. }
  33729. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33730. return this;
  33731. }
  33732. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33733. return this;
  33734. }
  33735. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33736. return this;
  33737. }
  33738. if (!this._sourcePositions) {
  33739. var submeshes = this.subMeshes.slice();
  33740. this.setPositionsForCPUSkinning();
  33741. this.subMeshes = submeshes;
  33742. }
  33743. if (!this._sourceNormals) {
  33744. this.setNormalsForCPUSkinning();
  33745. }
  33746. // positionsData checks for not being Float32Array will only pass at most once
  33747. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33748. if (!positionsData) {
  33749. return this;
  33750. }
  33751. if (!(positionsData instanceof Float32Array)) {
  33752. positionsData = new Float32Array(positionsData);
  33753. }
  33754. // normalsData checks for not being Float32Array will only pass at most once
  33755. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33756. if (!normalsData) {
  33757. return this;
  33758. }
  33759. if (!(normalsData instanceof Float32Array)) {
  33760. normalsData = new Float32Array(normalsData);
  33761. }
  33762. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33763. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33764. if (!matricesWeightsData || !matricesIndicesData) {
  33765. return this;
  33766. }
  33767. var needExtras = this.numBoneInfluencers > 4;
  33768. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33769. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33770. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33771. var tempVector3 = BABYLON.Vector3.Zero();
  33772. var finalMatrix = new BABYLON.Matrix();
  33773. var tempMatrix = new BABYLON.Matrix();
  33774. var matWeightIdx = 0;
  33775. var inf;
  33776. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33777. var weight;
  33778. for (inf = 0; inf < 4; inf++) {
  33779. weight = matricesWeightsData[matWeightIdx + inf];
  33780. if (weight > 0) {
  33781. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33782. finalMatrix.addToSelf(tempMatrix);
  33783. }
  33784. }
  33785. if (needExtras) {
  33786. for (inf = 0; inf < 4; inf++) {
  33787. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33788. if (weight > 0) {
  33789. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33790. finalMatrix.addToSelf(tempMatrix);
  33791. }
  33792. }
  33793. }
  33794. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33795. tempVector3.toArray(positionsData, index);
  33796. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33797. tempVector3.toArray(normalsData, index);
  33798. finalMatrix.reset();
  33799. }
  33800. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33801. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33802. return this;
  33803. };
  33804. // Tools
  33805. /**
  33806. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33807. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33808. */
  33809. Mesh.MinMax = function (meshes) {
  33810. var minVector = null;
  33811. var maxVector = null;
  33812. meshes.forEach(function (mesh, index, array) {
  33813. var boundingInfo = mesh.getBoundingInfo();
  33814. var boundingBox = boundingInfo.boundingBox;
  33815. if (!minVector || !maxVector) {
  33816. minVector = boundingBox.minimumWorld;
  33817. maxVector = boundingBox.maximumWorld;
  33818. }
  33819. else {
  33820. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33821. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33822. }
  33823. });
  33824. if (!minVector || !maxVector) {
  33825. return {
  33826. min: BABYLON.Vector3.Zero(),
  33827. max: BABYLON.Vector3.Zero()
  33828. };
  33829. }
  33830. return {
  33831. min: minVector,
  33832. max: maxVector
  33833. };
  33834. };
  33835. /**
  33836. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33837. */
  33838. Mesh.Center = function (meshesOrMinMaxVector) {
  33839. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33840. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33841. };
  33842. /**
  33843. * Merge the array of meshes into a single mesh for performance reasons.
  33844. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  33845. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  33846. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33847. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33848. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33849. */
  33850. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33851. if (disposeSource === void 0) { disposeSource = true; }
  33852. var index;
  33853. if (!allow32BitsIndices) {
  33854. var totalVertices = 0;
  33855. // Counting vertices
  33856. for (index = 0; index < meshes.length; index++) {
  33857. if (meshes[index]) {
  33858. totalVertices += meshes[index].getTotalVertices();
  33859. if (totalVertices > 65536) {
  33860. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33861. return null;
  33862. }
  33863. }
  33864. }
  33865. }
  33866. // Merge
  33867. var vertexData = null;
  33868. var otherVertexData;
  33869. var indiceArray = new Array();
  33870. var source = null;
  33871. for (index = 0; index < meshes.length; index++) {
  33872. if (meshes[index]) {
  33873. var wm = meshes[index].computeWorldMatrix(true);
  33874. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33875. otherVertexData.transform(wm);
  33876. if (vertexData) {
  33877. vertexData.merge(otherVertexData, allow32BitsIndices);
  33878. }
  33879. else {
  33880. vertexData = otherVertexData;
  33881. source = meshes[index];
  33882. }
  33883. if (subdivideWithSubMeshes) {
  33884. indiceArray.push(meshes[index].getTotalIndices());
  33885. }
  33886. }
  33887. }
  33888. source = source;
  33889. if (!meshSubclass) {
  33890. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33891. }
  33892. vertexData.applyToMesh(meshSubclass);
  33893. // Setting properties
  33894. meshSubclass.material = source.material;
  33895. meshSubclass.checkCollisions = source.checkCollisions;
  33896. // Cleaning
  33897. if (disposeSource) {
  33898. for (index = 0; index < meshes.length; index++) {
  33899. if (meshes[index]) {
  33900. meshes[index].dispose();
  33901. }
  33902. }
  33903. }
  33904. // Subdivide
  33905. if (subdivideWithSubMeshes) {
  33906. //-- removal of global submesh
  33907. meshSubclass.releaseSubMeshes();
  33908. index = 0;
  33909. var offset = 0;
  33910. //-- apply subdivision according to index table
  33911. while (index < indiceArray.length) {
  33912. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33913. offset += indiceArray[index];
  33914. index++;
  33915. }
  33916. }
  33917. return meshSubclass;
  33918. };
  33919. // Consts
  33920. Mesh._FRONTSIDE = 0;
  33921. Mesh._BACKSIDE = 1;
  33922. Mesh._DOUBLESIDE = 2;
  33923. Mesh._DEFAULTSIDE = 0;
  33924. Mesh._NO_CAP = 0;
  33925. Mesh._CAP_START = 1;
  33926. Mesh._CAP_END = 2;
  33927. Mesh._CAP_ALL = 3;
  33928. return Mesh;
  33929. }(BABYLON.AbstractMesh));
  33930. BABYLON.Mesh = Mesh;
  33931. })(BABYLON || (BABYLON = {}));
  33932. //# sourceMappingURL=babylon.mesh.js.map
  33933. var BABYLON;
  33934. (function (BABYLON) {
  33935. var BaseSubMesh = /** @class */ (function () {
  33936. function BaseSubMesh() {
  33937. }
  33938. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33939. get: function () {
  33940. return this._materialEffect;
  33941. },
  33942. enumerable: true,
  33943. configurable: true
  33944. });
  33945. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33946. if (defines === void 0) { defines = null; }
  33947. if (this._materialEffect === effect) {
  33948. if (!effect) {
  33949. this._materialDefines = null;
  33950. }
  33951. return;
  33952. }
  33953. this._materialDefines = defines;
  33954. this._materialEffect = effect;
  33955. };
  33956. return BaseSubMesh;
  33957. }());
  33958. BABYLON.BaseSubMesh = BaseSubMesh;
  33959. var SubMesh = /** @class */ (function (_super) {
  33960. __extends(SubMesh, _super);
  33961. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33962. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33963. var _this = _super.call(this) || this;
  33964. _this.materialIndex = materialIndex;
  33965. _this.verticesStart = verticesStart;
  33966. _this.verticesCount = verticesCount;
  33967. _this.indexStart = indexStart;
  33968. _this.indexCount = indexCount;
  33969. /** @hidden */
  33970. _this._renderId = 0;
  33971. _this._mesh = mesh;
  33972. _this._renderingMesh = renderingMesh || mesh;
  33973. mesh.subMeshes.push(_this);
  33974. _this._trianglePlanes = [];
  33975. _this._id = mesh.subMeshes.length - 1;
  33976. if (createBoundingBox) {
  33977. _this.refreshBoundingInfo();
  33978. mesh.computeWorldMatrix(true);
  33979. }
  33980. return _this;
  33981. }
  33982. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33983. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33984. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33985. };
  33986. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33987. get: function () {
  33988. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33989. },
  33990. enumerable: true,
  33991. configurable: true
  33992. });
  33993. /**
  33994. * Returns the submesh BoudingInfo object.
  33995. */
  33996. SubMesh.prototype.getBoundingInfo = function () {
  33997. if (this.IsGlobal) {
  33998. return this._mesh.getBoundingInfo();
  33999. }
  34000. return this._boundingInfo;
  34001. };
  34002. /**
  34003. * Sets the submesh BoundingInfo.
  34004. * Return the SubMesh.
  34005. */
  34006. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34007. this._boundingInfo = boundingInfo;
  34008. return this;
  34009. };
  34010. /**
  34011. * Returns the mesh of the current submesh.
  34012. */
  34013. SubMesh.prototype.getMesh = function () {
  34014. return this._mesh;
  34015. };
  34016. /**
  34017. * Returns the rendering mesh of the submesh.
  34018. */
  34019. SubMesh.prototype.getRenderingMesh = function () {
  34020. return this._renderingMesh;
  34021. };
  34022. /**
  34023. * Returns the submesh material.
  34024. */
  34025. SubMesh.prototype.getMaterial = function () {
  34026. var rootMaterial = this._renderingMesh.material;
  34027. if (rootMaterial === null || rootMaterial === undefined) {
  34028. return this._mesh.getScene().defaultMaterial;
  34029. }
  34030. else if (rootMaterial.getSubMaterial) {
  34031. var multiMaterial = rootMaterial;
  34032. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34033. if (this._currentMaterial !== effectiveMaterial) {
  34034. this._currentMaterial = effectiveMaterial;
  34035. this._materialDefines = null;
  34036. }
  34037. return effectiveMaterial;
  34038. }
  34039. return rootMaterial;
  34040. };
  34041. // Methods
  34042. /**
  34043. * Sets a new updated BoundingInfo object to the submesh.
  34044. * Returns the SubMesh.
  34045. */
  34046. SubMesh.prototype.refreshBoundingInfo = function () {
  34047. this._lastColliderWorldVertices = null;
  34048. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34049. return this;
  34050. }
  34051. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34052. if (!data) {
  34053. this._boundingInfo = this._mesh.getBoundingInfo();
  34054. return this;
  34055. }
  34056. var indices = this._renderingMesh.getIndices();
  34057. var extend;
  34058. //is this the only submesh?
  34059. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34060. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34061. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34062. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34063. }
  34064. else {
  34065. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34066. }
  34067. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34068. return this;
  34069. };
  34070. /** @hidden */
  34071. SubMesh.prototype._checkCollision = function (collider) {
  34072. var boundingInfo = this.getBoundingInfo();
  34073. return boundingInfo._checkCollision(collider);
  34074. };
  34075. /**
  34076. * Updates the submesh BoundingInfo.
  34077. * Returns the Submesh.
  34078. */
  34079. SubMesh.prototype.updateBoundingInfo = function (world) {
  34080. var boundingInfo = this.getBoundingInfo();
  34081. if (!boundingInfo) {
  34082. this.refreshBoundingInfo();
  34083. boundingInfo = this.getBoundingInfo();
  34084. }
  34085. boundingInfo.update(world);
  34086. return this;
  34087. };
  34088. /**
  34089. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34090. * Boolean returned.
  34091. */
  34092. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34093. var boundingInfo = this.getBoundingInfo();
  34094. if (!boundingInfo) {
  34095. return false;
  34096. }
  34097. return boundingInfo.isInFrustum(frustumPlanes);
  34098. };
  34099. /**
  34100. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34101. * Boolean returned.
  34102. */
  34103. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34104. var boundingInfo = this.getBoundingInfo();
  34105. if (!boundingInfo) {
  34106. return false;
  34107. }
  34108. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34109. };
  34110. /**
  34111. * Renders the submesh.
  34112. * Returns it.
  34113. */
  34114. SubMesh.prototype.render = function (enableAlphaMode) {
  34115. this._renderingMesh.render(this, enableAlphaMode);
  34116. return this;
  34117. };
  34118. /**
  34119. * Returns a new Index Buffer.
  34120. * Type returned : WebGLBuffer.
  34121. */
  34122. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34123. if (!this._linesIndexBuffer) {
  34124. var linesIndices = [];
  34125. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34126. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34127. }
  34128. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34129. this.linesIndexCount = linesIndices.length;
  34130. }
  34131. return this._linesIndexBuffer;
  34132. };
  34133. /**
  34134. * True is the passed Ray intersects the submesh bounding box.
  34135. * Boolean returned.
  34136. */
  34137. SubMesh.prototype.canIntersects = function (ray) {
  34138. var boundingInfo = this.getBoundingInfo();
  34139. if (!boundingInfo) {
  34140. return false;
  34141. }
  34142. return ray.intersectsBox(boundingInfo.boundingBox);
  34143. };
  34144. /**
  34145. * Returns an object IntersectionInfo.
  34146. */
  34147. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34148. var intersectInfo = null;
  34149. var material = this.getMaterial();
  34150. if (!material) {
  34151. return null;
  34152. }
  34153. switch (material.fillMode) {
  34154. case BABYLON.Material.PointListDrawMode:
  34155. case BABYLON.Material.LineListDrawMode:
  34156. case BABYLON.Material.LineLoopDrawMode:
  34157. case BABYLON.Material.LineStripDrawMode:
  34158. case BABYLON.Material.TriangleFanDrawMode:
  34159. case BABYLON.Material.TriangleStripDrawMode:
  34160. return null;
  34161. }
  34162. // LineMesh first as it's also a Mesh...
  34163. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34164. var lineMesh = this._mesh;
  34165. // Line test
  34166. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34167. var p0 = positions[indices[index]];
  34168. var p1 = positions[indices[index + 1]];
  34169. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34170. if (length < 0) {
  34171. continue;
  34172. }
  34173. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34174. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34175. if (fastCheck) {
  34176. break;
  34177. }
  34178. }
  34179. }
  34180. }
  34181. else {
  34182. // Triangles test
  34183. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34184. var p0 = positions[indices[index]];
  34185. var p1 = positions[indices[index + 1]];
  34186. var p2 = positions[indices[index + 2]];
  34187. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34188. if (currentIntersectInfo) {
  34189. if (currentIntersectInfo.distance < 0) {
  34190. continue;
  34191. }
  34192. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34193. intersectInfo = currentIntersectInfo;
  34194. intersectInfo.faceId = index / 3;
  34195. if (fastCheck) {
  34196. break;
  34197. }
  34198. }
  34199. }
  34200. }
  34201. }
  34202. return intersectInfo;
  34203. };
  34204. /** @hidden */
  34205. SubMesh.prototype._rebuild = function () {
  34206. if (this._linesIndexBuffer) {
  34207. this._linesIndexBuffer = null;
  34208. }
  34209. };
  34210. // Clone
  34211. /**
  34212. * Creates a new Submesh from the passed Mesh.
  34213. */
  34214. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34215. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34216. if (!this.IsGlobal) {
  34217. var boundingInfo = this.getBoundingInfo();
  34218. if (!boundingInfo) {
  34219. return result;
  34220. }
  34221. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34222. }
  34223. return result;
  34224. };
  34225. // Dispose
  34226. /**
  34227. * Disposes the Submesh.
  34228. * Returns nothing.
  34229. */
  34230. SubMesh.prototype.dispose = function () {
  34231. if (this._linesIndexBuffer) {
  34232. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34233. this._linesIndexBuffer = null;
  34234. }
  34235. // Remove from mesh
  34236. var index = this._mesh.subMeshes.indexOf(this);
  34237. this._mesh.subMeshes.splice(index, 1);
  34238. };
  34239. // Statics
  34240. /**
  34241. * Creates a new Submesh from the passed parameters :
  34242. * - materialIndex (integer) : the index of the main mesh material.
  34243. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34244. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34245. * - mesh (Mesh) : the main mesh to create the submesh from.
  34246. * - renderingMesh (optional Mesh) : rendering mesh.
  34247. */
  34248. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34249. var minVertexIndex = Number.MAX_VALUE;
  34250. var maxVertexIndex = -Number.MAX_VALUE;
  34251. renderingMesh = (renderingMesh || mesh);
  34252. var indices = renderingMesh.getIndices();
  34253. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34254. var vertexIndex = indices[index];
  34255. if (vertexIndex < minVertexIndex)
  34256. minVertexIndex = vertexIndex;
  34257. if (vertexIndex > maxVertexIndex)
  34258. maxVertexIndex = vertexIndex;
  34259. }
  34260. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34261. };
  34262. return SubMesh;
  34263. }(BaseSubMesh));
  34264. BABYLON.SubMesh = SubMesh;
  34265. })(BABYLON || (BABYLON = {}));
  34266. //# sourceMappingURL=babylon.subMesh.js.map
  34267. var __assign = (this && this.__assign) || function () {
  34268. __assign = Object.assign || function(t) {
  34269. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34270. s = arguments[i];
  34271. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34272. t[p] = s[p];
  34273. }
  34274. return t;
  34275. };
  34276. return __assign.apply(this, arguments);
  34277. };
  34278. var BABYLON;
  34279. (function (BABYLON) {
  34280. /**
  34281. * Manages the defines for the Material
  34282. */
  34283. var MaterialDefines = /** @class */ (function () {
  34284. function MaterialDefines() {
  34285. this._isDirty = true;
  34286. /** @hidden */
  34287. this._areLightsDirty = true;
  34288. /** @hidden */
  34289. this._areAttributesDirty = true;
  34290. /** @hidden */
  34291. this._areTexturesDirty = true;
  34292. /** @hidden */
  34293. this._areFresnelDirty = true;
  34294. /** @hidden */
  34295. this._areMiscDirty = true;
  34296. /** @hidden */
  34297. this._areImageProcessingDirty = true;
  34298. /** @hidden */
  34299. this._normals = false;
  34300. /** @hidden */
  34301. this._uvs = false;
  34302. /** @hidden */
  34303. this._needNormals = false;
  34304. /** @hidden */
  34305. this._needUVs = false;
  34306. }
  34307. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34308. /**
  34309. * Specifies if the material needs to be re-calculated
  34310. */
  34311. get: function () {
  34312. return this._isDirty;
  34313. },
  34314. enumerable: true,
  34315. configurable: true
  34316. });
  34317. /**
  34318. * Marks the material to indicate that it has been re-calculated
  34319. */
  34320. MaterialDefines.prototype.markAsProcessed = function () {
  34321. this._isDirty = false;
  34322. this._areAttributesDirty = false;
  34323. this._areTexturesDirty = false;
  34324. this._areFresnelDirty = false;
  34325. this._areLightsDirty = false;
  34326. this._areMiscDirty = false;
  34327. this._areImageProcessingDirty = false;
  34328. };
  34329. /**
  34330. * Marks the material to indicate that it needs to be re-calculated
  34331. */
  34332. MaterialDefines.prototype.markAsUnprocessed = function () {
  34333. this._isDirty = true;
  34334. };
  34335. /**
  34336. * Marks the material to indicate all of its defines need to be re-calculated
  34337. */
  34338. MaterialDefines.prototype.markAllAsDirty = function () {
  34339. this._areTexturesDirty = true;
  34340. this._areAttributesDirty = true;
  34341. this._areLightsDirty = true;
  34342. this._areFresnelDirty = true;
  34343. this._areMiscDirty = true;
  34344. this._areImageProcessingDirty = true;
  34345. this._isDirty = true;
  34346. };
  34347. /**
  34348. * Marks the material to indicate that image processing needs to be re-calculated
  34349. */
  34350. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34351. this._areImageProcessingDirty = true;
  34352. this._isDirty = true;
  34353. };
  34354. /**
  34355. * Marks the material to indicate the lights need to be re-calculated
  34356. */
  34357. MaterialDefines.prototype.markAsLightDirty = function () {
  34358. this._areLightsDirty = true;
  34359. this._isDirty = true;
  34360. };
  34361. /**
  34362. * Marks the attribute state as changed
  34363. */
  34364. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34365. this._areAttributesDirty = true;
  34366. this._isDirty = true;
  34367. };
  34368. /**
  34369. * Marks the texture state as changed
  34370. */
  34371. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34372. this._areTexturesDirty = true;
  34373. this._isDirty = true;
  34374. };
  34375. /**
  34376. * Marks the fresnel state as changed
  34377. */
  34378. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34379. this._areFresnelDirty = true;
  34380. this._isDirty = true;
  34381. };
  34382. /**
  34383. * Marks the misc state as changed
  34384. */
  34385. MaterialDefines.prototype.markAsMiscDirty = function () {
  34386. this._areMiscDirty = true;
  34387. this._isDirty = true;
  34388. };
  34389. /**
  34390. * Rebuilds the material defines
  34391. */
  34392. MaterialDefines.prototype.rebuild = function () {
  34393. if (this._keys) {
  34394. delete this._keys;
  34395. }
  34396. this._keys = [];
  34397. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34398. var key = _a[_i];
  34399. if (key[0] === "_") {
  34400. continue;
  34401. }
  34402. this._keys.push(key);
  34403. }
  34404. };
  34405. /**
  34406. * Specifies if two material defines are equal
  34407. * @param other - A material define instance to compare to
  34408. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34409. */
  34410. MaterialDefines.prototype.isEqual = function (other) {
  34411. if (this._keys.length !== other._keys.length) {
  34412. return false;
  34413. }
  34414. for (var index = 0; index < this._keys.length; index++) {
  34415. var prop = this._keys[index];
  34416. if (this[prop] !== other[prop]) {
  34417. return false;
  34418. }
  34419. }
  34420. return true;
  34421. };
  34422. /**
  34423. * Clones this instance's defines to another instance
  34424. * @param other - material defines to clone values to
  34425. */
  34426. MaterialDefines.prototype.cloneTo = function (other) {
  34427. if (this._keys.length !== other._keys.length) {
  34428. other._keys = this._keys.slice(0);
  34429. }
  34430. for (var index = 0; index < this._keys.length; index++) {
  34431. var prop = this._keys[index];
  34432. other[prop] = this[prop];
  34433. }
  34434. };
  34435. /**
  34436. * Resets the material define values
  34437. */
  34438. MaterialDefines.prototype.reset = function () {
  34439. for (var index = 0; index < this._keys.length; index++) {
  34440. var prop = this._keys[index];
  34441. var type = typeof this[prop];
  34442. switch (type) {
  34443. case "number":
  34444. this[prop] = 0;
  34445. break;
  34446. case "string":
  34447. this[prop] = "";
  34448. break;
  34449. default:
  34450. this[prop] = false;
  34451. break;
  34452. }
  34453. }
  34454. };
  34455. /**
  34456. * Converts the material define values to a string
  34457. * @returns - String of material define information
  34458. */
  34459. MaterialDefines.prototype.toString = function () {
  34460. var result = "";
  34461. for (var index = 0; index < this._keys.length; index++) {
  34462. var prop = this._keys[index];
  34463. var value = this[prop];
  34464. var type = typeof value;
  34465. switch (type) {
  34466. case "number":
  34467. case "string":
  34468. result += "#define " + prop + " " + value + "\n";
  34469. break;
  34470. default:
  34471. if (value) {
  34472. result += "#define " + prop + "\n";
  34473. }
  34474. break;
  34475. }
  34476. }
  34477. return result;
  34478. };
  34479. return MaterialDefines;
  34480. }());
  34481. BABYLON.MaterialDefines = MaterialDefines;
  34482. /**
  34483. * Base class for the main features of a material in Babylon.js
  34484. */
  34485. var Material = /** @class */ (function () {
  34486. /**
  34487. * Creates a material instance
  34488. * @param name defines the name of the material
  34489. * @param scene defines the scene to reference
  34490. * @param doNotAdd specifies if the material should be added to the scene
  34491. */
  34492. function Material(name, scene, doNotAdd) {
  34493. /**
  34494. * Specifies if the ready state should be checked on each call
  34495. */
  34496. this.checkReadyOnEveryCall = false;
  34497. /**
  34498. * Specifies if the ready state should be checked once
  34499. */
  34500. this.checkReadyOnlyOnce = false;
  34501. /**
  34502. * The state of the material
  34503. */
  34504. this.state = "";
  34505. /**
  34506. * The alpha value of the material
  34507. */
  34508. this._alpha = 1.0;
  34509. /**
  34510. * Specifies if back face culling is enabled
  34511. */
  34512. this._backFaceCulling = true;
  34513. /**
  34514. * Gets a boolean indicating that current material needs to register RTT
  34515. */
  34516. this.hasRenderTargetTextures = false;
  34517. /**
  34518. * Specifies if the material should be serialized
  34519. */
  34520. this.doNotSerialize = false;
  34521. /**
  34522. * Specifies if the effect should be stored on sub meshes
  34523. */
  34524. this.storeEffectOnSubMeshes = false;
  34525. /**
  34526. * An event triggered when the material is disposed
  34527. */
  34528. this.onDisposeObservable = new BABYLON.Observable();
  34529. /**
  34530. * Stores the value of the alpha mode
  34531. */
  34532. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34533. /**
  34534. * Stores the state of the need depth pre-pass value
  34535. */
  34536. this._needDepthPrePass = false;
  34537. /**
  34538. * Specifies if depth writing should be disabled
  34539. */
  34540. this.disableDepthWrite = false;
  34541. /**
  34542. * Specifies if depth writing should be forced
  34543. */
  34544. this.forceDepthWrite = false;
  34545. /**
  34546. * Specifies if there should be a separate pass for culling
  34547. */
  34548. this.separateCullingPass = false;
  34549. /**
  34550. * Stores the state specifing if fog should be enabled
  34551. */
  34552. this._fogEnabled = true;
  34553. /**
  34554. * Stores the size of points
  34555. */
  34556. this.pointSize = 1.0;
  34557. /**
  34558. * Stores the z offset value
  34559. */
  34560. this.zOffset = 0;
  34561. /**
  34562. * @hidden
  34563. * Specifies if the material was previously ready
  34564. */
  34565. this._wasPreviouslyReady = false;
  34566. /**
  34567. * Stores the fill mode state
  34568. */
  34569. this._fillMode = Material.TriangleFillMode;
  34570. this.name = name;
  34571. this.id = name || BABYLON.Tools.RandomId();
  34572. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34573. this.uniqueId = this._scene.getUniqueId();
  34574. if (this._scene.useRightHandedSystem) {
  34575. this.sideOrientation = Material.ClockWiseSideOrientation;
  34576. }
  34577. else {
  34578. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34579. }
  34580. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34581. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34582. if (!doNotAdd) {
  34583. this._scene.materials.push(this);
  34584. }
  34585. }
  34586. Object.defineProperty(Material, "TriangleFillMode", {
  34587. /**
  34588. * Returns the triangle fill mode
  34589. */
  34590. get: function () {
  34591. return Material._TriangleFillMode;
  34592. },
  34593. enumerable: true,
  34594. configurable: true
  34595. });
  34596. Object.defineProperty(Material, "WireFrameFillMode", {
  34597. /**
  34598. * Returns the wireframe mode
  34599. */
  34600. get: function () {
  34601. return Material._WireFrameFillMode;
  34602. },
  34603. enumerable: true,
  34604. configurable: true
  34605. });
  34606. Object.defineProperty(Material, "PointFillMode", {
  34607. /**
  34608. * Returns the point fill mode
  34609. */
  34610. get: function () {
  34611. return Material._PointFillMode;
  34612. },
  34613. enumerable: true,
  34614. configurable: true
  34615. });
  34616. Object.defineProperty(Material, "PointListDrawMode", {
  34617. /**
  34618. * Returns the point list draw mode
  34619. */
  34620. get: function () {
  34621. return Material._PointListDrawMode;
  34622. },
  34623. enumerable: true,
  34624. configurable: true
  34625. });
  34626. Object.defineProperty(Material, "LineListDrawMode", {
  34627. /**
  34628. * Returns the line list draw mode
  34629. */
  34630. get: function () {
  34631. return Material._LineListDrawMode;
  34632. },
  34633. enumerable: true,
  34634. configurable: true
  34635. });
  34636. Object.defineProperty(Material, "LineLoopDrawMode", {
  34637. /**
  34638. * Returns the line loop draw mode
  34639. */
  34640. get: function () {
  34641. return Material._LineLoopDrawMode;
  34642. },
  34643. enumerable: true,
  34644. configurable: true
  34645. });
  34646. Object.defineProperty(Material, "LineStripDrawMode", {
  34647. /**
  34648. * Returns the line strip draw mode
  34649. */
  34650. get: function () {
  34651. return Material._LineStripDrawMode;
  34652. },
  34653. enumerable: true,
  34654. configurable: true
  34655. });
  34656. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34657. /**
  34658. * Returns the triangle strip draw mode
  34659. */
  34660. get: function () {
  34661. return Material._TriangleStripDrawMode;
  34662. },
  34663. enumerable: true,
  34664. configurable: true
  34665. });
  34666. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34667. /**
  34668. * Returns the triangle fan draw mode
  34669. */
  34670. get: function () {
  34671. return Material._TriangleFanDrawMode;
  34672. },
  34673. enumerable: true,
  34674. configurable: true
  34675. });
  34676. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34677. /**
  34678. * Returns the clock-wise side orientation
  34679. */
  34680. get: function () {
  34681. return Material._ClockWiseSideOrientation;
  34682. },
  34683. enumerable: true,
  34684. configurable: true
  34685. });
  34686. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34687. /**
  34688. * Returns the counter clock-wise side orientation
  34689. */
  34690. get: function () {
  34691. return Material._CounterClockWiseSideOrientation;
  34692. },
  34693. enumerable: true,
  34694. configurable: true
  34695. });
  34696. Object.defineProperty(Material, "TextureDirtyFlag", {
  34697. /**
  34698. * Returns the dirty texture flag value
  34699. */
  34700. get: function () {
  34701. return Material._TextureDirtyFlag;
  34702. },
  34703. enumerable: true,
  34704. configurable: true
  34705. });
  34706. Object.defineProperty(Material, "LightDirtyFlag", {
  34707. /**
  34708. * Returns the dirty light flag value
  34709. */
  34710. get: function () {
  34711. return Material._LightDirtyFlag;
  34712. },
  34713. enumerable: true,
  34714. configurable: true
  34715. });
  34716. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34717. /**
  34718. * Returns the dirty fresnel flag value
  34719. */
  34720. get: function () {
  34721. return Material._FresnelDirtyFlag;
  34722. },
  34723. enumerable: true,
  34724. configurable: true
  34725. });
  34726. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34727. /**
  34728. * Returns the dirty attributes flag value
  34729. */
  34730. get: function () {
  34731. return Material._AttributesDirtyFlag;
  34732. },
  34733. enumerable: true,
  34734. configurable: true
  34735. });
  34736. Object.defineProperty(Material, "MiscDirtyFlag", {
  34737. /**
  34738. * Returns the dirty misc flag value
  34739. */
  34740. get: function () {
  34741. return Material._MiscDirtyFlag;
  34742. },
  34743. enumerable: true,
  34744. configurable: true
  34745. });
  34746. Object.defineProperty(Material.prototype, "alpha", {
  34747. /**
  34748. * Gets the alpha value of the material
  34749. */
  34750. get: function () {
  34751. return this._alpha;
  34752. },
  34753. /**
  34754. * Sets the alpha value of the material
  34755. */
  34756. set: function (value) {
  34757. if (this._alpha === value) {
  34758. return;
  34759. }
  34760. this._alpha = value;
  34761. this.markAsDirty(Material.MiscDirtyFlag);
  34762. },
  34763. enumerable: true,
  34764. configurable: true
  34765. });
  34766. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34767. /**
  34768. * Gets the back-face culling state
  34769. */
  34770. get: function () {
  34771. return this._backFaceCulling;
  34772. },
  34773. /**
  34774. * Sets the back-face culling state
  34775. */
  34776. set: function (value) {
  34777. if (this._backFaceCulling === value) {
  34778. return;
  34779. }
  34780. this._backFaceCulling = value;
  34781. this.markAsDirty(Material.TextureDirtyFlag);
  34782. },
  34783. enumerable: true,
  34784. configurable: true
  34785. });
  34786. Object.defineProperty(Material.prototype, "onDispose", {
  34787. /**
  34788. * Called during a dispose event
  34789. */
  34790. set: function (callback) {
  34791. if (this._onDisposeObserver) {
  34792. this.onDisposeObservable.remove(this._onDisposeObserver);
  34793. }
  34794. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34795. },
  34796. enumerable: true,
  34797. configurable: true
  34798. });
  34799. Object.defineProperty(Material.prototype, "onBindObservable", {
  34800. /**
  34801. * An event triggered when the material is bound
  34802. */
  34803. get: function () {
  34804. if (!this._onBindObservable) {
  34805. this._onBindObservable = new BABYLON.Observable();
  34806. }
  34807. return this._onBindObservable;
  34808. },
  34809. enumerable: true,
  34810. configurable: true
  34811. });
  34812. Object.defineProperty(Material.prototype, "onBind", {
  34813. /**
  34814. * Called during a bind event
  34815. */
  34816. set: function (callback) {
  34817. if (this._onBindObserver) {
  34818. this.onBindObservable.remove(this._onBindObserver);
  34819. }
  34820. this._onBindObserver = this.onBindObservable.add(callback);
  34821. },
  34822. enumerable: true,
  34823. configurable: true
  34824. });
  34825. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34826. /**
  34827. * An event triggered when the material is unbound
  34828. */
  34829. get: function () {
  34830. if (!this._onUnBindObservable) {
  34831. this._onUnBindObservable = new BABYLON.Observable();
  34832. }
  34833. return this._onUnBindObservable;
  34834. },
  34835. enumerable: true,
  34836. configurable: true
  34837. });
  34838. Object.defineProperty(Material.prototype, "alphaMode", {
  34839. /**
  34840. * Gets the value of the alpha mode
  34841. */
  34842. get: function () {
  34843. return this._alphaMode;
  34844. },
  34845. /**
  34846. * Sets the value of the alpha mode.
  34847. *
  34848. * | Value | Type | Description |
  34849. * | --- | --- | --- |
  34850. * | 0 | ALPHA_DISABLE | |
  34851. * | 1 | ALPHA_ADD | |
  34852. * | 2 | ALPHA_COMBINE | |
  34853. * | 3 | ALPHA_SUBTRACT | |
  34854. * | 4 | ALPHA_MULTIPLY | |
  34855. * | 5 | ALPHA_MAXIMIZED | |
  34856. * | 6 | ALPHA_ONEONE | |
  34857. * | 7 | ALPHA_PREMULTIPLIED | |
  34858. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34859. * | 9 | ALPHA_INTERPOLATE | |
  34860. * | 10 | ALPHA_SCREENMODE | |
  34861. *
  34862. */
  34863. set: function (value) {
  34864. if (this._alphaMode === value) {
  34865. return;
  34866. }
  34867. this._alphaMode = value;
  34868. this.markAsDirty(Material.TextureDirtyFlag);
  34869. },
  34870. enumerable: true,
  34871. configurable: true
  34872. });
  34873. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34874. /**
  34875. * Gets the depth pre-pass value
  34876. */
  34877. get: function () {
  34878. return this._needDepthPrePass;
  34879. },
  34880. /**
  34881. * Sets the need depth pre-pass value
  34882. */
  34883. set: function (value) {
  34884. if (this._needDepthPrePass === value) {
  34885. return;
  34886. }
  34887. this._needDepthPrePass = value;
  34888. if (this._needDepthPrePass) {
  34889. this.checkReadyOnEveryCall = true;
  34890. }
  34891. },
  34892. enumerable: true,
  34893. configurable: true
  34894. });
  34895. Object.defineProperty(Material.prototype, "fogEnabled", {
  34896. /**
  34897. * Gets the value of the fog enabled state
  34898. */
  34899. get: function () {
  34900. return this._fogEnabled;
  34901. },
  34902. /**
  34903. * Sets the state for enabling fog
  34904. */
  34905. set: function (value) {
  34906. if (this._fogEnabled === value) {
  34907. return;
  34908. }
  34909. this._fogEnabled = value;
  34910. this.markAsDirty(Material.MiscDirtyFlag);
  34911. },
  34912. enumerable: true,
  34913. configurable: true
  34914. });
  34915. Object.defineProperty(Material.prototype, "wireframe", {
  34916. /**
  34917. * Gets a value specifying if wireframe mode is enabled
  34918. */
  34919. get: function () {
  34920. switch (this._fillMode) {
  34921. case Material.WireFrameFillMode:
  34922. case Material.LineListDrawMode:
  34923. case Material.LineLoopDrawMode:
  34924. case Material.LineStripDrawMode:
  34925. return true;
  34926. }
  34927. return this._scene.forceWireframe;
  34928. },
  34929. /**
  34930. * Sets the state of wireframe mode
  34931. */
  34932. set: function (value) {
  34933. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. Object.defineProperty(Material.prototype, "pointsCloud", {
  34939. /**
  34940. * Gets the value specifying if point clouds are enabled
  34941. */
  34942. get: function () {
  34943. switch (this._fillMode) {
  34944. case Material.PointFillMode:
  34945. case Material.PointListDrawMode:
  34946. return true;
  34947. }
  34948. return this._scene.forcePointsCloud;
  34949. },
  34950. /**
  34951. * Sets the state of point cloud mode
  34952. */
  34953. set: function (value) {
  34954. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34955. },
  34956. enumerable: true,
  34957. configurable: true
  34958. });
  34959. Object.defineProperty(Material.prototype, "fillMode", {
  34960. /**
  34961. * Gets the material fill mode
  34962. */
  34963. get: function () {
  34964. return this._fillMode;
  34965. },
  34966. /**
  34967. * Sets the material fill mode
  34968. */
  34969. set: function (value) {
  34970. if (this._fillMode === value) {
  34971. return;
  34972. }
  34973. this._fillMode = value;
  34974. this.markAsDirty(Material.MiscDirtyFlag);
  34975. },
  34976. enumerable: true,
  34977. configurable: true
  34978. });
  34979. /**
  34980. * Returns a string representation of the current material
  34981. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34982. * @returns a string with material information
  34983. */
  34984. Material.prototype.toString = function (fullDetails) {
  34985. var ret = "Name: " + this.name;
  34986. if (fullDetails) {
  34987. }
  34988. return ret;
  34989. };
  34990. /**
  34991. * Gets the class name of the material
  34992. * @returns a string with the class name of the material
  34993. */
  34994. Material.prototype.getClassName = function () {
  34995. return "Material";
  34996. };
  34997. Object.defineProperty(Material.prototype, "isFrozen", {
  34998. /**
  34999. * Specifies if updates for the material been locked
  35000. */
  35001. get: function () {
  35002. return this.checkReadyOnlyOnce;
  35003. },
  35004. enumerable: true,
  35005. configurable: true
  35006. });
  35007. /**
  35008. * Locks updates for the material
  35009. */
  35010. Material.prototype.freeze = function () {
  35011. this.checkReadyOnlyOnce = true;
  35012. };
  35013. /**
  35014. * Unlocks updates for the material
  35015. */
  35016. Material.prototype.unfreeze = function () {
  35017. this.checkReadyOnlyOnce = false;
  35018. };
  35019. /**
  35020. * Specifies if the material is ready to be used
  35021. * @param mesh defines the mesh to check
  35022. * @param useInstances specifies if instances should be used
  35023. * @returns a boolean indicating if the material is ready to be used
  35024. */
  35025. Material.prototype.isReady = function (mesh, useInstances) {
  35026. return true;
  35027. };
  35028. /**
  35029. * Specifies that the submesh is ready to be used
  35030. * @param mesh defines the mesh to check
  35031. * @param subMesh defines which submesh to check
  35032. * @param useInstances specifies that instances should be used
  35033. * @returns a boolean indicating that the submesh is ready or not
  35034. */
  35035. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35036. return false;
  35037. };
  35038. /**
  35039. * Returns the material effect
  35040. * @returns the effect associated with the material
  35041. */
  35042. Material.prototype.getEffect = function () {
  35043. return this._effect;
  35044. };
  35045. /**
  35046. * Returns the current scene
  35047. * @returns a Scene
  35048. */
  35049. Material.prototype.getScene = function () {
  35050. return this._scene;
  35051. };
  35052. /**
  35053. * Specifies if the material will require alpha blending
  35054. * @returns a boolean specifying if alpha blending is needed
  35055. */
  35056. Material.prototype.needAlphaBlending = function () {
  35057. return (this.alpha < 1.0);
  35058. };
  35059. /**
  35060. * Specifies if the mesh will require alpha blending
  35061. * @param mesh defines the mesh to check
  35062. * @returns a boolean specifying if alpha blending is needed for the mesh
  35063. */
  35064. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35065. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35066. };
  35067. /**
  35068. * Specifies if this material should be rendered in alpha test mode
  35069. * @returns a boolean specifying if an alpha test is needed.
  35070. */
  35071. Material.prototype.needAlphaTesting = function () {
  35072. return false;
  35073. };
  35074. /**
  35075. * Gets the texture used for the alpha test
  35076. * @returns the texture to use for alpha testing
  35077. */
  35078. Material.prototype.getAlphaTestTexture = function () {
  35079. return null;
  35080. };
  35081. /**
  35082. * Marks the material to indicate that it needs to be re-calculated
  35083. */
  35084. Material.prototype.markDirty = function () {
  35085. this._wasPreviouslyReady = false;
  35086. };
  35087. /** @hidden */
  35088. Material.prototype._preBind = function (effect, overrideOrientation) {
  35089. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35090. var engine = this._scene.getEngine();
  35091. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35092. var reverse = orientation === Material.ClockWiseSideOrientation;
  35093. engine.enableEffect(effect ? effect : this._effect);
  35094. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35095. return reverse;
  35096. };
  35097. /**
  35098. * Binds the material to the mesh
  35099. * @param world defines the world transformation matrix
  35100. * @param mesh defines the mesh to bind the material to
  35101. */
  35102. Material.prototype.bind = function (world, mesh) {
  35103. };
  35104. /**
  35105. * Binds the submesh to the material
  35106. * @param world defines the world transformation matrix
  35107. * @param mesh defines the mesh containing the submesh
  35108. * @param subMesh defines the submesh to bind the material to
  35109. */
  35110. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35111. };
  35112. /**
  35113. * Binds the world matrix to the material
  35114. * @param world defines the world transformation matrix
  35115. */
  35116. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35117. };
  35118. /**
  35119. * Binds the scene's uniform buffer to the effect.
  35120. * @param effect defines the effect to bind to the scene uniform buffer
  35121. * @param sceneUbo defines the uniform buffer storing scene data
  35122. */
  35123. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35124. sceneUbo.bindToEffect(effect, "Scene");
  35125. };
  35126. /**
  35127. * Binds the view matrix to the effect
  35128. * @param effect defines the effect to bind the view matrix to
  35129. */
  35130. Material.prototype.bindView = function (effect) {
  35131. if (!this._useUBO) {
  35132. effect.setMatrix("view", this.getScene().getViewMatrix());
  35133. }
  35134. else {
  35135. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35136. }
  35137. };
  35138. /**
  35139. * Binds the view projection matrix to the effect
  35140. * @param effect defines the effect to bind the view projection matrix to
  35141. */
  35142. Material.prototype.bindViewProjection = function (effect) {
  35143. if (!this._useUBO) {
  35144. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35145. }
  35146. else {
  35147. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35148. }
  35149. };
  35150. /**
  35151. * Specifies if material alpha testing should be turned on for the mesh
  35152. * @param mesh defines the mesh to check
  35153. */
  35154. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35155. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35156. };
  35157. /**
  35158. * Processes to execute after binding the material to a mesh
  35159. * @param mesh defines the rendered mesh
  35160. */
  35161. Material.prototype._afterBind = function (mesh) {
  35162. this._scene._cachedMaterial = this;
  35163. if (mesh) {
  35164. this._scene._cachedVisibility = mesh.visibility;
  35165. }
  35166. else {
  35167. this._scene._cachedVisibility = 1;
  35168. }
  35169. if (this._onBindObservable && mesh) {
  35170. this._onBindObservable.notifyObservers(mesh);
  35171. }
  35172. if (this.disableDepthWrite) {
  35173. var engine = this._scene.getEngine();
  35174. this._cachedDepthWriteState = engine.getDepthWrite();
  35175. engine.setDepthWrite(false);
  35176. }
  35177. };
  35178. /**
  35179. * Unbinds the material from the mesh
  35180. */
  35181. Material.prototype.unbind = function () {
  35182. if (this._onUnBindObservable) {
  35183. this._onUnBindObservable.notifyObservers(this);
  35184. }
  35185. if (this.disableDepthWrite) {
  35186. var engine = this._scene.getEngine();
  35187. engine.setDepthWrite(this._cachedDepthWriteState);
  35188. }
  35189. };
  35190. /**
  35191. * Gets the active textures from the material
  35192. * @returns an array of textures
  35193. */
  35194. Material.prototype.getActiveTextures = function () {
  35195. return [];
  35196. };
  35197. /**
  35198. * Specifies if the material uses a texture
  35199. * @param texture defines the texture to check against the material
  35200. * @returns a boolean specifying if the material uses the texture
  35201. */
  35202. Material.prototype.hasTexture = function (texture) {
  35203. return false;
  35204. };
  35205. /**
  35206. * Makes a duplicate of the material, and gives it a new name
  35207. * @param name defines the new name for the duplicated material
  35208. * @returns the cloned material
  35209. */
  35210. Material.prototype.clone = function (name) {
  35211. return null;
  35212. };
  35213. /**
  35214. * Gets the meshes bound to the material
  35215. * @returns an array of meshes bound to the material
  35216. */
  35217. Material.prototype.getBindedMeshes = function () {
  35218. var result = new Array();
  35219. for (var index = 0; index < this._scene.meshes.length; index++) {
  35220. var mesh = this._scene.meshes[index];
  35221. if (mesh.material === this) {
  35222. result.push(mesh);
  35223. }
  35224. }
  35225. return result;
  35226. };
  35227. /**
  35228. * Force shader compilation
  35229. * @param mesh defines the mesh associated with this material
  35230. * @param onCompiled defines a function to execute once the material is compiled
  35231. * @param options defines the options to configure the compilation
  35232. */
  35233. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35234. var _this = this;
  35235. var localOptions = __assign({ clipPlane: false }, options);
  35236. var subMesh = new BABYLON.BaseSubMesh();
  35237. var scene = this.getScene();
  35238. var checkReady = function () {
  35239. if (!_this._scene || !_this._scene.getEngine()) {
  35240. return;
  35241. }
  35242. if (subMesh._materialDefines) {
  35243. subMesh._materialDefines._renderId = -1;
  35244. }
  35245. var clipPlaneState = scene.clipPlane;
  35246. if (localOptions.clipPlane) {
  35247. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35248. }
  35249. if (_this.storeEffectOnSubMeshes) {
  35250. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35251. if (onCompiled) {
  35252. onCompiled(_this);
  35253. }
  35254. }
  35255. else {
  35256. setTimeout(checkReady, 16);
  35257. }
  35258. }
  35259. else {
  35260. if (_this.isReady(mesh)) {
  35261. if (onCompiled) {
  35262. onCompiled(_this);
  35263. }
  35264. }
  35265. else {
  35266. setTimeout(checkReady, 16);
  35267. }
  35268. }
  35269. if (localOptions.clipPlane) {
  35270. scene.clipPlane = clipPlaneState;
  35271. }
  35272. };
  35273. checkReady();
  35274. };
  35275. /**
  35276. * Force shader compilation
  35277. * @param mesh defines the mesh that will use this material
  35278. * @param options defines additional options for compiling the shaders
  35279. * @returns a promise that resolves when the compilation completes
  35280. */
  35281. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35282. var _this = this;
  35283. return new Promise(function (resolve) {
  35284. _this.forceCompilation(mesh, function () {
  35285. resolve();
  35286. }, options);
  35287. });
  35288. };
  35289. /**
  35290. * Marks a define in the material to indicate that it needs to be re-computed
  35291. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35292. */
  35293. Material.prototype.markAsDirty = function (flag) {
  35294. if (flag & Material.TextureDirtyFlag) {
  35295. this._markAllSubMeshesAsTexturesDirty();
  35296. }
  35297. if (flag & Material.LightDirtyFlag) {
  35298. this._markAllSubMeshesAsLightsDirty();
  35299. }
  35300. if (flag & Material.FresnelDirtyFlag) {
  35301. this._markAllSubMeshesAsFresnelDirty();
  35302. }
  35303. if (flag & Material.AttributesDirtyFlag) {
  35304. this._markAllSubMeshesAsAttributesDirty();
  35305. }
  35306. if (flag & Material.MiscDirtyFlag) {
  35307. this._markAllSubMeshesAsMiscDirty();
  35308. }
  35309. this.getScene().resetCachedMaterial();
  35310. };
  35311. /**
  35312. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35313. * @param func defines a function which checks material defines against the submeshes
  35314. */
  35315. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35316. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35317. var mesh = _a[_i];
  35318. if (!mesh.subMeshes) {
  35319. continue;
  35320. }
  35321. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35322. var subMesh = _c[_b];
  35323. if (subMesh.getMaterial() !== this) {
  35324. continue;
  35325. }
  35326. if (!subMesh._materialDefines) {
  35327. continue;
  35328. }
  35329. func(subMesh._materialDefines);
  35330. }
  35331. }
  35332. };
  35333. /**
  35334. * Indicates that image processing needs to be re-calculated for all submeshes
  35335. */
  35336. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35337. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35338. };
  35339. /**
  35340. * Indicates that textures need to be re-calculated for all submeshes
  35341. */
  35342. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35343. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35344. };
  35345. /**
  35346. * Indicates that fresnel needs to be re-calculated for all submeshes
  35347. */
  35348. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35349. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35350. };
  35351. /**
  35352. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35353. */
  35354. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35355. this._markAllSubMeshesAsDirty(function (defines) {
  35356. defines.markAsFresnelDirty();
  35357. defines.markAsMiscDirty();
  35358. });
  35359. };
  35360. /**
  35361. * Indicates that lights need to be re-calculated for all submeshes
  35362. */
  35363. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35364. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35365. };
  35366. /**
  35367. * Indicates that attributes need to be re-calculated for all submeshes
  35368. */
  35369. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35370. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35371. };
  35372. /**
  35373. * Indicates that misc needs to be re-calculated for all submeshes
  35374. */
  35375. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35376. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35377. };
  35378. /**
  35379. * Indicates that textures and misc need to be re-calculated for all submeshes
  35380. */
  35381. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35382. this._markAllSubMeshesAsDirty(function (defines) {
  35383. defines.markAsTexturesDirty();
  35384. defines.markAsMiscDirty();
  35385. });
  35386. };
  35387. /**
  35388. * Disposes the material
  35389. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35390. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35391. */
  35392. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35393. // Animations
  35394. this.getScene().stopAnimation(this);
  35395. this.getScene().freeProcessedMaterials();
  35396. // Remove from scene
  35397. var index = this._scene.materials.indexOf(this);
  35398. if (index >= 0) {
  35399. this._scene.materials.splice(index, 1);
  35400. }
  35401. // Remove from meshes
  35402. for (index = 0; index < this._scene.meshes.length; index++) {
  35403. var mesh = this._scene.meshes[index];
  35404. if (mesh.material === this) {
  35405. mesh.material = null;
  35406. if (mesh.geometry) {
  35407. var geometry = (mesh.geometry);
  35408. if (this.storeEffectOnSubMeshes) {
  35409. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35410. var subMesh = _a[_i];
  35411. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35412. if (forceDisposeEffect && subMesh._materialEffect) {
  35413. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35414. }
  35415. }
  35416. }
  35417. else {
  35418. geometry._releaseVertexArrayObject(this._effect);
  35419. }
  35420. }
  35421. }
  35422. }
  35423. this._uniformBuffer.dispose();
  35424. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35425. if (forceDisposeEffect && this._effect) {
  35426. if (!this.storeEffectOnSubMeshes) {
  35427. this._scene.getEngine()._releaseEffect(this._effect);
  35428. }
  35429. this._effect = null;
  35430. }
  35431. // Callback
  35432. this.onDisposeObservable.notifyObservers(this);
  35433. this.onDisposeObservable.clear();
  35434. if (this._onBindObservable) {
  35435. this._onBindObservable.clear();
  35436. }
  35437. if (this._onUnBindObservable) {
  35438. this._onUnBindObservable.clear();
  35439. }
  35440. };
  35441. /**
  35442. * Serializes this material
  35443. * @returns the serialized material object
  35444. */
  35445. Material.prototype.serialize = function () {
  35446. return BABYLON.SerializationHelper.Serialize(this);
  35447. };
  35448. /**
  35449. * Creates a MultiMaterial from parsed MultiMaterial data.
  35450. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35451. * @param scene defines the hosting scene
  35452. * @returns a new MultiMaterial
  35453. */
  35454. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35455. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35456. multiMaterial.id = parsedMultiMaterial.id;
  35457. if (BABYLON.Tags) {
  35458. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35459. }
  35460. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35461. var subMatId = parsedMultiMaterial.materials[matIndex];
  35462. if (subMatId) {
  35463. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35464. }
  35465. else {
  35466. multiMaterial.subMaterials.push(null);
  35467. }
  35468. }
  35469. return multiMaterial;
  35470. };
  35471. /**
  35472. * Creates a material from parsed material data
  35473. * @param parsedMaterial defines parsed material data
  35474. * @param scene defines the hosting scene
  35475. * @param rootUrl defines the root URL to use to load textures
  35476. * @returns a new material
  35477. */
  35478. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35479. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35480. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35481. }
  35482. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35483. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35484. if (!BABYLON.LegacyPBRMaterial) {
  35485. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35486. return;
  35487. }
  35488. }
  35489. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35490. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35491. };
  35492. // Triangle views
  35493. Material._TriangleFillMode = 0;
  35494. Material._WireFrameFillMode = 1;
  35495. Material._PointFillMode = 2;
  35496. // Draw modes
  35497. Material._PointListDrawMode = 3;
  35498. Material._LineListDrawMode = 4;
  35499. Material._LineLoopDrawMode = 5;
  35500. Material._LineStripDrawMode = 6;
  35501. Material._TriangleStripDrawMode = 7;
  35502. Material._TriangleFanDrawMode = 8;
  35503. /**
  35504. * Stores the clock-wise side orientation
  35505. */
  35506. Material._ClockWiseSideOrientation = 0;
  35507. /**
  35508. * Stores the counter clock-wise side orientation
  35509. */
  35510. Material._CounterClockWiseSideOrientation = 1;
  35511. /**
  35512. * The dirty texture flag value
  35513. */
  35514. Material._TextureDirtyFlag = 1;
  35515. /**
  35516. * The dirty light flag value
  35517. */
  35518. Material._LightDirtyFlag = 2;
  35519. /**
  35520. * The dirty fresnel flag value
  35521. */
  35522. Material._FresnelDirtyFlag = 4;
  35523. /**
  35524. * The dirty attribute flag value
  35525. */
  35526. Material._AttributesDirtyFlag = 8;
  35527. /**
  35528. * The dirty misc flag value
  35529. */
  35530. Material._MiscDirtyFlag = 16;
  35531. __decorate([
  35532. BABYLON.serialize()
  35533. ], Material.prototype, "id", void 0);
  35534. __decorate([
  35535. BABYLON.serialize()
  35536. ], Material.prototype, "uniqueId", void 0);
  35537. __decorate([
  35538. BABYLON.serialize()
  35539. ], Material.prototype, "name", void 0);
  35540. __decorate([
  35541. BABYLON.serialize()
  35542. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35543. __decorate([
  35544. BABYLON.serialize()
  35545. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35546. __decorate([
  35547. BABYLON.serialize()
  35548. ], Material.prototype, "state", void 0);
  35549. __decorate([
  35550. BABYLON.serialize("alpha")
  35551. ], Material.prototype, "_alpha", void 0);
  35552. __decorate([
  35553. BABYLON.serialize("backFaceCulling")
  35554. ], Material.prototype, "_backFaceCulling", void 0);
  35555. __decorate([
  35556. BABYLON.serialize()
  35557. ], Material.prototype, "sideOrientation", void 0);
  35558. __decorate([
  35559. BABYLON.serialize("alphaMode")
  35560. ], Material.prototype, "_alphaMode", void 0);
  35561. __decorate([
  35562. BABYLON.serialize()
  35563. ], Material.prototype, "_needDepthPrePass", void 0);
  35564. __decorate([
  35565. BABYLON.serialize()
  35566. ], Material.prototype, "disableDepthWrite", void 0);
  35567. __decorate([
  35568. BABYLON.serialize()
  35569. ], Material.prototype, "forceDepthWrite", void 0);
  35570. __decorate([
  35571. BABYLON.serialize()
  35572. ], Material.prototype, "separateCullingPass", void 0);
  35573. __decorate([
  35574. BABYLON.serialize("fogEnabled")
  35575. ], Material.prototype, "_fogEnabled", void 0);
  35576. __decorate([
  35577. BABYLON.serialize()
  35578. ], Material.prototype, "pointSize", void 0);
  35579. __decorate([
  35580. BABYLON.serialize()
  35581. ], Material.prototype, "zOffset", void 0);
  35582. __decorate([
  35583. BABYLON.serialize()
  35584. ], Material.prototype, "wireframe", null);
  35585. __decorate([
  35586. BABYLON.serialize()
  35587. ], Material.prototype, "pointsCloud", null);
  35588. __decorate([
  35589. BABYLON.serialize()
  35590. ], Material.prototype, "fillMode", null);
  35591. return Material;
  35592. }());
  35593. BABYLON.Material = Material;
  35594. })(BABYLON || (BABYLON = {}));
  35595. //# sourceMappingURL=babylon.material.js.map
  35596. var BABYLON;
  35597. (function (BABYLON) {
  35598. var UniformBuffer = /** @class */ (function () {
  35599. /**
  35600. * Uniform buffer objects.
  35601. *
  35602. * Handles blocks of uniform on the GPU.
  35603. *
  35604. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35605. *
  35606. * For more information, please refer to :
  35607. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35608. */
  35609. function UniformBuffer(engine, data, dynamic) {
  35610. this._engine = engine;
  35611. this._noUBO = !engine.supportsUniformBuffers;
  35612. this._dynamic = dynamic;
  35613. this._data = data || [];
  35614. this._uniformLocations = {};
  35615. this._uniformSizes = {};
  35616. this._uniformLocationPointer = 0;
  35617. this._needSync = false;
  35618. if (this._noUBO) {
  35619. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35620. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35621. this.updateFloat = this._updateFloatForEffect;
  35622. this.updateFloat2 = this._updateFloat2ForEffect;
  35623. this.updateFloat3 = this._updateFloat3ForEffect;
  35624. this.updateFloat4 = this._updateFloat4ForEffect;
  35625. this.updateMatrix = this._updateMatrixForEffect;
  35626. this.updateVector3 = this._updateVector3ForEffect;
  35627. this.updateVector4 = this._updateVector4ForEffect;
  35628. this.updateColor3 = this._updateColor3ForEffect;
  35629. this.updateColor4 = this._updateColor4ForEffect;
  35630. }
  35631. else {
  35632. this._engine._uniformBuffers.push(this);
  35633. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35634. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35635. this.updateFloat = this._updateFloatForUniform;
  35636. this.updateFloat2 = this._updateFloat2ForUniform;
  35637. this.updateFloat3 = this._updateFloat3ForUniform;
  35638. this.updateFloat4 = this._updateFloat4ForUniform;
  35639. this.updateMatrix = this._updateMatrixForUniform;
  35640. this.updateVector3 = this._updateVector3ForUniform;
  35641. this.updateVector4 = this._updateVector4ForUniform;
  35642. this.updateColor3 = this._updateColor3ForUniform;
  35643. this.updateColor4 = this._updateColor4ForUniform;
  35644. }
  35645. }
  35646. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35647. // Properties
  35648. /**
  35649. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35650. * or just falling back on setUniformXXX calls.
  35651. */
  35652. get: function () {
  35653. return !this._noUBO;
  35654. },
  35655. enumerable: true,
  35656. configurable: true
  35657. });
  35658. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35659. /**
  35660. * Indicates if the WebGL underlying uniform buffer is in sync
  35661. * with the javascript cache data.
  35662. */
  35663. get: function () {
  35664. return !this._needSync;
  35665. },
  35666. enumerable: true,
  35667. configurable: true
  35668. });
  35669. /**
  35670. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35671. * Also, a dynamic UniformBuffer will disable cache verification and always
  35672. * update the underlying WebGL uniform buffer to the GPU.
  35673. */
  35674. UniformBuffer.prototype.isDynamic = function () {
  35675. return this._dynamic !== undefined;
  35676. };
  35677. /**
  35678. * The data cache on JS side.
  35679. */
  35680. UniformBuffer.prototype.getData = function () {
  35681. return this._bufferData;
  35682. };
  35683. /**
  35684. * The underlying WebGL Uniform buffer.
  35685. */
  35686. UniformBuffer.prototype.getBuffer = function () {
  35687. return this._buffer;
  35688. };
  35689. /**
  35690. * std140 layout specifies how to align data within an UBO structure.
  35691. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35692. * for specs.
  35693. */
  35694. UniformBuffer.prototype._fillAlignment = function (size) {
  35695. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35696. // and 4x4 matrices
  35697. // TODO : change if other types are used
  35698. var alignment;
  35699. if (size <= 2) {
  35700. alignment = size;
  35701. }
  35702. else {
  35703. alignment = 4;
  35704. }
  35705. if ((this._uniformLocationPointer % alignment) !== 0) {
  35706. var oldPointer = this._uniformLocationPointer;
  35707. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35708. var diff = this._uniformLocationPointer - oldPointer;
  35709. for (var i = 0; i < diff; i++) {
  35710. this._data.push(0);
  35711. }
  35712. }
  35713. };
  35714. /**
  35715. * Adds an uniform in the buffer.
  35716. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35717. * for the layout to be correct !
  35718. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35719. * @param {number|number[]} size Data size, or data directly.
  35720. */
  35721. UniformBuffer.prototype.addUniform = function (name, size) {
  35722. if (this._noUBO) {
  35723. return;
  35724. }
  35725. if (this._uniformLocations[name] !== undefined) {
  35726. // Already existing uniform
  35727. return;
  35728. }
  35729. // This function must be called in the order of the shader layout !
  35730. // size can be the size of the uniform, or data directly
  35731. var data;
  35732. if (size instanceof Array) {
  35733. data = size;
  35734. size = data.length;
  35735. }
  35736. else {
  35737. size = size;
  35738. data = [];
  35739. // Fill with zeros
  35740. for (var i = 0; i < size; i++) {
  35741. data.push(0);
  35742. }
  35743. }
  35744. this._fillAlignment(size);
  35745. this._uniformSizes[name] = size;
  35746. this._uniformLocations[name] = this._uniformLocationPointer;
  35747. this._uniformLocationPointer += size;
  35748. for (var i = 0; i < size; i++) {
  35749. this._data.push(data[i]);
  35750. }
  35751. this._needSync = true;
  35752. };
  35753. /**
  35754. * Wrapper for addUniform.
  35755. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35756. * @param {Matrix} mat A 4x4 matrix.
  35757. */
  35758. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35759. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35760. };
  35761. /**
  35762. * Wrapper for addUniform.
  35763. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35764. * @param {number} x
  35765. * @param {number} y
  35766. */
  35767. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35768. var temp = [x, y];
  35769. this.addUniform(name, temp);
  35770. };
  35771. /**
  35772. * Wrapper for addUniform.
  35773. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35774. * @param {number} x
  35775. * @param {number} y
  35776. * @param {number} z
  35777. */
  35778. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35779. var temp = [x, y, z];
  35780. this.addUniform(name, temp);
  35781. };
  35782. /**
  35783. * Wrapper for addUniform.
  35784. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35785. * @param {Color3} color
  35786. */
  35787. UniformBuffer.prototype.addColor3 = function (name, color) {
  35788. var temp = new Array();
  35789. color.toArray(temp);
  35790. this.addUniform(name, temp);
  35791. };
  35792. /**
  35793. * Wrapper for addUniform.
  35794. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35795. * @param {Color3} color
  35796. * @param {number} alpha
  35797. */
  35798. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35799. var temp = new Array();
  35800. color.toArray(temp);
  35801. temp.push(alpha);
  35802. this.addUniform(name, temp);
  35803. };
  35804. /**
  35805. * Wrapper for addUniform.
  35806. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35807. * @param {Vector3} vector
  35808. */
  35809. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35810. var temp = new Array();
  35811. vector.toArray(temp);
  35812. this.addUniform(name, temp);
  35813. };
  35814. /**
  35815. * Wrapper for addUniform.
  35816. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35817. */
  35818. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35819. this.addUniform(name, 12);
  35820. };
  35821. /**
  35822. * Wrapper for addUniform.
  35823. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35824. */
  35825. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35826. this.addUniform(name, 8);
  35827. };
  35828. /**
  35829. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35830. */
  35831. UniformBuffer.prototype.create = function () {
  35832. if (this._noUBO) {
  35833. return;
  35834. }
  35835. if (this._buffer) {
  35836. return; // nothing to do
  35837. }
  35838. // See spec, alignment must be filled as a vec4
  35839. this._fillAlignment(4);
  35840. this._bufferData = new Float32Array(this._data);
  35841. this._rebuild();
  35842. this._needSync = true;
  35843. };
  35844. /** @hidden */
  35845. UniformBuffer.prototype._rebuild = function () {
  35846. if (this._noUBO) {
  35847. return;
  35848. }
  35849. if (this._dynamic) {
  35850. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35851. }
  35852. else {
  35853. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35854. }
  35855. };
  35856. /**
  35857. * Updates the WebGL Uniform Buffer on the GPU.
  35858. * If the `dynamic` flag is set to true, no cache comparison is done.
  35859. * Otherwise, the buffer will be updated only if the cache differs.
  35860. */
  35861. UniformBuffer.prototype.update = function () {
  35862. if (!this._buffer) {
  35863. this.create();
  35864. return;
  35865. }
  35866. if (!this._dynamic && !this._needSync) {
  35867. return;
  35868. }
  35869. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35870. this._needSync = false;
  35871. };
  35872. /**
  35873. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35874. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35875. * @param {number[]|Float32Array} data Flattened data
  35876. * @param {number} size Size of the data.
  35877. */
  35878. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35879. var location = this._uniformLocations[uniformName];
  35880. if (location === undefined) {
  35881. if (this._buffer) {
  35882. // Cannot add an uniform if the buffer is already created
  35883. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35884. return;
  35885. }
  35886. this.addUniform(uniformName, size);
  35887. location = this._uniformLocations[uniformName];
  35888. }
  35889. if (!this._buffer) {
  35890. this.create();
  35891. }
  35892. if (!this._dynamic) {
  35893. // Cache for static uniform buffers
  35894. var changed = false;
  35895. for (var i = 0; i < size; i++) {
  35896. if (this._bufferData[location + i] !== data[i]) {
  35897. changed = true;
  35898. this._bufferData[location + i] = data[i];
  35899. }
  35900. }
  35901. this._needSync = this._needSync || changed;
  35902. }
  35903. else {
  35904. // No cache for dynamic
  35905. for (var i = 0; i < size; i++) {
  35906. this._bufferData[location + i] = data[i];
  35907. }
  35908. }
  35909. };
  35910. // Update methods
  35911. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35912. // To match std140, matrix must be realigned
  35913. for (var i = 0; i < 3; i++) {
  35914. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35915. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35916. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35917. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35918. }
  35919. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35920. };
  35921. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35922. this._currentEffect.setMatrix3x3(name, matrix);
  35923. };
  35924. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35925. this._currentEffect.setMatrix2x2(name, matrix);
  35926. };
  35927. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35928. // To match std140, matrix must be realigned
  35929. for (var i = 0; i < 2; i++) {
  35930. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35931. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35932. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35933. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35934. }
  35935. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35936. };
  35937. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35938. this._currentEffect.setFloat(name, x);
  35939. };
  35940. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35941. UniformBuffer._tempBuffer[0] = x;
  35942. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35943. };
  35944. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35945. if (suffix === void 0) { suffix = ""; }
  35946. this._currentEffect.setFloat2(name + suffix, x, y);
  35947. };
  35948. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35949. if (suffix === void 0) { suffix = ""; }
  35950. UniformBuffer._tempBuffer[0] = x;
  35951. UniformBuffer._tempBuffer[1] = y;
  35952. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35953. };
  35954. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35955. if (suffix === void 0) { suffix = ""; }
  35956. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35957. };
  35958. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35959. if (suffix === void 0) { suffix = ""; }
  35960. UniformBuffer._tempBuffer[0] = x;
  35961. UniformBuffer._tempBuffer[1] = y;
  35962. UniformBuffer._tempBuffer[2] = z;
  35963. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35964. };
  35965. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35966. if (suffix === void 0) { suffix = ""; }
  35967. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35968. };
  35969. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35970. if (suffix === void 0) { suffix = ""; }
  35971. UniformBuffer._tempBuffer[0] = x;
  35972. UniformBuffer._tempBuffer[1] = y;
  35973. UniformBuffer._tempBuffer[2] = z;
  35974. UniformBuffer._tempBuffer[3] = w;
  35975. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35976. };
  35977. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35978. this._currentEffect.setMatrix(name, mat);
  35979. };
  35980. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35981. this.updateUniform(name, mat.toArray(), 16);
  35982. };
  35983. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35984. this._currentEffect.setVector3(name, vector);
  35985. };
  35986. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35987. vector.toArray(UniformBuffer._tempBuffer);
  35988. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35989. };
  35990. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35991. this._currentEffect.setVector4(name, vector);
  35992. };
  35993. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35994. vector.toArray(UniformBuffer._tempBuffer);
  35995. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35996. };
  35997. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35998. if (suffix === void 0) { suffix = ""; }
  35999. this._currentEffect.setColor3(name + suffix, color);
  36000. };
  36001. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36002. if (suffix === void 0) { suffix = ""; }
  36003. color.toArray(UniformBuffer._tempBuffer);
  36004. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36005. };
  36006. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36007. if (suffix === void 0) { suffix = ""; }
  36008. this._currentEffect.setColor4(name + suffix, color, alpha);
  36009. };
  36010. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36011. if (suffix === void 0) { suffix = ""; }
  36012. color.toArray(UniformBuffer._tempBuffer);
  36013. UniformBuffer._tempBuffer[3] = alpha;
  36014. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36015. };
  36016. /**
  36017. * Sets a sampler uniform on the effect.
  36018. * @param {string} name Name of the sampler.
  36019. * @param {Texture} texture
  36020. */
  36021. UniformBuffer.prototype.setTexture = function (name, texture) {
  36022. this._currentEffect.setTexture(name, texture);
  36023. };
  36024. /**
  36025. * Directly updates the value of the uniform in the cache AND on the GPU.
  36026. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36027. * @param {number[]|Float32Array} data Flattened data
  36028. */
  36029. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36030. this.updateUniform(uniformName, data, data.length);
  36031. this.update();
  36032. };
  36033. /**
  36034. * Binds this uniform buffer to an effect.
  36035. * @param {Effect} effect
  36036. * @param {string} name Name of the uniform block in the shader.
  36037. */
  36038. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36039. this._currentEffect = effect;
  36040. if (this._noUBO || !this._buffer) {
  36041. return;
  36042. }
  36043. effect.bindUniformBuffer(this._buffer, name);
  36044. };
  36045. /**
  36046. * Disposes the uniform buffer.
  36047. */
  36048. UniformBuffer.prototype.dispose = function () {
  36049. if (this._noUBO) {
  36050. return;
  36051. }
  36052. var index = this._engine._uniformBuffers.indexOf(this);
  36053. if (index !== -1) {
  36054. this._engine._uniformBuffers.splice(index, 1);
  36055. }
  36056. if (!this._buffer) {
  36057. return;
  36058. }
  36059. if (this._engine._releaseBuffer(this._buffer)) {
  36060. this._buffer = null;
  36061. }
  36062. };
  36063. // Pool for avoiding memory leaks
  36064. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36065. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36066. return UniformBuffer;
  36067. }());
  36068. BABYLON.UniformBuffer = UniformBuffer;
  36069. })(BABYLON || (BABYLON = {}));
  36070. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36071. var BABYLON;
  36072. (function (BABYLON) {
  36073. /**
  36074. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36075. */
  36076. var VertexData = /** @class */ (function () {
  36077. function VertexData() {
  36078. }
  36079. /**
  36080. * Uses the passed data array to set the set the values for the specified kind of data
  36081. * @param data a linear array of floating numbers
  36082. * @param kind the type of data that is being set, eg positions, colors etc
  36083. */
  36084. VertexData.prototype.set = function (data, kind) {
  36085. switch (kind) {
  36086. case BABYLON.VertexBuffer.PositionKind:
  36087. this.positions = data;
  36088. break;
  36089. case BABYLON.VertexBuffer.NormalKind:
  36090. this.normals = data;
  36091. break;
  36092. case BABYLON.VertexBuffer.TangentKind:
  36093. this.tangents = data;
  36094. break;
  36095. case BABYLON.VertexBuffer.UVKind:
  36096. this.uvs = data;
  36097. break;
  36098. case BABYLON.VertexBuffer.UV2Kind:
  36099. this.uvs2 = data;
  36100. break;
  36101. case BABYLON.VertexBuffer.UV3Kind:
  36102. this.uvs3 = data;
  36103. break;
  36104. case BABYLON.VertexBuffer.UV4Kind:
  36105. this.uvs4 = data;
  36106. break;
  36107. case BABYLON.VertexBuffer.UV5Kind:
  36108. this.uvs5 = data;
  36109. break;
  36110. case BABYLON.VertexBuffer.UV6Kind:
  36111. this.uvs6 = data;
  36112. break;
  36113. case BABYLON.VertexBuffer.ColorKind:
  36114. this.colors = data;
  36115. break;
  36116. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36117. this.matricesIndices = data;
  36118. break;
  36119. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36120. this.matricesWeights = data;
  36121. break;
  36122. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36123. this.matricesIndicesExtra = data;
  36124. break;
  36125. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36126. this.matricesWeightsExtra = data;
  36127. break;
  36128. }
  36129. };
  36130. /**
  36131. * Associates the vertexData to the passed Mesh.
  36132. * Sets it as updatable or not (default `false`)
  36133. * @param mesh the mesh the vertexData is applied to
  36134. * @param updatable when used and having the value true allows new data to update the vertexData
  36135. * @returns the VertexData
  36136. */
  36137. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36138. this._applyTo(mesh, updatable);
  36139. return this;
  36140. };
  36141. /**
  36142. * Associates the vertexData to the passed Geometry.
  36143. * Sets it as updatable or not (default `false`)
  36144. * @param geometry the geometry the vertexData is applied to
  36145. * @param updatable when used and having the value true allows new data to update the vertexData
  36146. * @returns VertexData
  36147. */
  36148. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36149. this._applyTo(geometry, updatable);
  36150. return this;
  36151. };
  36152. /**
  36153. * Updates the associated mesh
  36154. * @param mesh the mesh to be updated
  36155. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36156. * @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
  36157. * @returns VertexData
  36158. */
  36159. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36160. this._update(mesh);
  36161. return this;
  36162. };
  36163. /**
  36164. * Updates the associated geometry
  36165. * @param geometry the geometry to be updated
  36166. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36167. * @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
  36168. * @returns VertexData.
  36169. */
  36170. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36171. this._update(geometry);
  36172. return this;
  36173. };
  36174. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36175. if (updatable === void 0) { updatable = false; }
  36176. if (this.positions) {
  36177. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36178. }
  36179. if (this.normals) {
  36180. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36181. }
  36182. if (this.tangents) {
  36183. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36184. }
  36185. if (this.uvs) {
  36186. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36187. }
  36188. if (this.uvs2) {
  36189. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36190. }
  36191. if (this.uvs3) {
  36192. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36193. }
  36194. if (this.uvs4) {
  36195. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36196. }
  36197. if (this.uvs5) {
  36198. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36199. }
  36200. if (this.uvs6) {
  36201. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36202. }
  36203. if (this.colors) {
  36204. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36205. }
  36206. if (this.matricesIndices) {
  36207. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36208. }
  36209. if (this.matricesWeights) {
  36210. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36211. }
  36212. if (this.matricesIndicesExtra) {
  36213. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36214. }
  36215. if (this.matricesWeightsExtra) {
  36216. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36217. }
  36218. if (this.indices) {
  36219. meshOrGeometry.setIndices(this.indices, null, updatable);
  36220. }
  36221. else {
  36222. meshOrGeometry.setIndices([], null);
  36223. }
  36224. return this;
  36225. };
  36226. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36227. if (this.positions) {
  36228. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36229. }
  36230. if (this.normals) {
  36231. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36232. }
  36233. if (this.tangents) {
  36234. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36235. }
  36236. if (this.uvs) {
  36237. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36238. }
  36239. if (this.uvs2) {
  36240. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36241. }
  36242. if (this.uvs3) {
  36243. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36244. }
  36245. if (this.uvs4) {
  36246. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36247. }
  36248. if (this.uvs5) {
  36249. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36250. }
  36251. if (this.uvs6) {
  36252. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36253. }
  36254. if (this.colors) {
  36255. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36256. }
  36257. if (this.matricesIndices) {
  36258. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36259. }
  36260. if (this.matricesWeights) {
  36261. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36262. }
  36263. if (this.matricesIndicesExtra) {
  36264. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36265. }
  36266. if (this.matricesWeightsExtra) {
  36267. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36268. }
  36269. if (this.indices) {
  36270. meshOrGeometry.setIndices(this.indices, null);
  36271. }
  36272. return this;
  36273. };
  36274. /**
  36275. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36276. * @param matrix the transforming matrix
  36277. * @returns the VertexData
  36278. */
  36279. VertexData.prototype.transform = function (matrix) {
  36280. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36281. var transformed = BABYLON.Vector3.Zero();
  36282. var index;
  36283. if (this.positions) {
  36284. var position = BABYLON.Vector3.Zero();
  36285. for (index = 0; index < this.positions.length; index += 3) {
  36286. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36287. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36288. this.positions[index] = transformed.x;
  36289. this.positions[index + 1] = transformed.y;
  36290. this.positions[index + 2] = transformed.z;
  36291. }
  36292. }
  36293. if (this.normals) {
  36294. var normal = BABYLON.Vector3.Zero();
  36295. for (index = 0; index < this.normals.length; index += 3) {
  36296. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36297. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36298. this.normals[index] = transformed.x;
  36299. this.normals[index + 1] = transformed.y;
  36300. this.normals[index + 2] = transformed.z;
  36301. }
  36302. }
  36303. if (this.tangents) {
  36304. var tangent = BABYLON.Vector4.Zero();
  36305. var tangentTransformed = BABYLON.Vector4.Zero();
  36306. for (index = 0; index < this.tangents.length; index += 4) {
  36307. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36308. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36309. this.tangents[index] = tangentTransformed.x;
  36310. this.tangents[index + 1] = tangentTransformed.y;
  36311. this.tangents[index + 2] = tangentTransformed.z;
  36312. this.tangents[index + 3] = tangentTransformed.w;
  36313. }
  36314. }
  36315. if (flip && this.indices) {
  36316. for (index = 0; index < this.indices.length; index += 3) {
  36317. var tmp = this.indices[index + 1];
  36318. this.indices[index + 1] = this.indices[index + 2];
  36319. this.indices[index + 2] = tmp;
  36320. }
  36321. }
  36322. return this;
  36323. };
  36324. /**
  36325. * Merges the passed VertexData into the current one
  36326. * @param other the VertexData to be merged into the current one
  36327. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36328. * @returns the modified VertexData
  36329. */
  36330. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36331. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36332. this._validate();
  36333. other._validate();
  36334. if (!this.normals !== !other.normals ||
  36335. !this.tangents !== !other.tangents ||
  36336. !this.uvs !== !other.uvs ||
  36337. !this.uvs2 !== !other.uvs2 ||
  36338. !this.uvs3 !== !other.uvs3 ||
  36339. !this.uvs4 !== !other.uvs4 ||
  36340. !this.uvs5 !== !other.uvs5 ||
  36341. !this.uvs6 !== !other.uvs6 ||
  36342. !this.colors !== !other.colors ||
  36343. !this.matricesIndices !== !other.matricesIndices ||
  36344. !this.matricesWeights !== !other.matricesWeights ||
  36345. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36346. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36347. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36348. }
  36349. if (other.indices) {
  36350. if (!this.indices) {
  36351. this.indices = [];
  36352. }
  36353. var offset = this.positions ? this.positions.length / 3 : 0;
  36354. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36355. if (isSrcTypedArray) {
  36356. var len = this.indices.length + other.indices.length;
  36357. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36358. temp.set(this.indices);
  36359. var decal = this.indices.length;
  36360. for (var index = 0; index < other.indices.length; index++) {
  36361. temp[decal + index] = other.indices[index] + offset;
  36362. }
  36363. this.indices = temp;
  36364. }
  36365. else {
  36366. for (var index = 0; index < other.indices.length; index++) {
  36367. this.indices.push(other.indices[index] + offset);
  36368. }
  36369. }
  36370. }
  36371. this.positions = this._mergeElement(this.positions, other.positions);
  36372. this.normals = this._mergeElement(this.normals, other.normals);
  36373. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36374. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36375. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36376. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36377. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36378. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36379. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36380. this.colors = this._mergeElement(this.colors, other.colors);
  36381. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36382. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36383. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36384. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36385. return this;
  36386. };
  36387. VertexData.prototype._mergeElement = function (source, other) {
  36388. if (!source) {
  36389. return other;
  36390. }
  36391. if (!other) {
  36392. return source;
  36393. }
  36394. var len = other.length + source.length;
  36395. var isSrcTypedArray = source instanceof Float32Array;
  36396. var isOthTypedArray = other instanceof Float32Array;
  36397. // use non-loop method when the source is Float32Array
  36398. if (isSrcTypedArray) {
  36399. var ret32 = new Float32Array(len);
  36400. ret32.set(source);
  36401. ret32.set(other, source.length);
  36402. return ret32;
  36403. // source is number[], when other is also use concat
  36404. }
  36405. else if (!isOthTypedArray) {
  36406. return source.concat(other);
  36407. // source is a number[], but other is a Float32Array, loop required
  36408. }
  36409. else {
  36410. var ret = source.slice(0); // copy source to a separate array
  36411. for (var i = 0, len = other.length; i < len; i++) {
  36412. ret.push(other[i]);
  36413. }
  36414. return ret;
  36415. }
  36416. };
  36417. VertexData.prototype._validate = function () {
  36418. if (!this.positions) {
  36419. throw new Error("Positions are required");
  36420. }
  36421. var getElementCount = function (kind, values) {
  36422. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36423. if ((values.length % stride) !== 0) {
  36424. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36425. }
  36426. return values.length / stride;
  36427. };
  36428. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36429. var validateElementCount = function (kind, values) {
  36430. var elementCount = getElementCount(kind, values);
  36431. if (elementCount !== positionsElementCount) {
  36432. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36433. }
  36434. };
  36435. if (this.normals)
  36436. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36437. if (this.tangents)
  36438. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36439. if (this.uvs)
  36440. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36441. if (this.uvs2)
  36442. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36443. if (this.uvs3)
  36444. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36445. if (this.uvs4)
  36446. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36447. if (this.uvs5)
  36448. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36449. if (this.uvs6)
  36450. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36451. if (this.colors)
  36452. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36453. if (this.matricesIndices)
  36454. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36455. if (this.matricesWeights)
  36456. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36457. if (this.matricesIndicesExtra)
  36458. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36459. if (this.matricesWeightsExtra)
  36460. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36461. };
  36462. /**
  36463. * Serializes the VertexData
  36464. * @returns a serialized object
  36465. */
  36466. VertexData.prototype.serialize = function () {
  36467. var serializationObject = this.serialize();
  36468. if (this.positions) {
  36469. serializationObject.positions = this.positions;
  36470. }
  36471. if (this.normals) {
  36472. serializationObject.normals = this.normals;
  36473. }
  36474. if (this.tangents) {
  36475. serializationObject.tangents = this.tangents;
  36476. }
  36477. if (this.uvs) {
  36478. serializationObject.uvs = this.uvs;
  36479. }
  36480. if (this.uvs2) {
  36481. serializationObject.uvs2 = this.uvs2;
  36482. }
  36483. if (this.uvs3) {
  36484. serializationObject.uvs3 = this.uvs3;
  36485. }
  36486. if (this.uvs4) {
  36487. serializationObject.uvs4 = this.uvs4;
  36488. }
  36489. if (this.uvs5) {
  36490. serializationObject.uvs5 = this.uvs5;
  36491. }
  36492. if (this.uvs6) {
  36493. serializationObject.uvs6 = this.uvs6;
  36494. }
  36495. if (this.colors) {
  36496. serializationObject.colors = this.colors;
  36497. }
  36498. if (this.matricesIndices) {
  36499. serializationObject.matricesIndices = this.matricesIndices;
  36500. serializationObject.matricesIndices._isExpanded = true;
  36501. }
  36502. if (this.matricesWeights) {
  36503. serializationObject.matricesWeights = this.matricesWeights;
  36504. }
  36505. if (this.matricesIndicesExtra) {
  36506. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36507. serializationObject.matricesIndicesExtra._isExpanded = true;
  36508. }
  36509. if (this.matricesWeightsExtra) {
  36510. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36511. }
  36512. serializationObject.indices = this.indices;
  36513. return serializationObject;
  36514. };
  36515. // Statics
  36516. /**
  36517. * Extracts the vertexData from a mesh
  36518. * @param mesh the mesh from which to extract the VertexData
  36519. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36520. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36521. * @returns the object VertexData associated to the passed mesh
  36522. */
  36523. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36524. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36525. };
  36526. /**
  36527. * Extracts the vertexData from the geometry
  36528. * @param geometry the geometry from which to extract the VertexData
  36529. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36530. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36531. * @returns the object VertexData associated to the passed mesh
  36532. */
  36533. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36534. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36535. };
  36536. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36537. var result = new VertexData();
  36538. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36539. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36540. }
  36541. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36542. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36543. }
  36544. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36545. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36546. }
  36547. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36548. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36549. }
  36550. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36551. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36552. }
  36553. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36554. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36555. }
  36556. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36557. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36558. }
  36559. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36560. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36561. }
  36562. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36563. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36564. }
  36565. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36566. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36567. }
  36568. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36569. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36570. }
  36571. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36572. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36573. }
  36574. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36575. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36576. }
  36577. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36578. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36579. }
  36580. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36581. return result;
  36582. };
  36583. /**
  36584. * Creates the VertexData for a Ribbon
  36585. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36586. * * pathArray array of paths, each of which an array of successive Vector3
  36587. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36588. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36589. * * 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
  36590. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36591. * * 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)
  36592. * * 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)
  36593. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36594. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36595. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36596. * @returns the VertexData of the ribbon
  36597. */
  36598. VertexData.CreateRibbon = function (options) {
  36599. var pathArray = options.pathArray;
  36600. var closeArray = options.closeArray || false;
  36601. var closePath = options.closePath || false;
  36602. var invertUV = options.invertUV || false;
  36603. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36604. var offset = options.offset || defaultOffset;
  36605. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36606. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36607. var customUV = options.uvs;
  36608. var customColors = options.colors;
  36609. var positions = [];
  36610. var indices = [];
  36611. var normals = [];
  36612. var uvs = [];
  36613. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36614. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36615. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36616. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36617. var minlg; // minimal length among all paths from pathArray
  36618. var lg = []; // array of path lengths : nb of vertex per path
  36619. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36620. var p; // path iterator
  36621. var i; // point iterator
  36622. var j; // point iterator
  36623. // if single path in pathArray
  36624. if (pathArray.length < 2) {
  36625. var ar1 = [];
  36626. var ar2 = [];
  36627. for (i = 0; i < pathArray[0].length - offset; i++) {
  36628. ar1.push(pathArray[0][i]);
  36629. ar2.push(pathArray[0][i + offset]);
  36630. }
  36631. pathArray = [ar1, ar2];
  36632. }
  36633. // positions and horizontal distances (u)
  36634. var idc = 0;
  36635. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36636. var path;
  36637. var l;
  36638. minlg = pathArray[0].length;
  36639. var vectlg;
  36640. var dist;
  36641. for (p = 0; p < pathArray.length; p++) {
  36642. uTotalDistance[p] = 0;
  36643. us[p] = [0];
  36644. path = pathArray[p];
  36645. l = path.length;
  36646. minlg = (minlg < l) ? minlg : l;
  36647. j = 0;
  36648. while (j < l) {
  36649. positions.push(path[j].x, path[j].y, path[j].z);
  36650. if (j > 0) {
  36651. vectlg = path[j].subtract(path[j - 1]).length();
  36652. dist = vectlg + uTotalDistance[p];
  36653. us[p].push(dist);
  36654. uTotalDistance[p] = dist;
  36655. }
  36656. j++;
  36657. }
  36658. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36659. j--;
  36660. positions.push(path[0].x, path[0].y, path[0].z);
  36661. vectlg = path[j].subtract(path[0]).length();
  36662. dist = vectlg + uTotalDistance[p];
  36663. us[p].push(dist);
  36664. uTotalDistance[p] = dist;
  36665. }
  36666. lg[p] = l + closePathCorr;
  36667. idx[p] = idc;
  36668. idc += (l + closePathCorr);
  36669. }
  36670. // vertical distances (v)
  36671. var path1;
  36672. var path2;
  36673. var vertex1 = null;
  36674. var vertex2 = null;
  36675. for (i = 0; i < minlg + closePathCorr; i++) {
  36676. vTotalDistance[i] = 0;
  36677. vs[i] = [0];
  36678. for (p = 0; p < pathArray.length - 1; p++) {
  36679. path1 = pathArray[p];
  36680. path2 = pathArray[p + 1];
  36681. if (i === minlg) { // closePath
  36682. vertex1 = path1[0];
  36683. vertex2 = path2[0];
  36684. }
  36685. else {
  36686. vertex1 = path1[i];
  36687. vertex2 = path2[i];
  36688. }
  36689. vectlg = vertex2.subtract(vertex1).length();
  36690. dist = vectlg + vTotalDistance[i];
  36691. vs[i].push(dist);
  36692. vTotalDistance[i] = dist;
  36693. }
  36694. if (closeArray && vertex2 && vertex1) {
  36695. path1 = pathArray[p];
  36696. path2 = pathArray[0];
  36697. if (i === minlg) { // closePath
  36698. vertex2 = path2[0];
  36699. }
  36700. vectlg = vertex2.subtract(vertex1).length();
  36701. dist = vectlg + vTotalDistance[i];
  36702. vTotalDistance[i] = dist;
  36703. }
  36704. }
  36705. // uvs
  36706. var u;
  36707. var v;
  36708. if (customUV) {
  36709. for (p = 0; p < customUV.length; p++) {
  36710. uvs.push(customUV[p].x, customUV[p].y);
  36711. }
  36712. }
  36713. else {
  36714. for (p = 0; p < pathArray.length; p++) {
  36715. for (i = 0; i < minlg + closePathCorr; i++) {
  36716. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36717. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36718. if (invertUV) {
  36719. uvs.push(v, u);
  36720. }
  36721. else {
  36722. uvs.push(u, v);
  36723. }
  36724. }
  36725. }
  36726. }
  36727. // indices
  36728. p = 0; // path index
  36729. var pi = 0; // positions array index
  36730. var l1 = lg[p] - 1; // path1 length
  36731. var l2 = lg[p + 1] - 1; // path2 length
  36732. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36733. var shft = idx[1] - idx[0]; // shift
  36734. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36735. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36736. // 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
  36737. indices.push(pi, pi + shft, pi + 1);
  36738. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36739. pi += 1;
  36740. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36741. p++;
  36742. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36743. shft = idx[0] - idx[p];
  36744. l1 = lg[p] - 1;
  36745. l2 = lg[0] - 1;
  36746. }
  36747. else {
  36748. shft = idx[p + 1] - idx[p];
  36749. l1 = lg[p] - 1;
  36750. l2 = lg[p + 1] - 1;
  36751. }
  36752. pi = idx[p];
  36753. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36754. }
  36755. }
  36756. // normals
  36757. VertexData.ComputeNormals(positions, indices, normals);
  36758. if (closePath) { // update both the first and last vertex normals to their average value
  36759. var indexFirst = 0;
  36760. var indexLast = 0;
  36761. for (p = 0; p < pathArray.length; p++) {
  36762. indexFirst = idx[p] * 3;
  36763. if (p + 1 < pathArray.length) {
  36764. indexLast = (idx[p + 1] - 1) * 3;
  36765. }
  36766. else {
  36767. indexLast = normals.length - 3;
  36768. }
  36769. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36770. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36771. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36772. normals[indexLast] = normals[indexFirst];
  36773. normals[indexLast + 1] = normals[indexFirst + 1];
  36774. normals[indexLast + 2] = normals[indexFirst + 2];
  36775. }
  36776. }
  36777. // sides
  36778. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36779. // Colors
  36780. var colors = null;
  36781. if (customColors) {
  36782. colors = new Float32Array(customColors.length * 4);
  36783. for (var c = 0; c < customColors.length; c++) {
  36784. colors[c * 4] = customColors[c].r;
  36785. colors[c * 4 + 1] = customColors[c].g;
  36786. colors[c * 4 + 2] = customColors[c].b;
  36787. colors[c * 4 + 3] = customColors[c].a;
  36788. }
  36789. }
  36790. // Result
  36791. var vertexData = new VertexData();
  36792. var positions32 = new Float32Array(positions);
  36793. var normals32 = new Float32Array(normals);
  36794. var uvs32 = new Float32Array(uvs);
  36795. vertexData.indices = indices;
  36796. vertexData.positions = positions32;
  36797. vertexData.normals = normals32;
  36798. vertexData.uvs = uvs32;
  36799. if (colors) {
  36800. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36801. }
  36802. if (closePath) {
  36803. vertexData._idx = idx;
  36804. }
  36805. return vertexData;
  36806. };
  36807. /**
  36808. * Creates the VertexData for a box
  36809. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36810. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36811. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36812. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36813. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36814. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36815. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36816. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36817. * * 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)
  36818. * * 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)
  36819. * @returns the VertexData of the box
  36820. */
  36821. VertexData.CreateBox = function (options) {
  36822. var normalsSource = [
  36823. new BABYLON.Vector3(0, 0, 1),
  36824. new BABYLON.Vector3(0, 0, -1),
  36825. new BABYLON.Vector3(1, 0, 0),
  36826. new BABYLON.Vector3(-1, 0, 0),
  36827. new BABYLON.Vector3(0, 1, 0),
  36828. new BABYLON.Vector3(0, -1, 0)
  36829. ];
  36830. var indices = [];
  36831. var positions = [];
  36832. var normals = [];
  36833. var uvs = [];
  36834. var width = options.width || options.size || 1;
  36835. var height = options.height || options.size || 1;
  36836. var depth = options.depth || options.size || 1;
  36837. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36838. var faceUV = options.faceUV || new Array(6);
  36839. var faceColors = options.faceColors;
  36840. var colors = [];
  36841. // default face colors and UV if undefined
  36842. for (var f = 0; f < 6; f++) {
  36843. if (faceUV[f] === undefined) {
  36844. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36845. }
  36846. if (faceColors && faceColors[f] === undefined) {
  36847. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36848. }
  36849. }
  36850. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36851. // Create each face in turn.
  36852. for (var index = 0; index < normalsSource.length; index++) {
  36853. var normal = normalsSource[index];
  36854. // Get two vectors perpendicular to the face normal and to each other.
  36855. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36856. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36857. // Six indices (two triangles) per face.
  36858. var verticesLength = positions.length / 3;
  36859. indices.push(verticesLength);
  36860. indices.push(verticesLength + 1);
  36861. indices.push(verticesLength + 2);
  36862. indices.push(verticesLength);
  36863. indices.push(verticesLength + 2);
  36864. indices.push(verticesLength + 3);
  36865. // Four vertices per face.
  36866. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36867. positions.push(vertex.x, vertex.y, vertex.z);
  36868. normals.push(normal.x, normal.y, normal.z);
  36869. uvs.push(faceUV[index].z, faceUV[index].w);
  36870. if (faceColors) {
  36871. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36872. }
  36873. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36874. positions.push(vertex.x, vertex.y, vertex.z);
  36875. normals.push(normal.x, normal.y, normal.z);
  36876. uvs.push(faceUV[index].x, faceUV[index].w);
  36877. if (faceColors) {
  36878. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36879. }
  36880. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36881. positions.push(vertex.x, vertex.y, vertex.z);
  36882. normals.push(normal.x, normal.y, normal.z);
  36883. uvs.push(faceUV[index].x, faceUV[index].y);
  36884. if (faceColors) {
  36885. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36886. }
  36887. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36888. positions.push(vertex.x, vertex.y, vertex.z);
  36889. normals.push(normal.x, normal.y, normal.z);
  36890. uvs.push(faceUV[index].z, faceUV[index].y);
  36891. if (faceColors) {
  36892. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36893. }
  36894. }
  36895. // sides
  36896. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36897. // Result
  36898. var vertexData = new VertexData();
  36899. vertexData.indices = indices;
  36900. vertexData.positions = positions;
  36901. vertexData.normals = normals;
  36902. vertexData.uvs = uvs;
  36903. if (faceColors) {
  36904. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36905. vertexData.colors = totalColors;
  36906. }
  36907. return vertexData;
  36908. };
  36909. /**
  36910. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36911. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36912. * * segments sets the number of horizontal strips optional, default 32
  36913. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36914. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36915. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36916. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36917. * * 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
  36918. * * 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
  36919. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36920. * * 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)
  36921. * * 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)
  36922. * @returns the VertexData of the ellipsoid
  36923. */
  36924. VertexData.CreateSphere = function (options) {
  36925. var segments = options.segments || 32;
  36926. var diameterX = options.diameterX || options.diameter || 1;
  36927. var diameterY = options.diameterY || options.diameter || 1;
  36928. var diameterZ = options.diameterZ || options.diameter || 1;
  36929. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36930. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36931. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36932. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36933. var totalZRotationSteps = 2 + segments;
  36934. var totalYRotationSteps = 2 * totalZRotationSteps;
  36935. var indices = [];
  36936. var positions = [];
  36937. var normals = [];
  36938. var uvs = [];
  36939. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36940. var normalizedZ = zRotationStep / totalZRotationSteps;
  36941. var angleZ = normalizedZ * Math.PI * slice;
  36942. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36943. var normalizedY = yRotationStep / totalYRotationSteps;
  36944. var angleY = normalizedY * Math.PI * 2 * arc;
  36945. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36946. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36947. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36948. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36949. var vertex = complete.multiply(radius);
  36950. var normal = complete.divide(radius).normalize();
  36951. positions.push(vertex.x, vertex.y, vertex.z);
  36952. normals.push(normal.x, normal.y, normal.z);
  36953. uvs.push(normalizedY, normalizedZ);
  36954. }
  36955. if (zRotationStep > 0) {
  36956. var verticesCount = positions.length / 3;
  36957. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36958. indices.push((firstIndex));
  36959. indices.push((firstIndex + 1));
  36960. indices.push(firstIndex + totalYRotationSteps + 1);
  36961. indices.push((firstIndex + totalYRotationSteps + 1));
  36962. indices.push((firstIndex + 1));
  36963. indices.push((firstIndex + totalYRotationSteps + 2));
  36964. }
  36965. }
  36966. }
  36967. // Sides
  36968. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36969. // Result
  36970. var vertexData = new VertexData();
  36971. vertexData.indices = indices;
  36972. vertexData.positions = positions;
  36973. vertexData.normals = normals;
  36974. vertexData.uvs = uvs;
  36975. return vertexData;
  36976. };
  36977. /**
  36978. * Creates the VertexData for a cylinder, cone or prism
  36979. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36980. * * height sets the height (y direction) of the cylinder, optional, default 2
  36981. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36982. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36983. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36984. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36985. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36986. * * 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
  36987. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36988. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36989. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36990. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36991. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36992. * * 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)
  36993. * * 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)
  36994. * @returns the VertexData of the cylinder, cone or prism
  36995. */
  36996. VertexData.CreateCylinder = function (options) {
  36997. var height = options.height || 2;
  36998. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36999. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37000. var tessellation = options.tessellation || 24;
  37001. var subdivisions = options.subdivisions || 1;
  37002. var hasRings = options.hasRings ? true : false;
  37003. var enclose = options.enclose ? true : false;
  37004. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37005. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37006. var faceUV = options.faceUV || new Array(3);
  37007. var faceColors = options.faceColors;
  37008. // default face colors and UV if undefined
  37009. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37010. var ringNb = (hasRings) ? subdivisions : 1;
  37011. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37012. var f;
  37013. for (f = 0; f < surfaceNb; f++) {
  37014. if (faceColors && faceColors[f] === undefined) {
  37015. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37016. }
  37017. }
  37018. for (f = 0; f < surfaceNb; f++) {
  37019. if (faceUV && faceUV[f] === undefined) {
  37020. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37021. }
  37022. }
  37023. var indices = new Array();
  37024. var positions = new Array();
  37025. var normals = new Array();
  37026. var uvs = new Array();
  37027. var colors = new Array();
  37028. var angle_step = Math.PI * 2 * arc / tessellation;
  37029. var angle;
  37030. var h;
  37031. var radius;
  37032. var tan = (diameterBottom - diameterTop) / 2 / height;
  37033. var ringVertex = BABYLON.Vector3.Zero();
  37034. var ringNormal = BABYLON.Vector3.Zero();
  37035. var ringFirstVertex = BABYLON.Vector3.Zero();
  37036. var ringFirstNormal = BABYLON.Vector3.Zero();
  37037. var quadNormal = BABYLON.Vector3.Zero();
  37038. var Y = BABYLON.Axis.Y;
  37039. // positions, normals, uvs
  37040. var i;
  37041. var j;
  37042. var r;
  37043. var ringIdx = 1;
  37044. var s = 1; // surface index
  37045. var cs = 0;
  37046. var v = 0;
  37047. for (i = 0; i <= subdivisions; i++) {
  37048. h = i / subdivisions;
  37049. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37050. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37051. for (r = 0; r < ringIdx; r++) {
  37052. if (hasRings) {
  37053. s += r;
  37054. }
  37055. if (enclose) {
  37056. s += 2 * r;
  37057. }
  37058. for (j = 0; j <= tessellation; j++) {
  37059. angle = j * angle_step;
  37060. // position
  37061. ringVertex.x = Math.cos(-angle) * radius;
  37062. ringVertex.y = -height / 2 + h * height;
  37063. ringVertex.z = Math.sin(-angle) * radius;
  37064. // normal
  37065. if (diameterTop === 0 && i === subdivisions) {
  37066. // if no top cap, reuse former normals
  37067. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37068. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37069. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37070. }
  37071. else {
  37072. ringNormal.x = ringVertex.x;
  37073. ringNormal.z = ringVertex.z;
  37074. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37075. ringNormal.normalize();
  37076. }
  37077. // keep first ring vertex values for enclose
  37078. if (j === 0) {
  37079. ringFirstVertex.copyFrom(ringVertex);
  37080. ringFirstNormal.copyFrom(ringNormal);
  37081. }
  37082. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37083. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37084. if (hasRings) {
  37085. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37086. }
  37087. else {
  37088. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37089. }
  37090. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37091. if (faceColors) {
  37092. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37093. }
  37094. }
  37095. // if enclose, add four vertices and their dedicated normals
  37096. if (arc !== 1 && enclose) {
  37097. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37098. positions.push(0, ringVertex.y, 0);
  37099. positions.push(0, ringVertex.y, 0);
  37100. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37101. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37102. quadNormal.normalize();
  37103. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37104. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37105. quadNormal.normalize();
  37106. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37107. if (hasRings) {
  37108. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37109. }
  37110. else {
  37111. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37112. }
  37113. uvs.push(faceUV[s + 1].x, v);
  37114. uvs.push(faceUV[s + 1].z, v);
  37115. if (hasRings) {
  37116. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37117. }
  37118. else {
  37119. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37120. }
  37121. uvs.push(faceUV[s + 2].x, v);
  37122. uvs.push(faceUV[s + 2].z, v);
  37123. if (faceColors) {
  37124. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37125. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37126. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37127. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37128. }
  37129. }
  37130. if (cs !== s) {
  37131. cs = s;
  37132. }
  37133. }
  37134. }
  37135. // indices
  37136. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37137. var s;
  37138. i = 0;
  37139. for (s = 0; s < subdivisions; s++) {
  37140. var i0 = 0;
  37141. var i1 = 0;
  37142. var i2 = 0;
  37143. var i3 = 0;
  37144. for (j = 0; j < tessellation; j++) {
  37145. i0 = i * (e + 1) + j;
  37146. i1 = (i + 1) * (e + 1) + j;
  37147. i2 = i * (e + 1) + (j + 1);
  37148. i3 = (i + 1) * (e + 1) + (j + 1);
  37149. indices.push(i0, i1, i2);
  37150. indices.push(i3, i2, i1);
  37151. }
  37152. if (arc !== 1 && enclose) { // if enclose, add two quads
  37153. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37154. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37155. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37156. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37157. }
  37158. i = (hasRings) ? (i + 2) : (i + 1);
  37159. }
  37160. // Caps
  37161. var createCylinderCap = function (isTop) {
  37162. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37163. if (radius === 0) {
  37164. return;
  37165. }
  37166. // Cap positions, normals & uvs
  37167. var angle;
  37168. var circleVector;
  37169. var i;
  37170. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37171. var c = null;
  37172. if (faceColors) {
  37173. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37174. }
  37175. // cap center
  37176. var vbase = positions.length / 3;
  37177. var offset = isTop ? height / 2 : -height / 2;
  37178. var center = new BABYLON.Vector3(0, offset, 0);
  37179. positions.push(center.x, center.y, center.z);
  37180. normals.push(0, isTop ? 1 : -1, 0);
  37181. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37182. if (c) {
  37183. colors.push(c.r, c.g, c.b, c.a);
  37184. }
  37185. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37186. for (i = 0; i <= tessellation; i++) {
  37187. angle = Math.PI * 2 * i * arc / tessellation;
  37188. var cos = Math.cos(-angle);
  37189. var sin = Math.sin(-angle);
  37190. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37191. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37192. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37193. normals.push(0, isTop ? 1 : -1, 0);
  37194. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37195. if (c) {
  37196. colors.push(c.r, c.g, c.b, c.a);
  37197. }
  37198. }
  37199. // Cap indices
  37200. for (i = 0; i < tessellation; i++) {
  37201. if (!isTop) {
  37202. indices.push(vbase);
  37203. indices.push(vbase + (i + 1));
  37204. indices.push(vbase + (i + 2));
  37205. }
  37206. else {
  37207. indices.push(vbase);
  37208. indices.push(vbase + (i + 2));
  37209. indices.push(vbase + (i + 1));
  37210. }
  37211. }
  37212. };
  37213. // add caps to geometry
  37214. createCylinderCap(false);
  37215. createCylinderCap(true);
  37216. // Sides
  37217. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37218. var vertexData = new VertexData();
  37219. vertexData.indices = indices;
  37220. vertexData.positions = positions;
  37221. vertexData.normals = normals;
  37222. vertexData.uvs = uvs;
  37223. if (faceColors) {
  37224. vertexData.colors = colors;
  37225. }
  37226. return vertexData;
  37227. };
  37228. /**
  37229. * Creates the VertexData for a torus
  37230. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37231. * * diameter the diameter of the torus, optional default 1
  37232. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37233. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37234. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37235. * * 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)
  37236. * * 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)
  37237. * @returns the VertexData of the torus
  37238. */
  37239. VertexData.CreateTorus = function (options) {
  37240. var indices = [];
  37241. var positions = [];
  37242. var normals = [];
  37243. var uvs = [];
  37244. var diameter = options.diameter || 1;
  37245. var thickness = options.thickness || 0.5;
  37246. var tessellation = options.tessellation || 16;
  37247. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37248. var stride = tessellation + 1;
  37249. for (var i = 0; i <= tessellation; i++) {
  37250. var u = i / tessellation;
  37251. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37252. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37253. for (var j = 0; j <= tessellation; j++) {
  37254. var v = 1 - j / tessellation;
  37255. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37256. var dx = Math.cos(innerAngle);
  37257. var dy = Math.sin(innerAngle);
  37258. // Create a vertex.
  37259. var normal = new BABYLON.Vector3(dx, dy, 0);
  37260. var position = normal.scale(thickness / 2);
  37261. var textureCoordinate = new BABYLON.Vector2(u, v);
  37262. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37263. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37264. positions.push(position.x, position.y, position.z);
  37265. normals.push(normal.x, normal.y, normal.z);
  37266. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37267. // And create indices for two triangles.
  37268. var nextI = (i + 1) % stride;
  37269. var nextJ = (j + 1) % stride;
  37270. indices.push(i * stride + j);
  37271. indices.push(i * stride + nextJ);
  37272. indices.push(nextI * stride + j);
  37273. indices.push(i * stride + nextJ);
  37274. indices.push(nextI * stride + nextJ);
  37275. indices.push(nextI * stride + j);
  37276. }
  37277. }
  37278. // Sides
  37279. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37280. // Result
  37281. var vertexData = new VertexData();
  37282. vertexData.indices = indices;
  37283. vertexData.positions = positions;
  37284. vertexData.normals = normals;
  37285. vertexData.uvs = uvs;
  37286. return vertexData;
  37287. };
  37288. /**
  37289. * Creates the VertexData of the LineSystem
  37290. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37291. * - lines an array of lines, each line being an array of successive Vector3
  37292. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37293. * @returns the VertexData of the LineSystem
  37294. */
  37295. VertexData.CreateLineSystem = function (options) {
  37296. var indices = [];
  37297. var positions = [];
  37298. var lines = options.lines;
  37299. var colors = options.colors;
  37300. var vertexColors = [];
  37301. var idx = 0;
  37302. for (var l = 0; l < lines.length; l++) {
  37303. var points = lines[l];
  37304. for (var index = 0; index < points.length; index++) {
  37305. positions.push(points[index].x, points[index].y, points[index].z);
  37306. if (colors) {
  37307. var color = colors[l];
  37308. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37309. }
  37310. if (index > 0) {
  37311. indices.push(idx - 1);
  37312. indices.push(idx);
  37313. }
  37314. idx++;
  37315. }
  37316. }
  37317. var vertexData = new VertexData();
  37318. vertexData.indices = indices;
  37319. vertexData.positions = positions;
  37320. if (colors) {
  37321. vertexData.colors = vertexColors;
  37322. }
  37323. return vertexData;
  37324. };
  37325. /**
  37326. * Create the VertexData for a DashedLines
  37327. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37328. * - points an array successive Vector3
  37329. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37330. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37331. * - dashNb the intended total number of dashes, optional, default 200
  37332. * @returns the VertexData for the DashedLines
  37333. */
  37334. VertexData.CreateDashedLines = function (options) {
  37335. var dashSize = options.dashSize || 3;
  37336. var gapSize = options.gapSize || 1;
  37337. var dashNb = options.dashNb || 200;
  37338. var points = options.points;
  37339. var positions = new Array();
  37340. var indices = new Array();
  37341. var curvect = BABYLON.Vector3.Zero();
  37342. var lg = 0;
  37343. var nb = 0;
  37344. var shft = 0;
  37345. var dashshft = 0;
  37346. var curshft = 0;
  37347. var idx = 0;
  37348. var i = 0;
  37349. for (i = 0; i < points.length - 1; i++) {
  37350. points[i + 1].subtractToRef(points[i], curvect);
  37351. lg += curvect.length();
  37352. }
  37353. shft = lg / dashNb;
  37354. dashshft = dashSize * shft / (dashSize + gapSize);
  37355. for (i = 0; i < points.length - 1; i++) {
  37356. points[i + 1].subtractToRef(points[i], curvect);
  37357. nb = Math.floor(curvect.length() / shft);
  37358. curvect.normalize();
  37359. for (var j = 0; j < nb; j++) {
  37360. curshft = shft * j;
  37361. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37362. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37363. indices.push(idx, idx + 1);
  37364. idx += 2;
  37365. }
  37366. }
  37367. // Result
  37368. var vertexData = new VertexData();
  37369. vertexData.positions = positions;
  37370. vertexData.indices = indices;
  37371. return vertexData;
  37372. };
  37373. /**
  37374. * Creates the VertexData for a Ground
  37375. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37376. * - width the width (x direction) of the ground, optional, default 1
  37377. * - height the height (z direction) of the ground, optional, default 1
  37378. * - subdivisions the number of subdivisions per side, optional, default 1
  37379. * @returns the VertexData of the Ground
  37380. */
  37381. VertexData.CreateGround = function (options) {
  37382. var indices = [];
  37383. var positions = [];
  37384. var normals = [];
  37385. var uvs = [];
  37386. var row, col;
  37387. var width = options.width || 1;
  37388. var height = options.height || 1;
  37389. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37390. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37391. for (row = 0; row <= subdivisionsY; row++) {
  37392. for (col = 0; col <= subdivisionsX; col++) {
  37393. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37394. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37395. positions.push(position.x, position.y, position.z);
  37396. normals.push(normal.x, normal.y, normal.z);
  37397. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37398. }
  37399. }
  37400. for (row = 0; row < subdivisionsY; row++) {
  37401. for (col = 0; col < subdivisionsX; col++) {
  37402. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37403. indices.push(col + 1 + row * (subdivisionsX + 1));
  37404. indices.push(col + row * (subdivisionsX + 1));
  37405. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37406. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37407. indices.push(col + row * (subdivisionsX + 1));
  37408. }
  37409. }
  37410. // Result
  37411. var vertexData = new VertexData();
  37412. vertexData.indices = indices;
  37413. vertexData.positions = positions;
  37414. vertexData.normals = normals;
  37415. vertexData.uvs = uvs;
  37416. return vertexData;
  37417. };
  37418. /**
  37419. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37420. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37421. * * xmin the ground minimum X coordinate, optional, default -1
  37422. * * zmin the ground minimum Z coordinate, optional, default -1
  37423. * * xmax the ground maximum X coordinate, optional, default 1
  37424. * * zmax the ground maximum Z coordinate, optional, default 1
  37425. * * 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}
  37426. * * 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}
  37427. * @returns the VertexData of the TiledGround
  37428. */
  37429. VertexData.CreateTiledGround = function (options) {
  37430. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37431. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37432. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37433. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37434. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37435. var precision = options.precision || { w: 1, h: 1 };
  37436. var indices = new Array();
  37437. var positions = new Array();
  37438. var normals = new Array();
  37439. var uvs = new Array();
  37440. var row, col, tileRow, tileCol;
  37441. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37442. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37443. precision.w = (precision.w < 1) ? 1 : precision.w;
  37444. precision.h = (precision.h < 1) ? 1 : precision.h;
  37445. var tileSize = {
  37446. 'w': (xmax - xmin) / subdivisions.w,
  37447. 'h': (zmax - zmin) / subdivisions.h
  37448. };
  37449. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37450. // Indices
  37451. var base = positions.length / 3;
  37452. var rowLength = precision.w + 1;
  37453. for (row = 0; row < precision.h; row++) {
  37454. for (col = 0; col < precision.w; col++) {
  37455. var square = [
  37456. base + col + row * rowLength,
  37457. base + (col + 1) + row * rowLength,
  37458. base + (col + 1) + (row + 1) * rowLength,
  37459. base + col + (row + 1) * rowLength
  37460. ];
  37461. indices.push(square[1]);
  37462. indices.push(square[2]);
  37463. indices.push(square[3]);
  37464. indices.push(square[0]);
  37465. indices.push(square[1]);
  37466. indices.push(square[3]);
  37467. }
  37468. }
  37469. // Position, normals and uvs
  37470. var position = BABYLON.Vector3.Zero();
  37471. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37472. for (row = 0; row <= precision.h; row++) {
  37473. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37474. for (col = 0; col <= precision.w; col++) {
  37475. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37476. position.y = 0;
  37477. positions.push(position.x, position.y, position.z);
  37478. normals.push(normal.x, normal.y, normal.z);
  37479. uvs.push(col / precision.w, row / precision.h);
  37480. }
  37481. }
  37482. }
  37483. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37484. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37485. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37486. }
  37487. }
  37488. // Result
  37489. var vertexData = new VertexData();
  37490. vertexData.indices = indices;
  37491. vertexData.positions = positions;
  37492. vertexData.normals = normals;
  37493. vertexData.uvs = uvs;
  37494. return vertexData;
  37495. };
  37496. /**
  37497. * Creates the VertexData of the Ground designed from a heightmap
  37498. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37499. * * width the width (x direction) of the ground
  37500. * * height the height (z direction) of the ground
  37501. * * subdivisions the number of subdivisions per side
  37502. * * minHeight the minimum altitude on the ground, optional, default 0
  37503. * * maxHeight the maximum altitude on the ground, optional default 1
  37504. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37505. * * buffer the array holding the image color data
  37506. * * bufferWidth the width of image
  37507. * * bufferHeight the height of image
  37508. * @returns the VertexData of the Ground designed from a heightmap
  37509. */
  37510. VertexData.CreateGroundFromHeightMap = function (options) {
  37511. var indices = [];
  37512. var positions = [];
  37513. var normals = [];
  37514. var uvs = [];
  37515. var row, col;
  37516. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37517. // Vertices
  37518. for (row = 0; row <= options.subdivisions; row++) {
  37519. for (col = 0; col <= options.subdivisions; col++) {
  37520. 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));
  37521. // Compute height
  37522. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37523. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37524. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37525. var r = options.buffer[pos] / 255.0;
  37526. var g = options.buffer[pos + 1] / 255.0;
  37527. var b = options.buffer[pos + 2] / 255.0;
  37528. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37529. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37530. // Add vertex
  37531. positions.push(position.x, position.y, position.z);
  37532. normals.push(0, 0, 0);
  37533. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37534. }
  37535. }
  37536. // Indices
  37537. for (row = 0; row < options.subdivisions; row++) {
  37538. for (col = 0; col < options.subdivisions; col++) {
  37539. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37540. indices.push(col + 1 + row * (options.subdivisions + 1));
  37541. indices.push(col + row * (options.subdivisions + 1));
  37542. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37543. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37544. indices.push(col + row * (options.subdivisions + 1));
  37545. }
  37546. }
  37547. // Normals
  37548. VertexData.ComputeNormals(positions, indices, normals);
  37549. // Result
  37550. var vertexData = new VertexData();
  37551. vertexData.indices = indices;
  37552. vertexData.positions = positions;
  37553. vertexData.normals = normals;
  37554. vertexData.uvs = uvs;
  37555. return vertexData;
  37556. };
  37557. /**
  37558. * Creates the VertexData for a Plane
  37559. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37560. * * size sets the width and height of the plane to the value of size, optional default 1
  37561. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37562. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37563. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37564. * * 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)
  37565. * * 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)
  37566. * @returns the VertexData of the box
  37567. */
  37568. VertexData.CreatePlane = function (options) {
  37569. var indices = [];
  37570. var positions = [];
  37571. var normals = [];
  37572. var uvs = [];
  37573. var width = options.width || options.size || 1;
  37574. var height = options.height || options.size || 1;
  37575. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37576. // Vertices
  37577. var halfWidth = width / 2.0;
  37578. var halfHeight = height / 2.0;
  37579. positions.push(-halfWidth, -halfHeight, 0);
  37580. normals.push(0, 0, -1.0);
  37581. uvs.push(0.0, 0.0);
  37582. positions.push(halfWidth, -halfHeight, 0);
  37583. normals.push(0, 0, -1.0);
  37584. uvs.push(1.0, 0.0);
  37585. positions.push(halfWidth, halfHeight, 0);
  37586. normals.push(0, 0, -1.0);
  37587. uvs.push(1.0, 1.0);
  37588. positions.push(-halfWidth, halfHeight, 0);
  37589. normals.push(0, 0, -1.0);
  37590. uvs.push(0.0, 1.0);
  37591. // Indices
  37592. indices.push(0);
  37593. indices.push(1);
  37594. indices.push(2);
  37595. indices.push(0);
  37596. indices.push(2);
  37597. indices.push(3);
  37598. // Sides
  37599. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37600. // Result
  37601. var vertexData = new VertexData();
  37602. vertexData.indices = indices;
  37603. vertexData.positions = positions;
  37604. vertexData.normals = normals;
  37605. vertexData.uvs = uvs;
  37606. return vertexData;
  37607. };
  37608. /**
  37609. * Creates the VertexData of the Disc or regular Polygon
  37610. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37611. * * radius the radius of the disc, optional default 0.5
  37612. * * tessellation the number of polygon sides, optional, default 64
  37613. * * 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
  37614. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37615. * * 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)
  37616. * * 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)
  37617. * @returns the VertexData of the box
  37618. */
  37619. VertexData.CreateDisc = function (options) {
  37620. var positions = new Array();
  37621. var indices = new Array();
  37622. var normals = new Array();
  37623. var uvs = new Array();
  37624. var radius = options.radius || 0.5;
  37625. var tessellation = options.tessellation || 64;
  37626. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37627. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37628. // positions and uvs
  37629. positions.push(0, 0, 0); // disc center first
  37630. uvs.push(0.5, 0.5);
  37631. var theta = Math.PI * 2 * arc;
  37632. var step = theta / tessellation;
  37633. for (var a = 0; a < theta; a += step) {
  37634. var x = Math.cos(a);
  37635. var y = Math.sin(a);
  37636. var u = (x + 1) / 2;
  37637. var v = (1 - y) / 2;
  37638. positions.push(radius * x, radius * y, 0);
  37639. uvs.push(u, v);
  37640. }
  37641. if (arc === 1) {
  37642. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37643. uvs.push(uvs[2], uvs[3]);
  37644. }
  37645. //indices
  37646. var vertexNb = positions.length / 3;
  37647. for (var i = 1; i < vertexNb - 1; i++) {
  37648. indices.push(i + 1, 0, i);
  37649. }
  37650. // result
  37651. VertexData.ComputeNormals(positions, indices, normals);
  37652. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37653. var vertexData = new VertexData();
  37654. vertexData.indices = indices;
  37655. vertexData.positions = positions;
  37656. vertexData.normals = normals;
  37657. vertexData.uvs = uvs;
  37658. return vertexData;
  37659. };
  37660. /**
  37661. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37662. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37663. * @param polygon a mesh built from polygonTriangulation.build()
  37664. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37665. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37666. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37667. * @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)
  37668. * @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)
  37669. * @returns the VertexData of the Polygon
  37670. */
  37671. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37672. var faceUV = fUV || new Array(3);
  37673. var faceColors = fColors;
  37674. var colors = [];
  37675. // default face colors and UV if undefined
  37676. for (var f = 0; f < 3; f++) {
  37677. if (faceUV[f] === undefined) {
  37678. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37679. }
  37680. if (faceColors && faceColors[f] === undefined) {
  37681. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37682. }
  37683. }
  37684. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37685. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37686. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37687. var indices = polygon.getIndices();
  37688. // set face colours and textures
  37689. var idx = 0;
  37690. var face = 0;
  37691. for (var index = 0; index < normals.length; index += 3) {
  37692. //Edge Face no. 1
  37693. if (Math.abs(normals[index + 1]) < 0.001) {
  37694. face = 1;
  37695. }
  37696. //Top Face no. 0
  37697. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37698. face = 0;
  37699. }
  37700. //Bottom Face no. 2
  37701. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37702. face = 2;
  37703. }
  37704. idx = index / 3;
  37705. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37706. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37707. if (faceColors) {
  37708. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37709. }
  37710. }
  37711. // sides
  37712. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37713. // Result
  37714. var vertexData = new VertexData();
  37715. vertexData.indices = indices;
  37716. vertexData.positions = positions;
  37717. vertexData.normals = normals;
  37718. vertexData.uvs = uvs;
  37719. if (faceColors) {
  37720. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37721. vertexData.colors = totalColors;
  37722. }
  37723. return vertexData;
  37724. };
  37725. /**
  37726. * Creates the VertexData of the IcoSphere
  37727. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37728. * * radius the radius of the IcoSphere, optional default 1
  37729. * * radiusX allows stretching in the x direction, optional, default radius
  37730. * * radiusY allows stretching in the y direction, optional, default radius
  37731. * * radiusZ allows stretching in the z direction, optional, default radius
  37732. * * flat when true creates a flat shaded mesh, optional, default true
  37733. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37734. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37735. * * 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)
  37736. * * 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)
  37737. * @returns the VertexData of the IcoSphere
  37738. */
  37739. VertexData.CreateIcoSphere = function (options) {
  37740. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37741. var radius = options.radius || 1;
  37742. var flat = (options.flat === undefined) ? true : options.flat;
  37743. var subdivisions = options.subdivisions || 4;
  37744. var radiusX = options.radiusX || radius;
  37745. var radiusY = options.radiusY || radius;
  37746. var radiusZ = options.radiusZ || radius;
  37747. var t = (1 + Math.sqrt(5)) / 2;
  37748. // 12 vertex x,y,z
  37749. var ico_vertices = [
  37750. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37751. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37752. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37753. ];
  37754. // index of 3 vertex makes a face of icopshere
  37755. var ico_indices = [
  37756. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37757. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37758. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37759. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37760. ];
  37761. // vertex for uv have aliased position, not for UV
  37762. var vertices_unalias_id = [
  37763. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37764. // vertex alias
  37765. 0,
  37766. 2,
  37767. 3,
  37768. 3,
  37769. 3,
  37770. 4,
  37771. 7,
  37772. 8,
  37773. 9,
  37774. 9,
  37775. 10,
  37776. 11 // 23: B + 12
  37777. ];
  37778. // uv as integer step (not pixels !)
  37779. var ico_vertexuv = [
  37780. 5, 1, 3, 1, 6, 4, 0, 0,
  37781. 5, 3, 4, 2, 2, 2, 4, 0,
  37782. 2, 0, 1, 1, 6, 0, 6, 2,
  37783. // vertex alias (for same vertex on different faces)
  37784. 0, 4,
  37785. 3, 3,
  37786. 4, 4,
  37787. 3, 1,
  37788. 4, 2,
  37789. 4, 4,
  37790. 0, 2,
  37791. 1, 1,
  37792. 2, 2,
  37793. 3, 3,
  37794. 1, 3,
  37795. 2, 4 // 23: B + 12
  37796. ];
  37797. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37798. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37799. // First island of uv mapping
  37800. // v = 4h 3+ 2
  37801. // v = 3h 9+ 4
  37802. // v = 2h 9+ 5 B
  37803. // v = 1h 9 1 0
  37804. // v = 0h 3 8 7 A
  37805. // u = 0 1 2 3 4 5 6 *a
  37806. // Second island of uv mapping
  37807. // v = 4h 0+ B+ 4+
  37808. // v = 3h A+ 2+
  37809. // v = 2h 7+ 6 3+
  37810. // v = 1h 8+ 3+
  37811. // v = 0h
  37812. // u = 0 1 2 3 4 5 6 *a
  37813. // Face layout on texture UV mapping
  37814. // ============
  37815. // \ 4 /\ 16 / ======
  37816. // \ / \ / /\ 11 /
  37817. // \/ 7 \/ / \ /
  37818. // ======= / 10 \/
  37819. // /\ 17 /\ =======
  37820. // / \ / \ \ 15 /\
  37821. // / 8 \/ 12 \ \ / \
  37822. // ============ \/ 6 \
  37823. // \ 18 /\ ============
  37824. // \ / \ \ 5 /\ 0 /
  37825. // \/ 13 \ \ / \ /
  37826. // ======= \/ 1 \/
  37827. // =============
  37828. // /\ 19 /\ 2 /\
  37829. // / \ / \ / \
  37830. // / 14 \/ 9 \/ 3 \
  37831. // ===================
  37832. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37833. var ustep = 138 / 1024;
  37834. var vstep = 239 / 1024;
  37835. var uoffset = 60 / 1024;
  37836. var voffset = 26 / 1024;
  37837. // Second island should have margin, not to touch the first island
  37838. // avoid any borderline artefact in pixel rounding
  37839. var island_u_offset = -40 / 1024;
  37840. var island_v_offset = +20 / 1024;
  37841. // face is either island 0 or 1 :
  37842. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37843. var island = [
  37844. 0, 0, 0, 0, 1,
  37845. 0, 0, 1, 1, 0,
  37846. 0, 0, 1, 1, 0,
  37847. 0, 1, 1, 1, 0 // 15 - 19
  37848. ];
  37849. var indices = new Array();
  37850. var positions = new Array();
  37851. var normals = new Array();
  37852. var uvs = new Array();
  37853. var current_indice = 0;
  37854. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37855. var face_vertex_pos = new Array(3);
  37856. var face_vertex_uv = new Array(3);
  37857. var v012;
  37858. for (v012 = 0; v012 < 3; v012++) {
  37859. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37860. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37861. }
  37862. // create all with normals
  37863. for (var face = 0; face < 20; face++) {
  37864. // 3 vertex per face
  37865. for (v012 = 0; v012 < 3; v012++) {
  37866. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37867. var v_id = ico_indices[3 * face + v012];
  37868. // vertex have 3D position (x,y,z)
  37869. 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]);
  37870. // Normalize to get normal, then scale to radius
  37871. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37872. // uv Coordinates from vertex ID
  37873. 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);
  37874. }
  37875. // Subdivide the face (interpolate pos, norm, uv)
  37876. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37877. // - norm is linear interpolation of vertex corner normal
  37878. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37879. // - uv is linear interpolation
  37880. //
  37881. // Topology is as below for sub-divide by 2
  37882. // vertex shown as v0,v1,v2
  37883. // interp index is i1 to progress in range [v0,v1[
  37884. // interp index is i2 to progress in range [v0,v2[
  37885. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37886. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37887. //
  37888. //
  37889. // i2 v2
  37890. // ^ ^
  37891. // / / \
  37892. // / / \
  37893. // / / \
  37894. // / / (0,1) \
  37895. // / #---------\
  37896. // / / \ (0,0)'/ \
  37897. // / / \ / \
  37898. // / / \ / \
  37899. // / / (0,0) \ / (1,0) \
  37900. // / #---------#---------\
  37901. // v0 v1
  37902. //
  37903. // --------------------> i1
  37904. //
  37905. // interp of (i1,i2):
  37906. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37907. // along i1 : lerp(x0,x1, i1/(S-i2))
  37908. //
  37909. // centroid of triangle is needed to get help normal computation
  37910. // (c1,c2) are used for centroid location
  37911. var interp_vertex = function (i1, i2, c1, c2) {
  37912. // vertex is interpolated from
  37913. // - face_vertex_pos[0..2]
  37914. // - face_vertex_uv[0..2]
  37915. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37916. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37917. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37918. pos_interp.normalize();
  37919. var vertex_normal;
  37920. if (flat) {
  37921. // in flat mode, recalculate normal as face centroid normal
  37922. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37923. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37924. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37925. }
  37926. else {
  37927. // in smooth mode, recalculate normal from each single vertex position
  37928. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37929. }
  37930. // Vertex normal need correction due to X,Y,Z radius scaling
  37931. vertex_normal.x /= radiusX;
  37932. vertex_normal.y /= radiusY;
  37933. vertex_normal.z /= radiusZ;
  37934. vertex_normal.normalize();
  37935. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37936. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37937. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37938. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37939. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37940. uvs.push(uv_interp.x, uv_interp.y);
  37941. // push each vertex has member of a face
  37942. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37943. indices.push(current_indice);
  37944. current_indice++;
  37945. };
  37946. for (var i2 = 0; i2 < subdivisions; i2++) {
  37947. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37948. // face : (i1,i2) for /\ :
  37949. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37950. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37951. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37952. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37953. if (i1 + i2 + 1 < subdivisions) {
  37954. // face : (i1,i2)' for \/ :
  37955. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37956. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37957. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37958. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37959. }
  37960. }
  37961. }
  37962. }
  37963. // Sides
  37964. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37965. // Result
  37966. var vertexData = new VertexData();
  37967. vertexData.indices = indices;
  37968. vertexData.positions = positions;
  37969. vertexData.normals = normals;
  37970. vertexData.uvs = uvs;
  37971. return vertexData;
  37972. };
  37973. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37974. /**
  37975. * Creates the VertexData for a Polyhedron
  37976. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37977. * * type provided types are:
  37978. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37979. * * 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)
  37980. * * size the size of the IcoSphere, optional default 1
  37981. * * sizeX allows stretching in the x direction, optional, default size
  37982. * * sizeY allows stretching in the y direction, optional, default size
  37983. * * sizeZ allows stretching in the z direction, optional, default size
  37984. * * 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
  37985. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37986. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37987. * * flat when true creates a flat shaded mesh, optional, default true
  37988. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37989. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37990. * * 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)
  37991. * * 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)
  37992. * @returns the VertexData of the Polyhedron
  37993. */
  37994. VertexData.CreatePolyhedron = function (options) {
  37995. // provided polyhedron types :
  37996. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37997. // 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)
  37998. var polyhedra = [];
  37999. 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]] };
  38000. 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]] };
  38001. polyhedra[2] = {
  38002. 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]],
  38003. 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]]
  38004. };
  38005. polyhedra[3] = {
  38006. 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]],
  38007. 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]]
  38008. };
  38009. polyhedra[4] = {
  38010. 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]],
  38011. 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]]
  38012. };
  38013. 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]] };
  38014. 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]] };
  38015. 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]] };
  38016. 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]] };
  38017. 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]] };
  38018. 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]] };
  38019. 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]] };
  38020. 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]] };
  38021. 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]] };
  38022. polyhedra[14] = {
  38023. 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]],
  38024. 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]]
  38025. };
  38026. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38027. var size = options.size;
  38028. var sizeX = options.sizeX || size || 1;
  38029. var sizeY = options.sizeY || size || 1;
  38030. var sizeZ = options.sizeZ || size || 1;
  38031. var data = options.custom || polyhedra[type];
  38032. var nbfaces = data.face.length;
  38033. var faceUV = options.faceUV || new Array(nbfaces);
  38034. var faceColors = options.faceColors;
  38035. var flat = (options.flat === undefined) ? true : options.flat;
  38036. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38037. var positions = new Array();
  38038. var indices = new Array();
  38039. var normals = new Array();
  38040. var uvs = new Array();
  38041. var colors = new Array();
  38042. var index = 0;
  38043. var faceIdx = 0; // face cursor in the array "indexes"
  38044. var indexes = new Array();
  38045. var i = 0;
  38046. var f = 0;
  38047. var u, v, ang, x, y, tmp;
  38048. // default face colors and UV if undefined
  38049. if (flat) {
  38050. for (f = 0; f < nbfaces; f++) {
  38051. if (faceColors && faceColors[f] === undefined) {
  38052. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38053. }
  38054. if (faceUV && faceUV[f] === undefined) {
  38055. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38056. }
  38057. }
  38058. }
  38059. if (!flat) {
  38060. for (i = 0; i < data.vertex.length; i++) {
  38061. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38062. uvs.push(0, 0);
  38063. }
  38064. for (f = 0; f < nbfaces; f++) {
  38065. for (i = 0; i < data.face[f].length - 2; i++) {
  38066. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38067. }
  38068. }
  38069. }
  38070. else {
  38071. for (f = 0; f < nbfaces; f++) {
  38072. var fl = data.face[f].length; // number of vertices of the current face
  38073. ang = 2 * Math.PI / fl;
  38074. x = 0.5 * Math.tan(ang / 2);
  38075. y = 0.5;
  38076. // positions, uvs, colors
  38077. for (i = 0; i < fl; i++) {
  38078. // positions
  38079. 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);
  38080. indexes.push(index);
  38081. index++;
  38082. // uvs
  38083. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38084. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38085. uvs.push(u, v);
  38086. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38087. y = x * Math.sin(ang) + y * Math.cos(ang);
  38088. x = tmp;
  38089. // colors
  38090. if (faceColors) {
  38091. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38092. }
  38093. }
  38094. // indices from indexes
  38095. for (i = 0; i < fl - 2; i++) {
  38096. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38097. }
  38098. faceIdx += fl;
  38099. }
  38100. }
  38101. VertexData.ComputeNormals(positions, indices, normals);
  38102. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38103. var vertexData = new VertexData();
  38104. vertexData.positions = positions;
  38105. vertexData.indices = indices;
  38106. vertexData.normals = normals;
  38107. vertexData.uvs = uvs;
  38108. if (faceColors && flat) {
  38109. vertexData.colors = colors;
  38110. }
  38111. return vertexData;
  38112. };
  38113. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38114. /**
  38115. * Creates the VertexData for a TorusKnot
  38116. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38117. * * radius the radius of the torus knot, optional, default 2
  38118. * * tube the thickness of the tube, optional, default 0.5
  38119. * * radialSegments the number of sides on each tube segments, optional, default 32
  38120. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38121. * * p the number of windings around the z axis, optional, default 2
  38122. * * q the number of windings around the x axis, optional, default 3
  38123. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38124. * * 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)
  38125. * * 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)
  38126. * @returns the VertexData of the Torus Knot
  38127. */
  38128. VertexData.CreateTorusKnot = function (options) {
  38129. var indices = new Array();
  38130. var positions = new Array();
  38131. var normals = new Array();
  38132. var uvs = new Array();
  38133. var radius = options.radius || 2;
  38134. var tube = options.tube || 0.5;
  38135. var radialSegments = options.radialSegments || 32;
  38136. var tubularSegments = options.tubularSegments || 32;
  38137. var p = options.p || 2;
  38138. var q = options.q || 3;
  38139. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38140. // Helper
  38141. var getPos = function (angle) {
  38142. var cu = Math.cos(angle);
  38143. var su = Math.sin(angle);
  38144. var quOverP = q / p * angle;
  38145. var cs = Math.cos(quOverP);
  38146. var tx = radius * (2 + cs) * 0.5 * cu;
  38147. var ty = radius * (2 + cs) * su * 0.5;
  38148. var tz = radius * Math.sin(quOverP) * 0.5;
  38149. return new BABYLON.Vector3(tx, ty, tz);
  38150. };
  38151. // Vertices
  38152. var i;
  38153. var j;
  38154. for (i = 0; i <= radialSegments; i++) {
  38155. var modI = i % radialSegments;
  38156. var u = modI / radialSegments * 2 * p * Math.PI;
  38157. var p1 = getPos(u);
  38158. var p2 = getPos(u + 0.01);
  38159. var tang = p2.subtract(p1);
  38160. var n = p2.add(p1);
  38161. var bitan = BABYLON.Vector3.Cross(tang, n);
  38162. n = BABYLON.Vector3.Cross(bitan, tang);
  38163. bitan.normalize();
  38164. n.normalize();
  38165. for (j = 0; j < tubularSegments; j++) {
  38166. var modJ = j % tubularSegments;
  38167. var v = modJ / tubularSegments * 2 * Math.PI;
  38168. var cx = -tube * Math.cos(v);
  38169. var cy = tube * Math.sin(v);
  38170. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38171. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38172. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38173. uvs.push(i / radialSegments);
  38174. uvs.push(j / tubularSegments);
  38175. }
  38176. }
  38177. for (i = 0; i < radialSegments; i++) {
  38178. for (j = 0; j < tubularSegments; j++) {
  38179. var jNext = (j + 1) % tubularSegments;
  38180. var a = i * tubularSegments + j;
  38181. var b = (i + 1) * tubularSegments + j;
  38182. var c = (i + 1) * tubularSegments + jNext;
  38183. var d = i * tubularSegments + jNext;
  38184. indices.push(d);
  38185. indices.push(b);
  38186. indices.push(a);
  38187. indices.push(d);
  38188. indices.push(c);
  38189. indices.push(b);
  38190. }
  38191. }
  38192. // Normals
  38193. VertexData.ComputeNormals(positions, indices, normals);
  38194. // Sides
  38195. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38196. // Result
  38197. var vertexData = new VertexData();
  38198. vertexData.indices = indices;
  38199. vertexData.positions = positions;
  38200. vertexData.normals = normals;
  38201. vertexData.uvs = uvs;
  38202. return vertexData;
  38203. };
  38204. // Tools
  38205. /**
  38206. * Compute normals for given positions and indices
  38207. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38208. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38209. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38210. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38211. * * facetNormals : optional array of facet normals (vector3)
  38212. * * facetPositions : optional array of facet positions (vector3)
  38213. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38214. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38215. * * bInfo : optional bounding info, required for facetPartitioning computation
  38216. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38217. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38218. * * useRightHandedSystem: optional boolean to for right handed system computation
  38219. * * depthSort : optional boolean to enable the facet depth sort computation
  38220. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38221. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38222. */
  38223. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38224. // temporary scalar variables
  38225. var index = 0; // facet index
  38226. var p1p2x = 0.0; // p1p2 vector x coordinate
  38227. var p1p2y = 0.0; // p1p2 vector y coordinate
  38228. var p1p2z = 0.0; // p1p2 vector z coordinate
  38229. var p3p2x = 0.0; // p3p2 vector x coordinate
  38230. var p3p2y = 0.0; // p3p2 vector y coordinate
  38231. var p3p2z = 0.0; // p3p2 vector z coordinate
  38232. var faceNormalx = 0.0; // facet normal x coordinate
  38233. var faceNormaly = 0.0; // facet normal y coordinate
  38234. var faceNormalz = 0.0; // facet normal z coordinate
  38235. var length = 0.0; // facet normal length before normalization
  38236. var v1x = 0; // vector1 x index in the positions array
  38237. var v1y = 0; // vector1 y index in the positions array
  38238. var v1z = 0; // vector1 z index in the positions array
  38239. var v2x = 0; // vector2 x index in the positions array
  38240. var v2y = 0; // vector2 y index in the positions array
  38241. var v2z = 0; // vector2 z index in the positions array
  38242. var v3x = 0; // vector3 x index in the positions array
  38243. var v3y = 0; // vector3 y index in the positions array
  38244. var v3z = 0; // vector3 z index in the positions array
  38245. var computeFacetNormals = false;
  38246. var computeFacetPositions = false;
  38247. var computeFacetPartitioning = false;
  38248. var computeDepthSort = false;
  38249. var faceNormalSign = 1;
  38250. var ratio = 0;
  38251. var distanceTo = null;
  38252. if (options) {
  38253. computeFacetNormals = (options.facetNormals) ? true : false;
  38254. computeFacetPositions = (options.facetPositions) ? true : false;
  38255. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38256. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38257. ratio = options.ratio || 0;
  38258. computeDepthSort = (options.depthSort) ? true : false;
  38259. distanceTo = (options.distanceTo);
  38260. if (computeDepthSort) {
  38261. if (distanceTo === undefined) {
  38262. distanceTo = BABYLON.Vector3.Zero();
  38263. }
  38264. var depthSortedFacets = options.depthSortedFacets;
  38265. }
  38266. }
  38267. // facetPartitioning reinit if needed
  38268. var xSubRatio = 0;
  38269. var ySubRatio = 0;
  38270. var zSubRatio = 0;
  38271. var subSq = 0;
  38272. if (computeFacetPartitioning && options && options.bbSize) {
  38273. var ox = 0; // X partitioning index for facet position
  38274. var oy = 0; // Y partinioning index for facet position
  38275. var oz = 0; // Z partinioning index for facet position
  38276. var b1x = 0; // X partitioning index for facet v1 vertex
  38277. var b1y = 0; // Y partitioning index for facet v1 vertex
  38278. var b1z = 0; // z partitioning index for facet v1 vertex
  38279. var b2x = 0; // X partitioning index for facet v2 vertex
  38280. var b2y = 0; // Y partitioning index for facet v2 vertex
  38281. var b2z = 0; // Z partitioning index for facet v2 vertex
  38282. var b3x = 0; // X partitioning index for facet v3 vertex
  38283. var b3y = 0; // Y partitioning index for facet v3 vertex
  38284. var b3z = 0; // Z partitioning index for facet v3 vertex
  38285. var block_idx_o = 0; // facet barycenter block index
  38286. var block_idx_v1 = 0; // v1 vertex block index
  38287. var block_idx_v2 = 0; // v2 vertex block index
  38288. var block_idx_v3 = 0; // v3 vertex block index
  38289. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38290. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38291. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38292. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38293. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38294. subSq = options.subDiv.max * options.subDiv.max;
  38295. options.facetPartitioning.length = 0;
  38296. }
  38297. // reset the normals
  38298. for (index = 0; index < positions.length; index++) {
  38299. normals[index] = 0.0;
  38300. }
  38301. // Loop : 1 indice triplet = 1 facet
  38302. var nbFaces = (indices.length / 3) | 0;
  38303. for (index = 0; index < nbFaces; index++) {
  38304. // get the indexes of the coordinates of each vertex of the facet
  38305. v1x = indices[index * 3] * 3;
  38306. v1y = v1x + 1;
  38307. v1z = v1x + 2;
  38308. v2x = indices[index * 3 + 1] * 3;
  38309. v2y = v2x + 1;
  38310. v2z = v2x + 2;
  38311. v3x = indices[index * 3 + 2] * 3;
  38312. v3y = v3x + 1;
  38313. v3z = v3x + 2;
  38314. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38315. p1p2y = positions[v1y] - positions[v2y];
  38316. p1p2z = positions[v1z] - positions[v2z];
  38317. p3p2x = positions[v3x] - positions[v2x];
  38318. p3p2y = positions[v3y] - positions[v2y];
  38319. p3p2z = positions[v3z] - positions[v2z];
  38320. // compute the face normal with the cross product
  38321. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38322. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38323. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38324. // normalize this normal and store it in the array facetData
  38325. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38326. length = (length === 0) ? 1.0 : length;
  38327. faceNormalx /= length;
  38328. faceNormaly /= length;
  38329. faceNormalz /= length;
  38330. if (computeFacetNormals && options) {
  38331. options.facetNormals[index].x = faceNormalx;
  38332. options.facetNormals[index].y = faceNormaly;
  38333. options.facetNormals[index].z = faceNormalz;
  38334. }
  38335. if (computeFacetPositions && options) {
  38336. // compute and the facet barycenter coordinates in the array facetPositions
  38337. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38338. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38339. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38340. }
  38341. if (computeFacetPartitioning && options) {
  38342. // store the facet indexes in arrays in the main facetPartitioning array :
  38343. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38344. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38345. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38346. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38347. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38348. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38349. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38350. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38351. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38352. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38353. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38354. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38355. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38356. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38357. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38358. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38359. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38360. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38361. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38362. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38363. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38364. // push each facet index in each block containing the vertex
  38365. options.facetPartitioning[block_idx_v1].push(index);
  38366. if (block_idx_v2 != block_idx_v1) {
  38367. options.facetPartitioning[block_idx_v2].push(index);
  38368. }
  38369. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38370. options.facetPartitioning[block_idx_v3].push(index);
  38371. }
  38372. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38373. options.facetPartitioning[block_idx_o].push(index);
  38374. }
  38375. }
  38376. if (computeDepthSort && options && options.facetPositions) {
  38377. var dsf = depthSortedFacets[index];
  38378. dsf.ind = index * 3;
  38379. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38380. }
  38381. // compute the normals anyway
  38382. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38383. normals[v1y] += faceNormaly;
  38384. normals[v1z] += faceNormalz;
  38385. normals[v2x] += faceNormalx;
  38386. normals[v2y] += faceNormaly;
  38387. normals[v2z] += faceNormalz;
  38388. normals[v3x] += faceNormalx;
  38389. normals[v3y] += faceNormaly;
  38390. normals[v3z] += faceNormalz;
  38391. }
  38392. // last normalization of each normal
  38393. for (index = 0; index < normals.length / 3; index++) {
  38394. faceNormalx = normals[index * 3];
  38395. faceNormaly = normals[index * 3 + 1];
  38396. faceNormalz = normals[index * 3 + 2];
  38397. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38398. length = (length === 0) ? 1.0 : length;
  38399. faceNormalx /= length;
  38400. faceNormaly /= length;
  38401. faceNormalz /= length;
  38402. normals[index * 3] = faceNormalx;
  38403. normals[index * 3 + 1] = faceNormaly;
  38404. normals[index * 3 + 2] = faceNormalz;
  38405. }
  38406. };
  38407. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38408. var li = indices.length;
  38409. var ln = normals.length;
  38410. var i;
  38411. var n;
  38412. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38413. switch (sideOrientation) {
  38414. case BABYLON.Mesh.FRONTSIDE:
  38415. // nothing changed
  38416. break;
  38417. case BABYLON.Mesh.BACKSIDE:
  38418. var tmp;
  38419. // indices
  38420. for (i = 0; i < li; i += 3) {
  38421. tmp = indices[i];
  38422. indices[i] = indices[i + 2];
  38423. indices[i + 2] = tmp;
  38424. }
  38425. // normals
  38426. for (n = 0; n < ln; n++) {
  38427. normals[n] = -normals[n];
  38428. }
  38429. break;
  38430. case BABYLON.Mesh.DOUBLESIDE:
  38431. // positions
  38432. var lp = positions.length;
  38433. var l = lp / 3;
  38434. for (var p = 0; p < lp; p++) {
  38435. positions[lp + p] = positions[p];
  38436. }
  38437. // indices
  38438. for (i = 0; i < li; i += 3) {
  38439. indices[i + li] = indices[i + 2] + l;
  38440. indices[i + 1 + li] = indices[i + 1] + l;
  38441. indices[i + 2 + li] = indices[i] + l;
  38442. }
  38443. // normals
  38444. for (n = 0; n < ln; n++) {
  38445. normals[ln + n] = -normals[n];
  38446. }
  38447. // uvs
  38448. var lu = uvs.length;
  38449. var u = 0;
  38450. for (u = 0; u < lu; u++) {
  38451. uvs[u + lu] = uvs[u];
  38452. }
  38453. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38454. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38455. u = 0;
  38456. for (i = 0; i < lu / 2; i++) {
  38457. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38458. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38459. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38460. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38461. u += 2;
  38462. }
  38463. break;
  38464. }
  38465. };
  38466. /**
  38467. * Applies VertexData created from the imported parameters to the geometry
  38468. * @param parsedVertexData the parsed data from an imported file
  38469. * @param geometry the geometry to apply the VertexData to
  38470. */
  38471. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38472. var vertexData = new VertexData();
  38473. // positions
  38474. var positions = parsedVertexData.positions;
  38475. if (positions) {
  38476. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38477. }
  38478. // normals
  38479. var normals = parsedVertexData.normals;
  38480. if (normals) {
  38481. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38482. }
  38483. // tangents
  38484. var tangents = parsedVertexData.tangents;
  38485. if (tangents) {
  38486. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38487. }
  38488. // uvs
  38489. var uvs = parsedVertexData.uvs;
  38490. if (uvs) {
  38491. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38492. }
  38493. // uv2s
  38494. var uv2s = parsedVertexData.uv2s;
  38495. if (uv2s) {
  38496. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38497. }
  38498. // uv3s
  38499. var uv3s = parsedVertexData.uv3s;
  38500. if (uv3s) {
  38501. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38502. }
  38503. // uv4s
  38504. var uv4s = parsedVertexData.uv4s;
  38505. if (uv4s) {
  38506. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38507. }
  38508. // uv5s
  38509. var uv5s = parsedVertexData.uv5s;
  38510. if (uv5s) {
  38511. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38512. }
  38513. // uv6s
  38514. var uv6s = parsedVertexData.uv6s;
  38515. if (uv6s) {
  38516. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38517. }
  38518. // colors
  38519. var colors = parsedVertexData.colors;
  38520. if (colors) {
  38521. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38522. }
  38523. // matricesIndices
  38524. var matricesIndices = parsedVertexData.matricesIndices;
  38525. if (matricesIndices) {
  38526. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38527. }
  38528. // matricesWeights
  38529. var matricesWeights = parsedVertexData.matricesWeights;
  38530. if (matricesWeights) {
  38531. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38532. }
  38533. // indices
  38534. var indices = parsedVertexData.indices;
  38535. if (indices) {
  38536. vertexData.indices = indices;
  38537. }
  38538. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38539. };
  38540. return VertexData;
  38541. }());
  38542. BABYLON.VertexData = VertexData;
  38543. })(BABYLON || (BABYLON = {}));
  38544. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38545. var BABYLON;
  38546. (function (BABYLON) {
  38547. /**
  38548. * Class used to store geometry data (vertex buffers + index buffer)
  38549. */
  38550. var Geometry = /** @class */ (function () {
  38551. /**
  38552. * Creates a new geometry
  38553. * @param id defines the unique ID
  38554. * @param scene defines the hosting scene
  38555. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38556. * @param updatable defines if geometry must be updatable (false by default)
  38557. * @param mesh defines the mesh that will be associated with the geometry
  38558. */
  38559. function Geometry(id, scene, vertexData, updatable, mesh) {
  38560. if (updatable === void 0) { updatable = false; }
  38561. if (mesh === void 0) { mesh = null; }
  38562. /**
  38563. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38564. */
  38565. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38566. this._totalVertices = 0;
  38567. this._isDisposed = false;
  38568. this._indexBufferIsUpdatable = false;
  38569. this.id = id;
  38570. this._engine = scene.getEngine();
  38571. this._meshes = [];
  38572. this._scene = scene;
  38573. //Init vertex buffer cache
  38574. this._vertexBuffers = {};
  38575. this._indices = [];
  38576. this._updatable = updatable;
  38577. // vertexData
  38578. if (vertexData) {
  38579. this.setAllVerticesData(vertexData, updatable);
  38580. }
  38581. else {
  38582. this._totalVertices = 0;
  38583. this._indices = [];
  38584. }
  38585. if (this._engine.getCaps().vertexArrayObject) {
  38586. this._vertexArrayObjects = {};
  38587. }
  38588. // applyToMesh
  38589. if (mesh) {
  38590. if (mesh.getClassName() === "LinesMesh") {
  38591. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38592. this._updateExtend();
  38593. }
  38594. this.applyToMesh(mesh);
  38595. mesh.computeWorldMatrix(true);
  38596. }
  38597. }
  38598. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38599. /**
  38600. * 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
  38601. */
  38602. get: function () {
  38603. return this._boundingBias;
  38604. },
  38605. /**
  38606. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  38607. */
  38608. set: function (value) {
  38609. if (this._boundingBias && this._boundingBias.equals(value)) {
  38610. return;
  38611. }
  38612. this._boundingBias = value.clone();
  38613. this._updateBoundingInfo(true, null);
  38614. },
  38615. enumerable: true,
  38616. configurable: true
  38617. });
  38618. /**
  38619. * Static function used to attach a new empty geometry to a mesh
  38620. * @param mesh defines the mesh to attach the geometry to
  38621. * @returns the new {BABYLON.Geometry}
  38622. */
  38623. Geometry.CreateGeometryForMesh = function (mesh) {
  38624. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38625. geometry.applyToMesh(mesh);
  38626. return geometry;
  38627. };
  38628. Object.defineProperty(Geometry.prototype, "extend", {
  38629. /**
  38630. * Gets the current extend of the geometry
  38631. */
  38632. get: function () {
  38633. return this._extend;
  38634. },
  38635. enumerable: true,
  38636. configurable: true
  38637. });
  38638. /**
  38639. * Gets the hosting scene
  38640. * @returns the hosting {BABYLON.Scene}
  38641. */
  38642. Geometry.prototype.getScene = function () {
  38643. return this._scene;
  38644. };
  38645. /**
  38646. * Gets the hosting engine
  38647. * @returns the hosting {BABYLON.Engine}
  38648. */
  38649. Geometry.prototype.getEngine = function () {
  38650. return this._engine;
  38651. };
  38652. /**
  38653. * Defines if the geometry is ready to use
  38654. * @returns true if the geometry is ready to be used
  38655. */
  38656. Geometry.prototype.isReady = function () {
  38657. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38658. };
  38659. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38660. /**
  38661. * Gets a value indicating that the geometry should not be serialized
  38662. */
  38663. get: function () {
  38664. for (var index = 0; index < this._meshes.length; index++) {
  38665. if (!this._meshes[index].doNotSerialize) {
  38666. return false;
  38667. }
  38668. }
  38669. return true;
  38670. },
  38671. enumerable: true,
  38672. configurable: true
  38673. });
  38674. /** @hidden */
  38675. Geometry.prototype._rebuild = function () {
  38676. if (this._vertexArrayObjects) {
  38677. this._vertexArrayObjects = {};
  38678. }
  38679. // Index buffer
  38680. if (this._meshes.length !== 0 && this._indices) {
  38681. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38682. }
  38683. // Vertex buffers
  38684. for (var key in this._vertexBuffers) {
  38685. var vertexBuffer = this._vertexBuffers[key];
  38686. vertexBuffer._rebuild();
  38687. }
  38688. };
  38689. /**
  38690. * Affects all geometry data in one call
  38691. * @param vertexData defines the geometry data
  38692. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38693. */
  38694. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38695. vertexData.applyToGeometry(this, updatable);
  38696. this.notifyUpdate();
  38697. };
  38698. /**
  38699. * Set specific vertex data
  38700. * @param kind defines the data kind (Position, normal, etc...)
  38701. * @param data defines the vertex data to use
  38702. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38703. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38704. */
  38705. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38706. if (updatable === void 0) { updatable = false; }
  38707. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38708. this.setVerticesBuffer(buffer);
  38709. };
  38710. /**
  38711. * Removes a specific vertex data
  38712. * @param kind defines the data kind (Position, normal, etc...)
  38713. */
  38714. Geometry.prototype.removeVerticesData = function (kind) {
  38715. if (this._vertexBuffers[kind]) {
  38716. this._vertexBuffers[kind].dispose();
  38717. delete this._vertexBuffers[kind];
  38718. }
  38719. };
  38720. /**
  38721. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38722. * @param buffer defines the vertex buffer to use
  38723. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38724. */
  38725. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38726. if (totalVertices === void 0) { totalVertices = null; }
  38727. var kind = buffer.getKind();
  38728. if (this._vertexBuffers[kind]) {
  38729. this._vertexBuffers[kind].dispose();
  38730. }
  38731. this._vertexBuffers[kind] = buffer;
  38732. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38733. var data = buffer.getData();
  38734. if (totalVertices != null) {
  38735. this._totalVertices = totalVertices;
  38736. }
  38737. else {
  38738. if (data != null) {
  38739. this._totalVertices = data.length / (buffer.byteStride / 4);
  38740. }
  38741. }
  38742. this._updateExtend(data);
  38743. this._resetPointsArrayCache();
  38744. var meshes = this._meshes;
  38745. var numOfMeshes = meshes.length;
  38746. for (var index = 0; index < numOfMeshes; index++) {
  38747. var mesh = meshes[index];
  38748. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38749. mesh._createGlobalSubMesh(false);
  38750. mesh.computeWorldMatrix(true);
  38751. }
  38752. }
  38753. this.notifyUpdate(kind);
  38754. if (this._vertexArrayObjects) {
  38755. this._disposeVertexArrayObjects();
  38756. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38757. }
  38758. };
  38759. /**
  38760. * Update a specific vertex buffer
  38761. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38762. * It will do nothing if the buffer is not updatable
  38763. * @param kind defines the data kind (Position, normal, etc...)
  38764. * @param data defines the data to use
  38765. * @param offset defines the offset in the target buffer where to store the data
  38766. * @param useBytes set to true if the offset is in bytes
  38767. */
  38768. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38769. if (useBytes === void 0) { useBytes = false; }
  38770. var vertexBuffer = this.getVertexBuffer(kind);
  38771. if (!vertexBuffer) {
  38772. return;
  38773. }
  38774. vertexBuffer.updateDirectly(data, offset, useBytes);
  38775. this.notifyUpdate(kind);
  38776. };
  38777. /**
  38778. * Update a specific vertex buffer
  38779. * This function will create a new buffer if the current one is not updatable
  38780. * @param kind defines the data kind (Position, normal, etc...)
  38781. * @param data defines the data to use
  38782. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38783. */
  38784. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38785. if (updateExtends === void 0) { updateExtends = false; }
  38786. var vertexBuffer = this.getVertexBuffer(kind);
  38787. if (!vertexBuffer) {
  38788. return;
  38789. }
  38790. vertexBuffer.update(data);
  38791. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38792. this._updateBoundingInfo(updateExtends, data);
  38793. }
  38794. this.notifyUpdate(kind);
  38795. };
  38796. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38797. if (updateExtends) {
  38798. this._updateExtend(data);
  38799. }
  38800. var meshes = this._meshes;
  38801. var numOfMeshes = meshes.length;
  38802. this._resetPointsArrayCache();
  38803. for (var index = 0; index < numOfMeshes; index++) {
  38804. var mesh = meshes[index];
  38805. if (updateExtends) {
  38806. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38807. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38808. var subMesh = mesh.subMeshes[subIndex];
  38809. subMesh.refreshBoundingInfo();
  38810. }
  38811. }
  38812. }
  38813. };
  38814. /** @hidden */
  38815. Geometry.prototype._bind = function (effect, indexToBind) {
  38816. if (!effect) {
  38817. return;
  38818. }
  38819. if (indexToBind === undefined) {
  38820. indexToBind = this._indexBuffer;
  38821. }
  38822. var vbs = this.getVertexBuffers();
  38823. if (!vbs) {
  38824. return;
  38825. }
  38826. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38827. this._engine.bindBuffers(vbs, indexToBind, effect);
  38828. return;
  38829. }
  38830. // Using VAO
  38831. if (!this._vertexArrayObjects[effect.key]) {
  38832. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38833. }
  38834. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38835. };
  38836. /**
  38837. * Gets total number of vertices
  38838. * @returns the total number of vertices
  38839. */
  38840. Geometry.prototype.getTotalVertices = function () {
  38841. if (!this.isReady()) {
  38842. return 0;
  38843. }
  38844. return this._totalVertices;
  38845. };
  38846. /**
  38847. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38848. * @param kind defines the data kind (Position, normal, etc...)
  38849. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38850. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38851. * @returns a float array containing vertex data
  38852. */
  38853. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38854. var vertexBuffer = this.getVertexBuffer(kind);
  38855. if (!vertexBuffer) {
  38856. return null;
  38857. }
  38858. var data = vertexBuffer.getData();
  38859. if (!data) {
  38860. return null;
  38861. }
  38862. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38863. var count = this._totalVertices * vertexBuffer.getSize();
  38864. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38865. var copy_1 = new Array(count);
  38866. vertexBuffer.forEach(count, function (value, index) {
  38867. copy_1[index] = value;
  38868. });
  38869. return copy_1;
  38870. }
  38871. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38872. if (data instanceof Array) {
  38873. var offset = vertexBuffer.byteOffset / 4;
  38874. return BABYLON.Tools.Slice(data, offset, offset + count);
  38875. }
  38876. else if (data instanceof ArrayBuffer) {
  38877. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38878. }
  38879. else {
  38880. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38881. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38882. var result = new Float32Array(count);
  38883. var source = new Float32Array(data.buffer, offset, count);
  38884. result.set(source);
  38885. return result;
  38886. }
  38887. return new Float32Array(data.buffer, offset, count);
  38888. }
  38889. }
  38890. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38891. return BABYLON.Tools.Slice(data);
  38892. }
  38893. return data;
  38894. };
  38895. /**
  38896. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38897. * @param kind defines the data kind (Position, normal, etc...)
  38898. * @returns true if the vertex buffer with the specified kind is updatable
  38899. */
  38900. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38901. var vb = this._vertexBuffers[kind];
  38902. if (!vb) {
  38903. return false;
  38904. }
  38905. return vb.isUpdatable();
  38906. };
  38907. /**
  38908. * Gets a specific vertex buffer
  38909. * @param kind defines the data kind (Position, normal, etc...)
  38910. * @returns a {BABYLON.VertexBuffer}
  38911. */
  38912. Geometry.prototype.getVertexBuffer = function (kind) {
  38913. if (!this.isReady()) {
  38914. return null;
  38915. }
  38916. return this._vertexBuffers[kind];
  38917. };
  38918. /**
  38919. * Returns all vertex buffers
  38920. * @return an object holding all vertex buffers indexed by kind
  38921. */
  38922. Geometry.prototype.getVertexBuffers = function () {
  38923. if (!this.isReady()) {
  38924. return null;
  38925. }
  38926. return this._vertexBuffers;
  38927. };
  38928. /**
  38929. * Gets a boolean indicating if specific vertex buffer is present
  38930. * @param kind defines the data kind (Position, normal, etc...)
  38931. * @returns true if data is present
  38932. */
  38933. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38934. if (!this._vertexBuffers) {
  38935. if (this._delayInfo) {
  38936. return this._delayInfo.indexOf(kind) !== -1;
  38937. }
  38938. return false;
  38939. }
  38940. return this._vertexBuffers[kind] !== undefined;
  38941. };
  38942. /**
  38943. * Gets a list of all attached data kinds (Position, normal, etc...)
  38944. * @returns a list of string containing all kinds
  38945. */
  38946. Geometry.prototype.getVerticesDataKinds = function () {
  38947. var result = [];
  38948. var kind;
  38949. if (!this._vertexBuffers && this._delayInfo) {
  38950. for (kind in this._delayInfo) {
  38951. result.push(kind);
  38952. }
  38953. }
  38954. else {
  38955. for (kind in this._vertexBuffers) {
  38956. result.push(kind);
  38957. }
  38958. }
  38959. return result;
  38960. };
  38961. /**
  38962. * Update index buffer
  38963. * @param indices defines the indices to store in the index buffer
  38964. * @param offset defines the offset in the target buffer where to store the data
  38965. */
  38966. Geometry.prototype.updateIndices = function (indices, offset) {
  38967. if (!this._indexBuffer) {
  38968. return;
  38969. }
  38970. if (!this._indexBufferIsUpdatable) {
  38971. this.setIndices(indices, null, true);
  38972. }
  38973. else {
  38974. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38975. }
  38976. };
  38977. /**
  38978. * Creates a new index buffer
  38979. * @param indices defines the indices to store in the index buffer
  38980. * @param totalVertices defines the total number of vertices (could be null)
  38981. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38982. */
  38983. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38984. if (totalVertices === void 0) { totalVertices = null; }
  38985. if (updatable === void 0) { updatable = false; }
  38986. if (this._indexBuffer) {
  38987. this._engine._releaseBuffer(this._indexBuffer);
  38988. }
  38989. this._disposeVertexArrayObjects();
  38990. this._indices = indices;
  38991. this._indexBufferIsUpdatable = updatable;
  38992. if (this._meshes.length !== 0 && this._indices) {
  38993. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38994. }
  38995. if (totalVertices != undefined) { // including null and undefined
  38996. this._totalVertices = totalVertices;
  38997. }
  38998. var meshes = this._meshes;
  38999. var numOfMeshes = meshes.length;
  39000. for (var index = 0; index < numOfMeshes; index++) {
  39001. meshes[index]._createGlobalSubMesh(true);
  39002. }
  39003. this.notifyUpdate();
  39004. };
  39005. /**
  39006. * Return the total number of indices
  39007. * @returns the total number of indices
  39008. */
  39009. Geometry.prototype.getTotalIndices = function () {
  39010. if (!this.isReady()) {
  39011. return 0;
  39012. }
  39013. return this._indices.length;
  39014. };
  39015. /**
  39016. * Gets the index buffer array
  39017. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39018. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39019. * @returns the index buffer array
  39020. */
  39021. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39022. if (!this.isReady()) {
  39023. return null;
  39024. }
  39025. var orig = this._indices;
  39026. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39027. return orig;
  39028. }
  39029. else {
  39030. var len = orig.length;
  39031. var copy = [];
  39032. for (var i = 0; i < len; i++) {
  39033. copy.push(orig[i]);
  39034. }
  39035. return copy;
  39036. }
  39037. };
  39038. /**
  39039. * Gets the index buffer
  39040. * @return the index buffer
  39041. */
  39042. Geometry.prototype.getIndexBuffer = function () {
  39043. if (!this.isReady()) {
  39044. return null;
  39045. }
  39046. return this._indexBuffer;
  39047. };
  39048. /** @hidden */
  39049. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39050. if (effect === void 0) { effect = null; }
  39051. if (!effect || !this._vertexArrayObjects) {
  39052. return;
  39053. }
  39054. if (this._vertexArrayObjects[effect.key]) {
  39055. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39056. delete this._vertexArrayObjects[effect.key];
  39057. }
  39058. };
  39059. /**
  39060. * Release the associated resources for a specific mesh
  39061. * @param mesh defines the source mesh
  39062. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39063. */
  39064. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39065. var meshes = this._meshes;
  39066. var index = meshes.indexOf(mesh);
  39067. if (index === -1) {
  39068. return;
  39069. }
  39070. meshes.splice(index, 1);
  39071. mesh._geometry = null;
  39072. if (meshes.length === 0 && shouldDispose) {
  39073. this.dispose();
  39074. }
  39075. };
  39076. /**
  39077. * Apply current geometry to a given mesh
  39078. * @param mesh defines the mesh to apply geometry to
  39079. */
  39080. Geometry.prototype.applyToMesh = function (mesh) {
  39081. if (mesh._geometry === this) {
  39082. return;
  39083. }
  39084. var previousGeometry = mesh._geometry;
  39085. if (previousGeometry) {
  39086. previousGeometry.releaseForMesh(mesh);
  39087. }
  39088. var meshes = this._meshes;
  39089. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39090. mesh._geometry = this;
  39091. this._scene.pushGeometry(this);
  39092. meshes.push(mesh);
  39093. if (this.isReady()) {
  39094. this._applyToMesh(mesh);
  39095. }
  39096. else {
  39097. mesh._boundingInfo = this._boundingInfo;
  39098. }
  39099. };
  39100. Geometry.prototype._updateExtend = function (data) {
  39101. if (data === void 0) { data = null; }
  39102. if (!data) {
  39103. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39104. }
  39105. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39106. };
  39107. Geometry.prototype._applyToMesh = function (mesh) {
  39108. var numOfMeshes = this._meshes.length;
  39109. // vertexBuffers
  39110. for (var kind in this._vertexBuffers) {
  39111. if (numOfMeshes === 1) {
  39112. this._vertexBuffers[kind].create();
  39113. }
  39114. var buffer = this._vertexBuffers[kind].getBuffer();
  39115. if (buffer)
  39116. buffer.references = numOfMeshes;
  39117. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39118. if (!this._extend) {
  39119. this._updateExtend();
  39120. }
  39121. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39122. mesh._createGlobalSubMesh(false);
  39123. //bounding info was just created again, world matrix should be applied again.
  39124. mesh._updateBoundingInfo();
  39125. }
  39126. }
  39127. // indexBuffer
  39128. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39129. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39130. }
  39131. if (this._indexBuffer) {
  39132. this._indexBuffer.references = numOfMeshes;
  39133. }
  39134. };
  39135. Geometry.prototype.notifyUpdate = function (kind) {
  39136. if (this.onGeometryUpdated) {
  39137. this.onGeometryUpdated(this, kind);
  39138. }
  39139. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39140. var mesh = _a[_i];
  39141. mesh._markSubMeshesAsAttributesDirty();
  39142. }
  39143. };
  39144. /**
  39145. * Load the geometry if it was flagged as delay loaded
  39146. * @param scene defines the hosting scene
  39147. * @param onLoaded defines a callback called when the geometry is loaded
  39148. */
  39149. Geometry.prototype.load = function (scene, onLoaded) {
  39150. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39151. return;
  39152. }
  39153. if (this.isReady()) {
  39154. if (onLoaded) {
  39155. onLoaded();
  39156. }
  39157. return;
  39158. }
  39159. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39160. this._queueLoad(scene, onLoaded);
  39161. };
  39162. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39163. var _this = this;
  39164. if (!this.delayLoadingFile) {
  39165. return;
  39166. }
  39167. scene._addPendingData(this);
  39168. scene._loadFile(this.delayLoadingFile, function (data) {
  39169. if (!_this._delayLoadingFunction) {
  39170. return;
  39171. }
  39172. _this._delayLoadingFunction(JSON.parse(data), _this);
  39173. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39174. _this._delayInfo = [];
  39175. scene._removePendingData(_this);
  39176. var meshes = _this._meshes;
  39177. var numOfMeshes = meshes.length;
  39178. for (var index = 0; index < numOfMeshes; index++) {
  39179. _this._applyToMesh(meshes[index]);
  39180. }
  39181. if (onLoaded) {
  39182. onLoaded();
  39183. }
  39184. }, undefined, true);
  39185. };
  39186. /**
  39187. * Invert the geometry to move from a right handed system to a left handed one.
  39188. */
  39189. Geometry.prototype.toLeftHanded = function () {
  39190. // Flip faces
  39191. var tIndices = this.getIndices(false);
  39192. if (tIndices != null && tIndices.length > 0) {
  39193. for (var i = 0; i < tIndices.length; i += 3) {
  39194. var tTemp = tIndices[i + 0];
  39195. tIndices[i + 0] = tIndices[i + 2];
  39196. tIndices[i + 2] = tTemp;
  39197. }
  39198. this.setIndices(tIndices);
  39199. }
  39200. // Negate position.z
  39201. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39202. if (tPositions != null && tPositions.length > 0) {
  39203. for (var i = 0; i < tPositions.length; i += 3) {
  39204. tPositions[i + 2] = -tPositions[i + 2];
  39205. }
  39206. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39207. }
  39208. // Negate normal.z
  39209. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39210. if (tNormals != null && tNormals.length > 0) {
  39211. for (var i = 0; i < tNormals.length; i += 3) {
  39212. tNormals[i + 2] = -tNormals[i + 2];
  39213. }
  39214. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39215. }
  39216. };
  39217. // Cache
  39218. /** @hidden */
  39219. Geometry.prototype._resetPointsArrayCache = function () {
  39220. this._positions = null;
  39221. };
  39222. /** @hidden */
  39223. Geometry.prototype._generatePointsArray = function () {
  39224. if (this._positions)
  39225. return true;
  39226. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39227. if (!data || data.length === 0) {
  39228. return false;
  39229. }
  39230. this._positions = [];
  39231. for (var index = 0; index < data.length; index += 3) {
  39232. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39233. }
  39234. return true;
  39235. };
  39236. /**
  39237. * Gets a value indicating if the geometry is disposed
  39238. * @returns true if the geometry was disposed
  39239. */
  39240. Geometry.prototype.isDisposed = function () {
  39241. return this._isDisposed;
  39242. };
  39243. Geometry.prototype._disposeVertexArrayObjects = function () {
  39244. if (this._vertexArrayObjects) {
  39245. for (var kind in this._vertexArrayObjects) {
  39246. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39247. }
  39248. this._vertexArrayObjects = {};
  39249. }
  39250. };
  39251. /**
  39252. * Free all associated resources
  39253. */
  39254. Geometry.prototype.dispose = function () {
  39255. var meshes = this._meshes;
  39256. var numOfMeshes = meshes.length;
  39257. var index;
  39258. for (index = 0; index < numOfMeshes; index++) {
  39259. this.releaseForMesh(meshes[index]);
  39260. }
  39261. this._meshes = [];
  39262. this._disposeVertexArrayObjects();
  39263. for (var kind in this._vertexBuffers) {
  39264. this._vertexBuffers[kind].dispose();
  39265. }
  39266. this._vertexBuffers = {};
  39267. this._totalVertices = 0;
  39268. if (this._indexBuffer) {
  39269. this._engine._releaseBuffer(this._indexBuffer);
  39270. }
  39271. this._indexBuffer = null;
  39272. this._indices = [];
  39273. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39274. this.delayLoadingFile = null;
  39275. this._delayLoadingFunction = null;
  39276. this._delayInfo = [];
  39277. this._boundingInfo = null;
  39278. this._scene.removeGeometry(this);
  39279. this._isDisposed = true;
  39280. };
  39281. /**
  39282. * Clone the current geometry into a new geometry
  39283. * @param id defines the unique ID of the new geometry
  39284. * @returns a new geometry object
  39285. */
  39286. Geometry.prototype.copy = function (id) {
  39287. var vertexData = new BABYLON.VertexData();
  39288. vertexData.indices = [];
  39289. var indices = this.getIndices();
  39290. if (indices) {
  39291. for (var index = 0; index < indices.length; index++) {
  39292. vertexData.indices.push(indices[index]);
  39293. }
  39294. }
  39295. var updatable = false;
  39296. var stopChecking = false;
  39297. var kind;
  39298. for (kind in this._vertexBuffers) {
  39299. // using slice() to make a copy of the array and not just reference it
  39300. var data = this.getVerticesData(kind);
  39301. if (data instanceof Float32Array) {
  39302. vertexData.set(new Float32Array(data), kind);
  39303. }
  39304. else {
  39305. vertexData.set(data.slice(0), kind);
  39306. }
  39307. if (!stopChecking) {
  39308. var vb = this.getVertexBuffer(kind);
  39309. if (vb) {
  39310. updatable = vb.isUpdatable();
  39311. stopChecking = !updatable;
  39312. }
  39313. }
  39314. }
  39315. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39316. geometry.delayLoadState = this.delayLoadState;
  39317. geometry.delayLoadingFile = this.delayLoadingFile;
  39318. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39319. for (kind in this._delayInfo) {
  39320. geometry._delayInfo = geometry._delayInfo || [];
  39321. geometry._delayInfo.push(kind);
  39322. }
  39323. // Bounding info
  39324. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39325. return geometry;
  39326. };
  39327. /**
  39328. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39329. * @return a JSON representation of the current geometry data (without the vertices data)
  39330. */
  39331. Geometry.prototype.serialize = function () {
  39332. var serializationObject = {};
  39333. serializationObject.id = this.id;
  39334. serializationObject.updatable = this._updatable;
  39335. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39336. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39337. }
  39338. return serializationObject;
  39339. };
  39340. Geometry.prototype.toNumberArray = function (origin) {
  39341. if (Array.isArray(origin)) {
  39342. return origin;
  39343. }
  39344. else {
  39345. return Array.prototype.slice.call(origin);
  39346. }
  39347. };
  39348. /**
  39349. * Serialize all vertices data into a JSON oject
  39350. * @returns a JSON representation of the current geometry data
  39351. */
  39352. Geometry.prototype.serializeVerticeData = function () {
  39353. var serializationObject = this.serialize();
  39354. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39355. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39356. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39357. serializationObject.positions._updatable = true;
  39358. }
  39359. }
  39360. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39361. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39362. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39363. serializationObject.normals._updatable = true;
  39364. }
  39365. }
  39366. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39367. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39368. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39369. serializationObject.tangets._updatable = true;
  39370. }
  39371. }
  39372. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39373. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39374. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39375. serializationObject.uvs._updatable = true;
  39376. }
  39377. }
  39378. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39379. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39380. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39381. serializationObject.uv2s._updatable = true;
  39382. }
  39383. }
  39384. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39385. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39386. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39387. serializationObject.uv3s._updatable = true;
  39388. }
  39389. }
  39390. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39391. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39392. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39393. serializationObject.uv4s._updatable = true;
  39394. }
  39395. }
  39396. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39397. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39398. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39399. serializationObject.uv5s._updatable = true;
  39400. }
  39401. }
  39402. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39403. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39404. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39405. serializationObject.uv6s._updatable = true;
  39406. }
  39407. }
  39408. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39409. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39410. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39411. serializationObject.colors._updatable = true;
  39412. }
  39413. }
  39414. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39415. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39416. serializationObject.matricesIndices._isExpanded = true;
  39417. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39418. serializationObject.matricesIndices._updatable = true;
  39419. }
  39420. }
  39421. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39422. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39423. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39424. serializationObject.matricesWeights._updatable = true;
  39425. }
  39426. }
  39427. serializationObject.indices = this.toNumberArray(this.getIndices());
  39428. return serializationObject;
  39429. };
  39430. // Statics
  39431. /**
  39432. * Extracts a clone of a mesh geometry
  39433. * @param mesh defines the source mesh
  39434. * @param id defines the unique ID of the new geometry object
  39435. * @returns the new geometry object
  39436. */
  39437. Geometry.ExtractFromMesh = function (mesh, id) {
  39438. var geometry = mesh._geometry;
  39439. if (!geometry) {
  39440. return null;
  39441. }
  39442. return geometry.copy(id);
  39443. };
  39444. /**
  39445. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39446. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39447. * Be aware Math.random() could cause collisions, but:
  39448. * "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"
  39449. * @returns a string containing a new GUID
  39450. */
  39451. Geometry.RandomId = function () {
  39452. return BABYLON.Tools.RandomId();
  39453. };
  39454. /** @hidden */
  39455. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39456. var scene = mesh.getScene();
  39457. // Geometry
  39458. var geometryId = parsedGeometry.geometryId;
  39459. if (geometryId) {
  39460. var geometry = scene.getGeometryByID(geometryId);
  39461. if (geometry) {
  39462. geometry.applyToMesh(mesh);
  39463. }
  39464. }
  39465. else if (parsedGeometry instanceof ArrayBuffer) {
  39466. var binaryInfo = mesh._binaryInfo;
  39467. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39468. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39469. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39470. }
  39471. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39472. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39473. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39474. }
  39475. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39476. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39477. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39478. }
  39479. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39480. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39481. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39482. }
  39483. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39484. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39485. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39486. }
  39487. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39488. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39489. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39490. }
  39491. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39492. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39493. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39494. }
  39495. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39496. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39497. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39498. }
  39499. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39500. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39501. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39502. }
  39503. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39504. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39505. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39506. }
  39507. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39508. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39509. var floatIndices = [];
  39510. for (var i = 0; i < matricesIndicesData.length; i++) {
  39511. var index = matricesIndicesData[i];
  39512. floatIndices.push(index & 0x000000FF);
  39513. floatIndices.push((index & 0x0000FF00) >> 8);
  39514. floatIndices.push((index & 0x00FF0000) >> 16);
  39515. floatIndices.push(index >> 24);
  39516. }
  39517. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39518. }
  39519. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39520. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39521. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39522. }
  39523. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39524. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39525. mesh.setIndices(indicesData, null);
  39526. }
  39527. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39528. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39529. mesh.subMeshes = [];
  39530. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39531. var materialIndex = subMeshesData[(i * 5) + 0];
  39532. var verticesStart = subMeshesData[(i * 5) + 1];
  39533. var verticesCount = subMeshesData[(i * 5) + 2];
  39534. var indexStart = subMeshesData[(i * 5) + 3];
  39535. var indexCount = subMeshesData[(i * 5) + 4];
  39536. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39537. }
  39538. }
  39539. }
  39540. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39541. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39542. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39543. if (parsedGeometry.tangents) {
  39544. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39545. }
  39546. if (parsedGeometry.uvs) {
  39547. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39548. }
  39549. if (parsedGeometry.uvs2) {
  39550. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39551. }
  39552. if (parsedGeometry.uvs3) {
  39553. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39554. }
  39555. if (parsedGeometry.uvs4) {
  39556. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39557. }
  39558. if (parsedGeometry.uvs5) {
  39559. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39560. }
  39561. if (parsedGeometry.uvs6) {
  39562. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39563. }
  39564. if (parsedGeometry.colors) {
  39565. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39566. }
  39567. if (parsedGeometry.matricesIndices) {
  39568. if (!parsedGeometry.matricesIndices._isExpanded) {
  39569. var floatIndices = [];
  39570. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39571. var matricesIndex = parsedGeometry.matricesIndices[i];
  39572. floatIndices.push(matricesIndex & 0x000000FF);
  39573. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39574. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39575. floatIndices.push(matricesIndex >> 24);
  39576. }
  39577. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39578. }
  39579. else {
  39580. delete parsedGeometry.matricesIndices._isExpanded;
  39581. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39582. }
  39583. }
  39584. if (parsedGeometry.matricesIndicesExtra) {
  39585. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39586. var floatIndices = [];
  39587. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39588. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39589. floatIndices.push(matricesIndex & 0x000000FF);
  39590. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39591. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39592. floatIndices.push(matricesIndex >> 24);
  39593. }
  39594. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39595. }
  39596. else {
  39597. delete parsedGeometry.matricesIndices._isExpanded;
  39598. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39599. }
  39600. }
  39601. if (parsedGeometry.matricesWeights) {
  39602. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39603. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39604. }
  39605. if (parsedGeometry.matricesWeightsExtra) {
  39606. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39607. }
  39608. mesh.setIndices(parsedGeometry.indices, null);
  39609. }
  39610. // SubMeshes
  39611. if (parsedGeometry.subMeshes) {
  39612. mesh.subMeshes = [];
  39613. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39614. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39615. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39616. }
  39617. }
  39618. // Flat shading
  39619. if (mesh._shouldGenerateFlatShading) {
  39620. mesh.convertToFlatShadedMesh();
  39621. delete mesh._shouldGenerateFlatShading;
  39622. }
  39623. // Update
  39624. mesh.computeWorldMatrix(true);
  39625. scene.onMeshImportedObservable.notifyObservers(mesh);
  39626. };
  39627. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39628. var epsilon = 1e-3;
  39629. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39630. return;
  39631. }
  39632. var noInfluenceBoneIndex = 0.0;
  39633. if (parsedGeometry.skeletonId > -1) {
  39634. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39635. if (!skeleton) {
  39636. return;
  39637. }
  39638. noInfluenceBoneIndex = skeleton.bones.length;
  39639. }
  39640. else {
  39641. return;
  39642. }
  39643. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39644. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39645. var matricesWeights = parsedGeometry.matricesWeights;
  39646. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39647. var influencers = parsedGeometry.numBoneInfluencer;
  39648. var size = matricesWeights.length;
  39649. for (var i = 0; i < size; i += 4) {
  39650. var weight = 0.0;
  39651. var firstZeroWeight = -1;
  39652. for (var j = 0; j < 4; j++) {
  39653. var w = matricesWeights[i + j];
  39654. weight += w;
  39655. if (w < epsilon && firstZeroWeight < 0) {
  39656. firstZeroWeight = j;
  39657. }
  39658. }
  39659. if (matricesWeightsExtra) {
  39660. for (var j = 0; j < 4; j++) {
  39661. var w = matricesWeightsExtra[i + j];
  39662. weight += w;
  39663. if (w < epsilon && firstZeroWeight < 0) {
  39664. firstZeroWeight = j + 4;
  39665. }
  39666. }
  39667. }
  39668. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39669. firstZeroWeight = influencers - 1;
  39670. }
  39671. if (weight > epsilon) {
  39672. var mweight = 1.0 / weight;
  39673. for (var j = 0; j < 4; j++) {
  39674. matricesWeights[i + j] *= mweight;
  39675. }
  39676. if (matricesWeightsExtra) {
  39677. for (var j = 0; j < 4; j++) {
  39678. matricesWeightsExtra[i + j] *= mweight;
  39679. }
  39680. }
  39681. }
  39682. else {
  39683. if (firstZeroWeight >= 4) {
  39684. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39685. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39686. }
  39687. else {
  39688. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39689. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39690. }
  39691. }
  39692. }
  39693. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39694. if (parsedGeometry.matricesWeightsExtra) {
  39695. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39696. }
  39697. };
  39698. /**
  39699. * Create a new geometry from persisted data (Using .babylon file format)
  39700. * @param parsedVertexData defines the persisted data
  39701. * @param scene defines the hosting scene
  39702. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39703. * @returns the new geometry object
  39704. */
  39705. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39706. if (scene.getGeometryByID(parsedVertexData.id)) {
  39707. return null; // null since geometry could be something else than a box...
  39708. }
  39709. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39710. if (BABYLON.Tags) {
  39711. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39712. }
  39713. if (parsedVertexData.delayLoadingFile) {
  39714. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39715. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39716. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39717. geometry._delayInfo = [];
  39718. if (parsedVertexData.hasUVs) {
  39719. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39720. }
  39721. if (parsedVertexData.hasUVs2) {
  39722. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39723. }
  39724. if (parsedVertexData.hasUVs3) {
  39725. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39726. }
  39727. if (parsedVertexData.hasUVs4) {
  39728. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39729. }
  39730. if (parsedVertexData.hasUVs5) {
  39731. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39732. }
  39733. if (parsedVertexData.hasUVs6) {
  39734. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39735. }
  39736. if (parsedVertexData.hasColors) {
  39737. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39738. }
  39739. if (parsedVertexData.hasMatricesIndices) {
  39740. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39741. }
  39742. if (parsedVertexData.hasMatricesWeights) {
  39743. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39744. }
  39745. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39746. }
  39747. else {
  39748. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39749. }
  39750. scene.pushGeometry(geometry, true);
  39751. return geometry;
  39752. };
  39753. return Geometry;
  39754. }());
  39755. BABYLON.Geometry = Geometry;
  39756. // Primitives
  39757. /// Abstract class
  39758. /**
  39759. * Abstract class used to provide common services for all typed geometries
  39760. * @hidden
  39761. */
  39762. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39763. __extends(_PrimitiveGeometry, _super);
  39764. /**
  39765. * Creates a new typed geometry
  39766. * @param id defines the unique ID of the geometry
  39767. * @param scene defines the hosting scene
  39768. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39769. * @param mesh defines the hosting mesh (can be null)
  39770. */
  39771. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39772. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39773. if (mesh === void 0) { mesh = null; }
  39774. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39775. _this._canBeRegenerated = _canBeRegenerated;
  39776. _this._beingRegenerated = true;
  39777. _this.regenerate();
  39778. _this._beingRegenerated = false;
  39779. return _this;
  39780. }
  39781. /**
  39782. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39783. * @returns true if the geometry can be regenerated
  39784. */
  39785. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39786. return this._canBeRegenerated;
  39787. };
  39788. /**
  39789. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39790. */
  39791. _PrimitiveGeometry.prototype.regenerate = function () {
  39792. if (!this._canBeRegenerated) {
  39793. return;
  39794. }
  39795. this._beingRegenerated = true;
  39796. this.setAllVerticesData(this._regenerateVertexData(), false);
  39797. this._beingRegenerated = false;
  39798. };
  39799. /**
  39800. * Clone the geometry
  39801. * @param id defines the unique ID of the new geometry
  39802. * @returns the new geometry
  39803. */
  39804. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39805. return _super.prototype.copy.call(this, id);
  39806. };
  39807. // overrides
  39808. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39809. if (!this._beingRegenerated) {
  39810. return;
  39811. }
  39812. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39813. };
  39814. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39815. if (!this._beingRegenerated) {
  39816. return;
  39817. }
  39818. _super.prototype.setVerticesData.call(this, kind, data, false);
  39819. };
  39820. // to override
  39821. /** @hidden */
  39822. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39823. throw new Error("Abstract method");
  39824. };
  39825. _PrimitiveGeometry.prototype.copy = function (id) {
  39826. throw new Error("Must be overriden in sub-classes.");
  39827. };
  39828. _PrimitiveGeometry.prototype.serialize = function () {
  39829. var serializationObject = _super.prototype.serialize.call(this);
  39830. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39831. return serializationObject;
  39832. };
  39833. return _PrimitiveGeometry;
  39834. }(Geometry));
  39835. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39836. /**
  39837. * Creates a ribbon geometry
  39838. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39839. */
  39840. var RibbonGeometry = /** @class */ (function (_super) {
  39841. __extends(RibbonGeometry, _super);
  39842. /**
  39843. * Creates a ribbon geometry
  39844. * @param id defines the unique ID of the geometry
  39845. * @param scene defines the hosting scene
  39846. * @param pathArray defines the array of paths to use
  39847. * @param closeArray defines if the last path and the first path must be joined
  39848. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39849. * @param offset defines the offset between points
  39850. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39851. * @param mesh defines the hosting mesh (can be null)
  39852. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39853. */
  39854. function RibbonGeometry(id, scene,
  39855. /**
  39856. * Defines the array of paths to use
  39857. */
  39858. pathArray,
  39859. /**
  39860. * Defines if the last and first points of each path in your pathArray must be joined
  39861. */
  39862. closeArray,
  39863. /**
  39864. * Defines if the last and first points of each path in your pathArray must be joined
  39865. */
  39866. closePath,
  39867. /**
  39868. * Defines the offset between points
  39869. */
  39870. offset, canBeRegenerated, mesh,
  39871. /**
  39872. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39873. */
  39874. side) {
  39875. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39876. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39877. _this.pathArray = pathArray;
  39878. _this.closeArray = closeArray;
  39879. _this.closePath = closePath;
  39880. _this.offset = offset;
  39881. _this.side = side;
  39882. return _this;
  39883. }
  39884. /** @hidden */
  39885. RibbonGeometry.prototype._regenerateVertexData = function () {
  39886. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39887. };
  39888. RibbonGeometry.prototype.copy = function (id) {
  39889. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39890. };
  39891. return RibbonGeometry;
  39892. }(_PrimitiveGeometry));
  39893. BABYLON.RibbonGeometry = RibbonGeometry;
  39894. /**
  39895. * Creates a box geometry
  39896. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39897. */
  39898. var BoxGeometry = /** @class */ (function (_super) {
  39899. __extends(BoxGeometry, _super);
  39900. /**
  39901. * Creates a box geometry
  39902. * @param id defines the unique ID of the geometry
  39903. * @param scene defines the hosting scene
  39904. * @param size defines the zise of the box (width, height and depth are the same)
  39905. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39906. * @param mesh defines the hosting mesh (can be null)
  39907. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39908. */
  39909. function BoxGeometry(id, scene,
  39910. /**
  39911. * Defines the zise of the box (width, height and depth are the same)
  39912. */
  39913. size, canBeRegenerated, mesh,
  39914. /**
  39915. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39916. */
  39917. side) {
  39918. if (mesh === void 0) { mesh = null; }
  39919. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39920. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39921. _this.size = size;
  39922. _this.side = side;
  39923. return _this;
  39924. }
  39925. /** @hidden */
  39926. BoxGeometry.prototype._regenerateVertexData = function () {
  39927. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39928. };
  39929. BoxGeometry.prototype.copy = function (id) {
  39930. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39931. };
  39932. BoxGeometry.prototype.serialize = function () {
  39933. var serializationObject = _super.prototype.serialize.call(this);
  39934. serializationObject.size = this.size;
  39935. return serializationObject;
  39936. };
  39937. BoxGeometry.Parse = function (parsedBox, scene) {
  39938. if (scene.getGeometryByID(parsedBox.id)) {
  39939. return null; // null since geometry could be something else than a box...
  39940. }
  39941. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39942. if (BABYLON.Tags) {
  39943. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39944. }
  39945. scene.pushGeometry(box, true);
  39946. return box;
  39947. };
  39948. return BoxGeometry;
  39949. }(_PrimitiveGeometry));
  39950. BABYLON.BoxGeometry = BoxGeometry;
  39951. /**
  39952. * Creates a sphere geometry
  39953. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39954. */
  39955. var SphereGeometry = /** @class */ (function (_super) {
  39956. __extends(SphereGeometry, _super);
  39957. /**
  39958. * Create a new sphere geometry
  39959. * @param id defines the unique ID of the geometry
  39960. * @param scene defines the hosting scene
  39961. * @param segments defines the number of segments to use to create the sphere
  39962. * @param diameter defines the diameter of the sphere
  39963. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39964. * @param mesh defines the hosting mesh (can be null)
  39965. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39966. */
  39967. function SphereGeometry(id, scene,
  39968. /**
  39969. * Defines the number of segments to use to create the sphere
  39970. */
  39971. segments,
  39972. /**
  39973. * Defines the diameter of the sphere
  39974. */
  39975. diameter, canBeRegenerated, mesh,
  39976. /**
  39977. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39978. */
  39979. side) {
  39980. if (mesh === void 0) { mesh = null; }
  39981. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39982. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39983. _this.segments = segments;
  39984. _this.diameter = diameter;
  39985. _this.side = side;
  39986. return _this;
  39987. }
  39988. /** @hidden */
  39989. SphereGeometry.prototype._regenerateVertexData = function () {
  39990. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39991. };
  39992. SphereGeometry.prototype.copy = function (id) {
  39993. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39994. };
  39995. SphereGeometry.prototype.serialize = function () {
  39996. var serializationObject = _super.prototype.serialize.call(this);
  39997. serializationObject.segments = this.segments;
  39998. serializationObject.diameter = this.diameter;
  39999. return serializationObject;
  40000. };
  40001. SphereGeometry.Parse = function (parsedSphere, scene) {
  40002. if (scene.getGeometryByID(parsedSphere.id)) {
  40003. return null; // null since geometry could be something else than a sphere...
  40004. }
  40005. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40006. if (BABYLON.Tags) {
  40007. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40008. }
  40009. scene.pushGeometry(sphere, true);
  40010. return sphere;
  40011. };
  40012. return SphereGeometry;
  40013. }(_PrimitiveGeometry));
  40014. BABYLON.SphereGeometry = SphereGeometry;
  40015. /**
  40016. * Creates a disc geometry
  40017. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40018. */
  40019. var DiscGeometry = /** @class */ (function (_super) {
  40020. __extends(DiscGeometry, _super);
  40021. /**
  40022. * Creates a new disc geometry
  40023. * @param id defines the unique ID of the geometry
  40024. * @param scene defines the hosting scene
  40025. * @param radius defines the radius of the disc
  40026. * @param tessellation defines the tesselation factor to apply to the disc
  40027. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40028. * @param mesh defines the hosting mesh (can be null)
  40029. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40030. */
  40031. function DiscGeometry(id, scene,
  40032. /**
  40033. * Defines the radius of the disc
  40034. */
  40035. radius,
  40036. /**
  40037. * Defines the tesselation factor to apply to the disc
  40038. */
  40039. tessellation, canBeRegenerated, mesh,
  40040. /**
  40041. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40042. */
  40043. side) {
  40044. if (mesh === void 0) { mesh = null; }
  40045. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40046. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40047. _this.radius = radius;
  40048. _this.tessellation = tessellation;
  40049. _this.side = side;
  40050. return _this;
  40051. }
  40052. /** @hidden */
  40053. DiscGeometry.prototype._regenerateVertexData = function () {
  40054. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40055. };
  40056. DiscGeometry.prototype.copy = function (id) {
  40057. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40058. };
  40059. return DiscGeometry;
  40060. }(_PrimitiveGeometry));
  40061. BABYLON.DiscGeometry = DiscGeometry;
  40062. /**
  40063. * Creates a new cylinder geometry
  40064. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40065. */
  40066. var CylinderGeometry = /** @class */ (function (_super) {
  40067. __extends(CylinderGeometry, _super);
  40068. /**
  40069. * Creates a new cylinder geometry
  40070. * @param id defines the unique ID of the geometry
  40071. * @param scene defines the hosting scene
  40072. * @param height defines the height of the cylinder
  40073. * @param diameterTop defines the diameter of the cylinder's top cap
  40074. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40075. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40076. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40077. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40078. * @param mesh defines the hosting mesh (can be null)
  40079. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40080. */
  40081. function CylinderGeometry(id, scene,
  40082. /**
  40083. * Defines the height of the cylinder
  40084. */
  40085. height,
  40086. /**
  40087. * Defines the diameter of the cylinder's top cap
  40088. */
  40089. diameterTop,
  40090. /**
  40091. * Defines the diameter of the cylinder's bottom cap
  40092. */
  40093. diameterBottom,
  40094. /**
  40095. * Defines the tessellation factor to apply to the cylinder
  40096. */
  40097. tessellation,
  40098. /**
  40099. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40100. */
  40101. subdivisions, canBeRegenerated, mesh,
  40102. /**
  40103. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40104. */
  40105. side) {
  40106. if (subdivisions === void 0) { subdivisions = 1; }
  40107. if (mesh === void 0) { mesh = null; }
  40108. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40109. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40110. _this.height = height;
  40111. _this.diameterTop = diameterTop;
  40112. _this.diameterBottom = diameterBottom;
  40113. _this.tessellation = tessellation;
  40114. _this.subdivisions = subdivisions;
  40115. _this.side = side;
  40116. return _this;
  40117. }
  40118. /** @hidden */
  40119. CylinderGeometry.prototype._regenerateVertexData = function () {
  40120. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40121. };
  40122. CylinderGeometry.prototype.copy = function (id) {
  40123. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40124. };
  40125. CylinderGeometry.prototype.serialize = function () {
  40126. var serializationObject = _super.prototype.serialize.call(this);
  40127. serializationObject.height = this.height;
  40128. serializationObject.diameterTop = this.diameterTop;
  40129. serializationObject.diameterBottom = this.diameterBottom;
  40130. serializationObject.tessellation = this.tessellation;
  40131. return serializationObject;
  40132. };
  40133. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40134. if (scene.getGeometryByID(parsedCylinder.id)) {
  40135. return null; // null since geometry could be something else than a cylinder...
  40136. }
  40137. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40138. if (BABYLON.Tags) {
  40139. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40140. }
  40141. scene.pushGeometry(cylinder, true);
  40142. return cylinder;
  40143. };
  40144. return CylinderGeometry;
  40145. }(_PrimitiveGeometry));
  40146. BABYLON.CylinderGeometry = CylinderGeometry;
  40147. /**
  40148. * Creates a new torus geometry
  40149. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40150. */
  40151. var TorusGeometry = /** @class */ (function (_super) {
  40152. __extends(TorusGeometry, _super);
  40153. /**
  40154. * Creates a new torus geometry
  40155. * @param id defines the unique ID of the geometry
  40156. * @param scene defines the hosting scene
  40157. * @param diameter defines the diameter of the torus
  40158. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40159. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40160. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40161. * @param mesh defines the hosting mesh (can be null)
  40162. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40163. */
  40164. function TorusGeometry(id, scene,
  40165. /**
  40166. * Defines the diameter of the torus
  40167. */
  40168. diameter,
  40169. /**
  40170. * Defines the thickness of the torus (ie. internal diameter)
  40171. */
  40172. thickness,
  40173. /**
  40174. * Defines the tesselation factor to apply to the torus
  40175. */
  40176. tessellation, canBeRegenerated, mesh,
  40177. /**
  40178. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40179. */
  40180. side) {
  40181. if (mesh === void 0) { mesh = null; }
  40182. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40183. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40184. _this.diameter = diameter;
  40185. _this.thickness = thickness;
  40186. _this.tessellation = tessellation;
  40187. _this.side = side;
  40188. return _this;
  40189. }
  40190. /** @hidden */
  40191. TorusGeometry.prototype._regenerateVertexData = function () {
  40192. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40193. };
  40194. TorusGeometry.prototype.copy = function (id) {
  40195. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40196. };
  40197. TorusGeometry.prototype.serialize = function () {
  40198. var serializationObject = _super.prototype.serialize.call(this);
  40199. serializationObject.diameter = this.diameter;
  40200. serializationObject.thickness = this.thickness;
  40201. serializationObject.tessellation = this.tessellation;
  40202. return serializationObject;
  40203. };
  40204. TorusGeometry.Parse = function (parsedTorus, scene) {
  40205. if (scene.getGeometryByID(parsedTorus.id)) {
  40206. return null; // null since geometry could be something else than a torus...
  40207. }
  40208. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40209. if (BABYLON.Tags) {
  40210. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40211. }
  40212. scene.pushGeometry(torus, true);
  40213. return torus;
  40214. };
  40215. return TorusGeometry;
  40216. }(_PrimitiveGeometry));
  40217. BABYLON.TorusGeometry = TorusGeometry;
  40218. /**
  40219. * Creates a new ground geometry
  40220. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40221. */
  40222. var GroundGeometry = /** @class */ (function (_super) {
  40223. __extends(GroundGeometry, _super);
  40224. /**
  40225. * Creates a new ground geometry
  40226. * @param id defines the unique ID of the geometry
  40227. * @param scene defines the hosting scene
  40228. * @param width defines the width of the ground
  40229. * @param height defines the height of the ground
  40230. * @param subdivisions defines the subdivisions to apply to the ground
  40231. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40232. * @param mesh defines the hosting mesh (can be null)
  40233. */
  40234. function GroundGeometry(id, scene,
  40235. /**
  40236. * Defines the width of the ground
  40237. */
  40238. width,
  40239. /**
  40240. * Defines the height of the ground
  40241. */
  40242. height,
  40243. /**
  40244. * Defines the subdivisions to apply to the ground
  40245. */
  40246. subdivisions, canBeRegenerated, mesh) {
  40247. if (mesh === void 0) { mesh = null; }
  40248. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40249. _this.width = width;
  40250. _this.height = height;
  40251. _this.subdivisions = subdivisions;
  40252. return _this;
  40253. }
  40254. /** @hidden */
  40255. GroundGeometry.prototype._regenerateVertexData = function () {
  40256. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40257. };
  40258. GroundGeometry.prototype.copy = function (id) {
  40259. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40260. };
  40261. GroundGeometry.prototype.serialize = function () {
  40262. var serializationObject = _super.prototype.serialize.call(this);
  40263. serializationObject.width = this.width;
  40264. serializationObject.height = this.height;
  40265. serializationObject.subdivisions = this.subdivisions;
  40266. return serializationObject;
  40267. };
  40268. GroundGeometry.Parse = function (parsedGround, scene) {
  40269. if (scene.getGeometryByID(parsedGround.id)) {
  40270. return null; // null since geometry could be something else than a ground...
  40271. }
  40272. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40273. if (BABYLON.Tags) {
  40274. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40275. }
  40276. scene.pushGeometry(ground, true);
  40277. return ground;
  40278. };
  40279. return GroundGeometry;
  40280. }(_PrimitiveGeometry));
  40281. BABYLON.GroundGeometry = GroundGeometry;
  40282. /**
  40283. * Creates a tiled ground geometry
  40284. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40285. */
  40286. var TiledGroundGeometry = /** @class */ (function (_super) {
  40287. __extends(TiledGroundGeometry, _super);
  40288. /**
  40289. * Creates a tiled ground geometry
  40290. * @param id defines the unique ID of the geometry
  40291. * @param scene defines the hosting scene
  40292. * @param xmin defines the minimum value on X axis
  40293. * @param zmin defines the minimum value on Z axis
  40294. * @param xmax defines the maximum value on X axis
  40295. * @param zmax defines the maximum value on Z axis
  40296. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40297. * @param precision defines the precision to use when computing the tiles
  40298. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40299. * @param mesh defines the hosting mesh (can be null)
  40300. */
  40301. function TiledGroundGeometry(id, scene,
  40302. /**
  40303. * Defines the minimum value on X axis
  40304. */
  40305. xmin,
  40306. /**
  40307. * Defines the minimum value on Z axis
  40308. */
  40309. zmin,
  40310. /**
  40311. * Defines the maximum value on X axis
  40312. */
  40313. xmax,
  40314. /**
  40315. * Defines the maximum value on Z axis
  40316. */
  40317. zmax,
  40318. /**
  40319. * Defines the subdivisions to apply to the ground
  40320. */
  40321. subdivisions,
  40322. /**
  40323. * Defines the precision to use when computing the tiles
  40324. */
  40325. precision, canBeRegenerated, mesh) {
  40326. if (mesh === void 0) { mesh = null; }
  40327. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40328. _this.xmin = xmin;
  40329. _this.zmin = zmin;
  40330. _this.xmax = xmax;
  40331. _this.zmax = zmax;
  40332. _this.subdivisions = subdivisions;
  40333. _this.precision = precision;
  40334. return _this;
  40335. }
  40336. /** @hidden */
  40337. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40338. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40339. };
  40340. TiledGroundGeometry.prototype.copy = function (id) {
  40341. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40342. };
  40343. return TiledGroundGeometry;
  40344. }(_PrimitiveGeometry));
  40345. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40346. /**
  40347. * Creates a plane geometry
  40348. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40349. */
  40350. var PlaneGeometry = /** @class */ (function (_super) {
  40351. __extends(PlaneGeometry, _super);
  40352. /**
  40353. * Creates a plane geometry
  40354. * @param id defines the unique ID of the geometry
  40355. * @param scene defines the hosting scene
  40356. * @param size defines the size of the plane (width === height)
  40357. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40358. * @param mesh defines the hosting mesh (can be null)
  40359. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40360. */
  40361. function PlaneGeometry(id, scene,
  40362. /**
  40363. * Defines the size of the plane (width === height)
  40364. */
  40365. size, canBeRegenerated, mesh,
  40366. /**
  40367. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40368. */
  40369. side) {
  40370. if (mesh === void 0) { mesh = null; }
  40371. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40372. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40373. _this.size = size;
  40374. _this.side = side;
  40375. return _this;
  40376. }
  40377. /** @hidden */
  40378. PlaneGeometry.prototype._regenerateVertexData = function () {
  40379. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40380. };
  40381. PlaneGeometry.prototype.copy = function (id) {
  40382. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40383. };
  40384. PlaneGeometry.prototype.serialize = function () {
  40385. var serializationObject = _super.prototype.serialize.call(this);
  40386. serializationObject.size = this.size;
  40387. return serializationObject;
  40388. };
  40389. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40390. if (scene.getGeometryByID(parsedPlane.id)) {
  40391. return null; // null since geometry could be something else than a ground...
  40392. }
  40393. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40394. if (BABYLON.Tags) {
  40395. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40396. }
  40397. scene.pushGeometry(plane, true);
  40398. return plane;
  40399. };
  40400. return PlaneGeometry;
  40401. }(_PrimitiveGeometry));
  40402. BABYLON.PlaneGeometry = PlaneGeometry;
  40403. /**
  40404. * Creates a torus knot geometry
  40405. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40406. */
  40407. var TorusKnotGeometry = /** @class */ (function (_super) {
  40408. __extends(TorusKnotGeometry, _super);
  40409. /**
  40410. * Creates a torus knot geometry
  40411. * @param id defines the unique ID of the geometry
  40412. * @param scene defines the hosting scene
  40413. * @param radius defines the radius of the torus knot
  40414. * @param tube defines the thickness of the torus knot tube
  40415. * @param radialSegments defines the number of radial segments
  40416. * @param tubularSegments defines the number of tubular segments
  40417. * @param p defines the first number of windings
  40418. * @param q defines the second number of windings
  40419. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40420. * @param mesh defines the hosting mesh (can be null)
  40421. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40422. */
  40423. function TorusKnotGeometry(id, scene,
  40424. /**
  40425. * Defines the radius of the torus knot
  40426. */
  40427. radius,
  40428. /**
  40429. * Defines the thickness of the torus knot tube
  40430. */
  40431. tube,
  40432. /**
  40433. * Defines the number of radial segments
  40434. */
  40435. radialSegments,
  40436. /**
  40437. * Defines the number of tubular segments
  40438. */
  40439. tubularSegments,
  40440. /**
  40441. * Defines the first number of windings
  40442. */
  40443. p,
  40444. /**
  40445. * Defines the second number of windings
  40446. */
  40447. q, canBeRegenerated, mesh,
  40448. /**
  40449. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40450. */
  40451. side) {
  40452. if (mesh === void 0) { mesh = null; }
  40453. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40454. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40455. _this.radius = radius;
  40456. _this.tube = tube;
  40457. _this.radialSegments = radialSegments;
  40458. _this.tubularSegments = tubularSegments;
  40459. _this.p = p;
  40460. _this.q = q;
  40461. _this.side = side;
  40462. return _this;
  40463. }
  40464. /** @hidden */
  40465. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40466. 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 });
  40467. };
  40468. TorusKnotGeometry.prototype.copy = function (id) {
  40469. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40470. };
  40471. TorusKnotGeometry.prototype.serialize = function () {
  40472. var serializationObject = _super.prototype.serialize.call(this);
  40473. serializationObject.radius = this.radius;
  40474. serializationObject.tube = this.tube;
  40475. serializationObject.radialSegments = this.radialSegments;
  40476. serializationObject.tubularSegments = this.tubularSegments;
  40477. serializationObject.p = this.p;
  40478. serializationObject.q = this.q;
  40479. return serializationObject;
  40480. };
  40481. ;
  40482. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40483. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40484. return null; // null since geometry could be something else than a ground...
  40485. }
  40486. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40487. if (BABYLON.Tags) {
  40488. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40489. }
  40490. scene.pushGeometry(torusKnot, true);
  40491. return torusKnot;
  40492. };
  40493. return TorusKnotGeometry;
  40494. }(_PrimitiveGeometry));
  40495. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40496. //}
  40497. })(BABYLON || (BABYLON = {}));
  40498. //# sourceMappingURL=babylon.geometry.js.map
  40499. var BABYLON;
  40500. (function (BABYLON) {
  40501. /**
  40502. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40503. */
  40504. var PerformanceMonitor = /** @class */ (function () {
  40505. /**
  40506. * constructor
  40507. * @param frameSampleSize The number of samples required to saturate the sliding window
  40508. */
  40509. function PerformanceMonitor(frameSampleSize) {
  40510. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40511. this._enabled = true;
  40512. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40513. }
  40514. /**
  40515. * Samples current frame
  40516. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40517. */
  40518. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40519. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40520. if (!this._enabled)
  40521. return;
  40522. if (this._lastFrameTimeMs != null) {
  40523. var dt = timeMs - this._lastFrameTimeMs;
  40524. this._rollingFrameTime.add(dt);
  40525. }
  40526. this._lastFrameTimeMs = timeMs;
  40527. };
  40528. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40529. /**
  40530. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40531. * @return Average frame time in milliseconds
  40532. */
  40533. get: function () {
  40534. return this._rollingFrameTime.average;
  40535. },
  40536. enumerable: true,
  40537. configurable: true
  40538. });
  40539. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40540. /**
  40541. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40542. * @return Frame time variance in milliseconds squared
  40543. */
  40544. get: function () {
  40545. return this._rollingFrameTime.variance;
  40546. },
  40547. enumerable: true,
  40548. configurable: true
  40549. });
  40550. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40551. /**
  40552. * Returns the frame time of the most recent frame
  40553. * @return Frame time in milliseconds
  40554. */
  40555. get: function () {
  40556. return this._rollingFrameTime.history(0);
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40562. /**
  40563. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40564. * @return Framerate in frames per second
  40565. */
  40566. get: function () {
  40567. return 1000.0 / this._rollingFrameTime.average;
  40568. },
  40569. enumerable: true,
  40570. configurable: true
  40571. });
  40572. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40573. /**
  40574. * Returns the average framerate in frames per second using the most recent frame time
  40575. * @return Framerate in frames per second
  40576. */
  40577. get: function () {
  40578. var history = this._rollingFrameTime.history(0);
  40579. if (history === 0) {
  40580. return 0;
  40581. }
  40582. return 1000.0 / history;
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40588. /**
  40589. * Returns true if enough samples have been taken to completely fill the sliding window
  40590. * @return true if saturated
  40591. */
  40592. get: function () {
  40593. return this._rollingFrameTime.isSaturated();
  40594. },
  40595. enumerable: true,
  40596. configurable: true
  40597. });
  40598. /**
  40599. * Enables contributions to the sliding window sample set
  40600. */
  40601. PerformanceMonitor.prototype.enable = function () {
  40602. this._enabled = true;
  40603. };
  40604. /**
  40605. * Disables contributions to the sliding window sample set
  40606. * Samples will not be interpolated over the disabled period
  40607. */
  40608. PerformanceMonitor.prototype.disable = function () {
  40609. this._enabled = false;
  40610. //clear last sample to avoid interpolating over the disabled period when next enabled
  40611. this._lastFrameTimeMs = null;
  40612. };
  40613. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40614. /**
  40615. * Returns true if sampling is enabled
  40616. * @return true if enabled
  40617. */
  40618. get: function () {
  40619. return this._enabled;
  40620. },
  40621. enumerable: true,
  40622. configurable: true
  40623. });
  40624. /**
  40625. * Resets performance monitor
  40626. */
  40627. PerformanceMonitor.prototype.reset = function () {
  40628. //clear last sample to avoid interpolating over the disabled period when next enabled
  40629. this._lastFrameTimeMs = null;
  40630. //wipe record
  40631. this._rollingFrameTime.reset();
  40632. };
  40633. return PerformanceMonitor;
  40634. }());
  40635. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40636. /**
  40637. * RollingAverage
  40638. *
  40639. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40640. */
  40641. var RollingAverage = /** @class */ (function () {
  40642. /**
  40643. * constructor
  40644. * @param length The number of samples required to saturate the sliding window
  40645. */
  40646. function RollingAverage(length) {
  40647. this._samples = new Array(length);
  40648. this.reset();
  40649. }
  40650. /**
  40651. * Adds a sample to the sample set
  40652. * @param v The sample value
  40653. */
  40654. RollingAverage.prototype.add = function (v) {
  40655. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40656. var delta;
  40657. //we need to check if we've already wrapped round
  40658. if (this.isSaturated()) {
  40659. //remove bottom of stack from mean
  40660. var bottomValue = this._samples[this._pos];
  40661. delta = bottomValue - this.average;
  40662. this.average -= delta / (this._sampleCount - 1);
  40663. this._m2 -= delta * (bottomValue - this.average);
  40664. }
  40665. else {
  40666. this._sampleCount++;
  40667. }
  40668. //add new value to mean
  40669. delta = v - this.average;
  40670. this.average += delta / (this._sampleCount);
  40671. this._m2 += delta * (v - this.average);
  40672. //set the new variance
  40673. this.variance = this._m2 / (this._sampleCount - 1);
  40674. this._samples[this._pos] = v;
  40675. this._pos++;
  40676. this._pos %= this._samples.length; //positive wrap around
  40677. };
  40678. /**
  40679. * Returns previously added values or null if outside of history or outside the sliding window domain
  40680. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40681. * @return Value previously recorded with add() or null if outside of range
  40682. */
  40683. RollingAverage.prototype.history = function (i) {
  40684. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40685. return 0;
  40686. }
  40687. var i0 = this._wrapPosition(this._pos - 1.0);
  40688. return this._samples[this._wrapPosition(i0 - i)];
  40689. };
  40690. /**
  40691. * Returns true if enough samples have been taken to completely fill the sliding window
  40692. * @return true if sample-set saturated
  40693. */
  40694. RollingAverage.prototype.isSaturated = function () {
  40695. return this._sampleCount >= this._samples.length;
  40696. };
  40697. /**
  40698. * Resets the rolling average (equivalent to 0 samples taken so far)
  40699. */
  40700. RollingAverage.prototype.reset = function () {
  40701. this.average = 0;
  40702. this.variance = 0;
  40703. this._sampleCount = 0;
  40704. this._pos = 0;
  40705. this._m2 = 0;
  40706. };
  40707. /**
  40708. * Wraps a value around the sample range boundaries
  40709. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40710. * @return Wrapped position in sample range
  40711. */
  40712. RollingAverage.prototype._wrapPosition = function (i) {
  40713. var max = this._samples.length;
  40714. return ((i % max) + max) % max;
  40715. };
  40716. return RollingAverage;
  40717. }());
  40718. BABYLON.RollingAverage = RollingAverage;
  40719. })(BABYLON || (BABYLON = {}));
  40720. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40721. var BABYLON;
  40722. (function (BABYLON) {
  40723. /**
  40724. * "Static Class" containing the most commonly used helper while dealing with material for
  40725. * rendering purpose.
  40726. *
  40727. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40728. *
  40729. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40730. */
  40731. var MaterialHelper = /** @class */ (function () {
  40732. function MaterialHelper() {
  40733. }
  40734. /**
  40735. * Bind the current view position to an effect.
  40736. * @param effect The effect to be bound
  40737. * @param scene The scene the eyes position is used from
  40738. */
  40739. MaterialHelper.BindEyePosition = function (effect, scene) {
  40740. if (scene._forcedViewPosition) {
  40741. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40742. return;
  40743. }
  40744. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40745. };
  40746. /**
  40747. * Helps preparing the defines values about the UVs in used in the effect.
  40748. * UVs are shared as much as we can accross chanels in the shaders.
  40749. * @param texture The texture we are preparing the UVs for
  40750. * @param defines The defines to update
  40751. * @param key The chanel key "diffuse", "specular"... used in the shader
  40752. */
  40753. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40754. defines._needUVs = true;
  40755. defines[key] = true;
  40756. if (texture.getTextureMatrix().isIdentity(true)) {
  40757. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40758. if (texture.coordinatesIndex === 0) {
  40759. defines["MAINUV1"] = true;
  40760. }
  40761. else {
  40762. defines["MAINUV2"] = true;
  40763. }
  40764. }
  40765. else {
  40766. defines[key + "DIRECTUV"] = 0;
  40767. }
  40768. };
  40769. /**
  40770. * Binds a texture matrix value to its corrsponding uniform
  40771. * @param texture The texture to bind the matrix for
  40772. * @param uniformBuffer The uniform buffer receivin the data
  40773. * @param key The chanel key "diffuse", "specular"... used in the shader
  40774. */
  40775. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40776. var matrix = texture.getTextureMatrix();
  40777. if (!matrix.isIdentity(true)) {
  40778. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40779. }
  40780. };
  40781. /**
  40782. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40783. * @param mesh defines the current mesh
  40784. * @param scene defines the current scene
  40785. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40786. * @param pointsCloud defines if point cloud rendering has to be turned on
  40787. * @param fogEnabled defines if fog has to be turned on
  40788. * @param alphaTest defines if alpha testing has to be turned on
  40789. * @param defines defines the current list of defines
  40790. */
  40791. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40792. if (defines._areMiscDirty) {
  40793. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40794. defines["POINTSIZE"] = pointsCloud;
  40795. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40796. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40797. defines["ALPHATEST"] = alphaTest;
  40798. }
  40799. };
  40800. /**
  40801. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40802. * @param scene defines the current scene
  40803. * @param engine defines the current engine
  40804. * @param defines specifies the list of active defines
  40805. * @param useInstances defines if instances have to be turned on
  40806. * @param useClipPlane defines if clip plane have to be turned on
  40807. */
  40808. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40809. if (useClipPlane === void 0) { useClipPlane = null; }
  40810. var changed = false;
  40811. var useClipPlane1 = false;
  40812. var useClipPlane2 = false;
  40813. var useClipPlane3 = false;
  40814. var useClipPlane4 = false;
  40815. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40816. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40817. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40818. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40819. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40820. defines["CLIPPLANE"] = useClipPlane1;
  40821. changed = true;
  40822. }
  40823. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40824. defines["CLIPPLANE2"] = useClipPlane2;
  40825. changed = true;
  40826. }
  40827. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40828. defines["CLIPPLANE3"] = useClipPlane3;
  40829. changed = true;
  40830. }
  40831. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40832. defines["CLIPPLANE4"] = useClipPlane4;
  40833. changed = true;
  40834. }
  40835. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40836. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40837. changed = true;
  40838. }
  40839. if (defines["INSTANCES"] !== useInstances) {
  40840. defines["INSTANCES"] = useInstances;
  40841. changed = true;
  40842. }
  40843. if (changed) {
  40844. defines.markAsUnprocessed();
  40845. }
  40846. };
  40847. /**
  40848. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40849. * @param mesh The mesh containing the geometry data we will draw
  40850. * @param defines The defines to update
  40851. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40852. * @param useBones Precise whether bones should be used or not (override mesh info)
  40853. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40854. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40855. * @returns false if defines are considered not dirty and have not been checked
  40856. */
  40857. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40858. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40859. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40860. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40861. return false;
  40862. }
  40863. defines._normals = defines._needNormals;
  40864. defines._uvs = defines._needUVs;
  40865. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40866. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40867. defines["TANGENT"] = true;
  40868. }
  40869. if (defines._needUVs) {
  40870. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40871. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40872. }
  40873. else {
  40874. defines["UV1"] = false;
  40875. defines["UV2"] = false;
  40876. }
  40877. if (useVertexColor) {
  40878. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40879. defines["VERTEXCOLOR"] = hasVertexColors;
  40880. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40881. }
  40882. if (useBones) {
  40883. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40884. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40885. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40886. }
  40887. else {
  40888. defines["NUM_BONE_INFLUENCERS"] = 0;
  40889. defines["BonesPerMesh"] = 0;
  40890. }
  40891. }
  40892. if (useMorphTargets) {
  40893. var manager = mesh.morphTargetManager;
  40894. if (manager) {
  40895. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40896. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40897. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40898. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40899. }
  40900. else {
  40901. defines["MORPHTARGETS_TANGENT"] = false;
  40902. defines["MORPHTARGETS_NORMAL"] = false;
  40903. defines["MORPHTARGETS"] = false;
  40904. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40905. }
  40906. }
  40907. return true;
  40908. };
  40909. /**
  40910. * Prepares the defines related to the light information passed in parameter
  40911. * @param scene The scene we are intending to draw
  40912. * @param mesh The mesh the effect is compiling for
  40913. * @param defines The defines to update
  40914. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40915. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40916. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40917. * @returns true if normals will be required for the rest of the effect
  40918. */
  40919. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40920. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40921. if (disableLighting === void 0) { disableLighting = false; }
  40922. if (!defines._areLightsDirty) {
  40923. return defines._needNormals;
  40924. }
  40925. var lightIndex = 0;
  40926. var needNormals = false;
  40927. var needRebuild = false;
  40928. var lightmapMode = false;
  40929. var shadowEnabled = false;
  40930. var specularEnabled = false;
  40931. if (scene.lightsEnabled && !disableLighting) {
  40932. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40933. var light = _a[_i];
  40934. needNormals = true;
  40935. if (defines["LIGHT" + lightIndex] === undefined) {
  40936. needRebuild = true;
  40937. }
  40938. defines["LIGHT" + lightIndex] = true;
  40939. defines["SPOTLIGHT" + lightIndex] = false;
  40940. defines["HEMILIGHT" + lightIndex] = false;
  40941. defines["POINTLIGHT" + lightIndex] = false;
  40942. defines["DIRLIGHT" + lightIndex] = false;
  40943. light.prepareLightSpecificDefines(defines, lightIndex);
  40944. // FallOff.
  40945. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40946. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40947. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40948. switch (light.falloffType) {
  40949. case BABYLON.Light.FALLOFF_GLTF:
  40950. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40951. break;
  40952. case BABYLON.Light.FALLOFF_PHYSICAL:
  40953. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40954. break;
  40955. case BABYLON.Light.FALLOFF_STANDARD:
  40956. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40957. break;
  40958. }
  40959. // Specular
  40960. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40961. specularEnabled = true;
  40962. }
  40963. // Shadows
  40964. defines["SHADOW" + lightIndex] = false;
  40965. defines["SHADOWPCF" + lightIndex] = false;
  40966. defines["SHADOWPCSS" + lightIndex] = false;
  40967. defines["SHADOWPOISSON" + lightIndex] = false;
  40968. defines["SHADOWESM" + lightIndex] = false;
  40969. defines["SHADOWCUBE" + lightIndex] = false;
  40970. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40971. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40972. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40973. var shadowGenerator = light.getShadowGenerator();
  40974. if (shadowGenerator) {
  40975. var shadowMap = shadowGenerator.getShadowMap();
  40976. if (shadowMap) {
  40977. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40978. shadowEnabled = true;
  40979. shadowGenerator.prepareDefines(defines, lightIndex);
  40980. }
  40981. }
  40982. }
  40983. }
  40984. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40985. lightmapMode = true;
  40986. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40987. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40988. }
  40989. else {
  40990. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40991. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40992. }
  40993. lightIndex++;
  40994. if (lightIndex === maxSimultaneousLights)
  40995. break;
  40996. }
  40997. }
  40998. defines["SPECULARTERM"] = specularEnabled;
  40999. defines["SHADOWS"] = shadowEnabled;
  41000. // Resetting all other lights if any
  41001. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41002. if (defines["LIGHT" + index] !== undefined) {
  41003. defines["LIGHT" + index] = false;
  41004. defines["HEMILIGHT" + lightIndex] = false;
  41005. defines["POINTLIGHT" + lightIndex] = false;
  41006. defines["DIRLIGHT" + lightIndex] = false;
  41007. defines["SPOTLIGHT" + lightIndex] = false;
  41008. defines["SHADOW" + lightIndex] = false;
  41009. }
  41010. }
  41011. var caps = scene.getEngine().getCaps();
  41012. if (defines["SHADOWFLOAT"] === undefined) {
  41013. needRebuild = true;
  41014. }
  41015. defines["SHADOWFLOAT"] = shadowEnabled &&
  41016. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41017. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41018. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41019. if (needRebuild) {
  41020. defines.rebuild();
  41021. }
  41022. return needNormals;
  41023. };
  41024. /**
  41025. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41026. * that won t be acctive due to defines being turned off.
  41027. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41028. * @param samplersList The samplers list
  41029. * @param defines The defines helping in the list generation
  41030. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41031. */
  41032. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41033. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41034. var uniformsList;
  41035. var uniformBuffersList = null;
  41036. if (uniformsListOrOptions.uniformsNames) {
  41037. var options = uniformsListOrOptions;
  41038. uniformsList = options.uniformsNames;
  41039. uniformBuffersList = options.uniformBuffersNames;
  41040. samplersList = options.samplers;
  41041. defines = options.defines;
  41042. maxSimultaneousLights = options.maxSimultaneousLights;
  41043. }
  41044. else {
  41045. uniformsList = uniformsListOrOptions;
  41046. if (!samplersList) {
  41047. samplersList = [];
  41048. }
  41049. }
  41050. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41051. if (!defines["LIGHT" + lightIndex]) {
  41052. break;
  41053. }
  41054. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41055. if (uniformBuffersList) {
  41056. uniformBuffersList.push("Light" + lightIndex);
  41057. }
  41058. samplersList.push("shadowSampler" + lightIndex);
  41059. samplersList.push("depthSampler" + lightIndex);
  41060. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41061. samplersList.push("projectionLightSampler" + lightIndex);
  41062. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41063. }
  41064. }
  41065. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41066. uniformsList.push("morphTargetInfluences");
  41067. }
  41068. };
  41069. /**
  41070. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41071. * @param defines The defines to update while falling back
  41072. * @param fallbacks The authorized effect fallbacks
  41073. * @param maxSimultaneousLights The maximum number of lights allowed
  41074. * @param rank the current rank of the Effect
  41075. * @returns The newly affected rank
  41076. */
  41077. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41078. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41079. if (rank === void 0) { rank = 0; }
  41080. var lightFallbackRank = 0;
  41081. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41082. if (!defines["LIGHT" + lightIndex]) {
  41083. break;
  41084. }
  41085. if (lightIndex > 0) {
  41086. lightFallbackRank = rank + lightIndex;
  41087. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41088. }
  41089. if (!defines["SHADOWS"]) {
  41090. if (defines["SHADOW" + lightIndex]) {
  41091. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41092. }
  41093. if (defines["SHADOWPCF" + lightIndex]) {
  41094. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41095. }
  41096. if (defines["SHADOWPCSS" + lightIndex]) {
  41097. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41098. }
  41099. if (defines["SHADOWPOISSON" + lightIndex]) {
  41100. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41101. }
  41102. if (defines["SHADOWESM" + lightIndex]) {
  41103. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41104. }
  41105. }
  41106. }
  41107. return lightFallbackRank++;
  41108. };
  41109. /**
  41110. * Prepares the list of attributes required for morph targets according to the effect defines.
  41111. * @param attribs The current list of supported attribs
  41112. * @param mesh The mesh to prepare the morph targets attributes for
  41113. * @param defines The current Defines of the effect
  41114. */
  41115. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41116. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41117. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41118. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41119. var manager = mesh.morphTargetManager;
  41120. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41121. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41122. for (var index = 0; index < influencers; index++) {
  41123. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41124. if (normal) {
  41125. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41126. }
  41127. if (tangent) {
  41128. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41129. }
  41130. if (attribs.length > maxAttributesCount) {
  41131. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41132. }
  41133. }
  41134. }
  41135. };
  41136. /**
  41137. * Prepares the list of attributes required for bones according to the effect defines.
  41138. * @param attribs The current list of supported attribs
  41139. * @param mesh The mesh to prepare the bones attributes for
  41140. * @param defines The current Defines of the effect
  41141. * @param fallbacks The current efffect fallback strategy
  41142. */
  41143. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41144. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41145. fallbacks.addCPUSkinningFallback(0, mesh);
  41146. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41147. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41148. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41149. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41150. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41151. }
  41152. }
  41153. };
  41154. /**
  41155. * Prepares the list of attributes required for instances according to the effect defines.
  41156. * @param attribs The current list of supported attribs
  41157. * @param defines The current Defines of the effect
  41158. */
  41159. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41160. if (defines["INSTANCES"]) {
  41161. attribs.push("world0");
  41162. attribs.push("world1");
  41163. attribs.push("world2");
  41164. attribs.push("world3");
  41165. }
  41166. };
  41167. /**
  41168. * Binds the light shadow information to the effect for the given mesh.
  41169. * @param light The light containing the generator
  41170. * @param scene The scene the lights belongs to
  41171. * @param mesh The mesh we are binding the information to render
  41172. * @param lightIndex The light index in the effect used to render the mesh
  41173. * @param effect The effect we are binding the data to
  41174. */
  41175. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41176. if (light.shadowEnabled && mesh.receiveShadows) {
  41177. var shadowGenerator = light.getShadowGenerator();
  41178. if (shadowGenerator) {
  41179. shadowGenerator.bindShadowLight(lightIndex, effect);
  41180. }
  41181. }
  41182. };
  41183. /**
  41184. * Binds the light information to the effect.
  41185. * @param light The light containing the generator
  41186. * @param effect The effect we are binding the data to
  41187. * @param lightIndex The light index in the effect used to render
  41188. */
  41189. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41190. light.transferToEffect(effect, lightIndex + "");
  41191. };
  41192. /**
  41193. * Binds the lights information from the scene to the effect for the given mesh.
  41194. * @param scene The scene the lights belongs to
  41195. * @param mesh The mesh we are binding the information to render
  41196. * @param effect The effect we are binding the data to
  41197. * @param defines The generated defines for the effect
  41198. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41199. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41200. */
  41201. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41202. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41203. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41204. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41205. for (var i = 0; i < len; i++) {
  41206. var light = mesh._lightSources[i];
  41207. var iAsString = i.toString();
  41208. var scaledIntensity = light.getScaledIntensity();
  41209. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41210. MaterialHelper.BindLightProperties(light, effect, i);
  41211. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41212. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41213. if (defines["SPECULARTERM"]) {
  41214. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41215. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41216. }
  41217. // Shadows
  41218. if (scene.shadowsEnabled) {
  41219. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41220. }
  41221. light._uniformBuffer.update();
  41222. }
  41223. };
  41224. /**
  41225. * Binds the fog information from the scene to the effect for the given mesh.
  41226. * @param scene The scene the lights belongs to
  41227. * @param mesh The mesh we are binding the information to render
  41228. * @param effect The effect we are binding the data to
  41229. */
  41230. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41231. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41232. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41233. effect.setColor3("vFogColor", scene.fogColor);
  41234. }
  41235. };
  41236. /**
  41237. * Binds the bones information from the mesh to the effect.
  41238. * @param mesh The mesh we are binding the information to render
  41239. * @param effect The effect we are binding the data to
  41240. */
  41241. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41242. if (!effect || !mesh) {
  41243. return;
  41244. }
  41245. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41246. mesh.computeBonesUsingShaders = false;
  41247. }
  41248. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41249. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41250. if (matrices) {
  41251. effect.setMatrices("mBones", matrices);
  41252. }
  41253. }
  41254. };
  41255. /**
  41256. * Binds the morph targets information from the mesh to the effect.
  41257. * @param abstractMesh The mesh we are binding the information to render
  41258. * @param effect The effect we are binding the data to
  41259. */
  41260. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41261. var manager = abstractMesh.morphTargetManager;
  41262. if (!abstractMesh || !manager) {
  41263. return;
  41264. }
  41265. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41266. };
  41267. /**
  41268. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41269. * @param defines The generated defines used in the effect
  41270. * @param effect The effect we are binding the data to
  41271. * @param scene The scene we are willing to render with logarithmic scale for
  41272. */
  41273. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41274. if (defines["LOGARITHMICDEPTH"]) {
  41275. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41276. }
  41277. };
  41278. /**
  41279. * Binds the clip plane information from the scene to the effect.
  41280. * @param scene The scene the clip plane information are extracted from
  41281. * @param effect The effect we are binding the data to
  41282. */
  41283. MaterialHelper.BindClipPlane = function (effect, scene) {
  41284. if (scene.clipPlane) {
  41285. var clipPlane = scene.clipPlane;
  41286. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41287. }
  41288. if (scene.clipPlane2) {
  41289. var clipPlane = scene.clipPlane2;
  41290. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41291. }
  41292. if (scene.clipPlane3) {
  41293. var clipPlane = scene.clipPlane3;
  41294. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41295. }
  41296. if (scene.clipPlane4) {
  41297. var clipPlane = scene.clipPlane4;
  41298. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41299. }
  41300. };
  41301. return MaterialHelper;
  41302. }());
  41303. BABYLON.MaterialHelper = MaterialHelper;
  41304. })(BABYLON || (BABYLON = {}));
  41305. //# sourceMappingURL=babylon.materialHelper.js.map
  41306. var BABYLON;
  41307. (function (BABYLON) {
  41308. var PushMaterial = /** @class */ (function (_super) {
  41309. __extends(PushMaterial, _super);
  41310. function PushMaterial(name, scene) {
  41311. var _this = _super.call(this, name, scene) || this;
  41312. _this._normalMatrix = new BABYLON.Matrix();
  41313. _this.storeEffectOnSubMeshes = true;
  41314. return _this;
  41315. }
  41316. PushMaterial.prototype.getEffect = function () {
  41317. return this._activeEffect;
  41318. };
  41319. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41320. if (!mesh) {
  41321. return false;
  41322. }
  41323. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41324. return true;
  41325. }
  41326. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41327. };
  41328. /**
  41329. * Binds the given world matrix to the active effect
  41330. *
  41331. * @param world the matrix to bind
  41332. */
  41333. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41334. this._activeEffect.setMatrix("world", world);
  41335. };
  41336. /**
  41337. * Binds the given normal matrix to the active effect
  41338. *
  41339. * @param normalMatrix the matrix to bind
  41340. */
  41341. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41342. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41343. };
  41344. PushMaterial.prototype.bind = function (world, mesh) {
  41345. if (!mesh) {
  41346. return;
  41347. }
  41348. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41349. };
  41350. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41351. if (effect === void 0) { effect = null; }
  41352. _super.prototype._afterBind.call(this, mesh);
  41353. this.getScene()._cachedEffect = effect;
  41354. };
  41355. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41356. if (visibility === void 0) { visibility = 1; }
  41357. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41358. };
  41359. return PushMaterial;
  41360. }(BABYLON.Material));
  41361. BABYLON.PushMaterial = PushMaterial;
  41362. })(BABYLON || (BABYLON = {}));
  41363. //# sourceMappingURL=babylon.pushMaterial.js.map
  41364. var BABYLON;
  41365. (function (BABYLON) {
  41366. /** @hidden */
  41367. var StandardMaterialDefines = /** @class */ (function (_super) {
  41368. __extends(StandardMaterialDefines, _super);
  41369. function StandardMaterialDefines() {
  41370. var _this = _super.call(this) || this;
  41371. _this.MAINUV1 = false;
  41372. _this.MAINUV2 = false;
  41373. _this.DIFFUSE = false;
  41374. _this.DIFFUSEDIRECTUV = 0;
  41375. _this.AMBIENT = false;
  41376. _this.AMBIENTDIRECTUV = 0;
  41377. _this.OPACITY = false;
  41378. _this.OPACITYDIRECTUV = 0;
  41379. _this.OPACITYRGB = false;
  41380. _this.REFLECTION = false;
  41381. _this.EMISSIVE = false;
  41382. _this.EMISSIVEDIRECTUV = 0;
  41383. _this.SPECULAR = false;
  41384. _this.SPECULARDIRECTUV = 0;
  41385. _this.BUMP = false;
  41386. _this.BUMPDIRECTUV = 0;
  41387. _this.PARALLAX = false;
  41388. _this.PARALLAXOCCLUSION = false;
  41389. _this.SPECULAROVERALPHA = false;
  41390. _this.CLIPPLANE = false;
  41391. _this.CLIPPLANE2 = false;
  41392. _this.CLIPPLANE3 = false;
  41393. _this.CLIPPLANE4 = false;
  41394. _this.ALPHATEST = false;
  41395. _this.DEPTHPREPASS = false;
  41396. _this.ALPHAFROMDIFFUSE = false;
  41397. _this.POINTSIZE = false;
  41398. _this.FOG = false;
  41399. _this.SPECULARTERM = false;
  41400. _this.DIFFUSEFRESNEL = false;
  41401. _this.OPACITYFRESNEL = false;
  41402. _this.REFLECTIONFRESNEL = false;
  41403. _this.REFRACTIONFRESNEL = false;
  41404. _this.EMISSIVEFRESNEL = false;
  41405. _this.FRESNEL = false;
  41406. _this.NORMAL = false;
  41407. _this.UV1 = false;
  41408. _this.UV2 = false;
  41409. _this.VERTEXCOLOR = false;
  41410. _this.VERTEXALPHA = false;
  41411. _this.NUM_BONE_INFLUENCERS = 0;
  41412. _this.BonesPerMesh = 0;
  41413. _this.INSTANCES = false;
  41414. _this.GLOSSINESS = false;
  41415. _this.ROUGHNESS = false;
  41416. _this.EMISSIVEASILLUMINATION = false;
  41417. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41418. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41419. _this.LIGHTMAP = false;
  41420. _this.LIGHTMAPDIRECTUV = 0;
  41421. _this.OBJECTSPACE_NORMALMAP = false;
  41422. _this.USELIGHTMAPASSHADOWMAP = false;
  41423. _this.REFLECTIONMAP_3D = false;
  41424. _this.REFLECTIONMAP_SPHERICAL = false;
  41425. _this.REFLECTIONMAP_PLANAR = false;
  41426. _this.REFLECTIONMAP_CUBIC = false;
  41427. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41428. _this.REFLECTIONMAP_PROJECTION = false;
  41429. _this.REFLECTIONMAP_SKYBOX = false;
  41430. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41431. _this.REFLECTIONMAP_EXPLICIT = false;
  41432. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41433. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41434. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41435. _this.INVERTCUBICMAP = false;
  41436. _this.LOGARITHMICDEPTH = false;
  41437. _this.REFRACTION = false;
  41438. _this.REFRACTIONMAP_3D = false;
  41439. _this.REFLECTIONOVERALPHA = false;
  41440. _this.TWOSIDEDLIGHTING = false;
  41441. _this.SHADOWFLOAT = false;
  41442. _this.MORPHTARGETS = false;
  41443. _this.MORPHTARGETS_NORMAL = false;
  41444. _this.MORPHTARGETS_TANGENT = false;
  41445. _this.NUM_MORPH_INFLUENCERS = 0;
  41446. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41447. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41448. _this.IMAGEPROCESSING = false;
  41449. _this.VIGNETTE = false;
  41450. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41451. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41452. _this.TONEMAPPING = false;
  41453. _this.TONEMAPPING_ACES = false;
  41454. _this.CONTRAST = false;
  41455. _this.COLORCURVES = false;
  41456. _this.COLORGRADING = false;
  41457. _this.COLORGRADING3D = false;
  41458. _this.SAMPLER3DGREENDEPTH = false;
  41459. _this.SAMPLER3DBGRMAP = false;
  41460. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41461. /**
  41462. * If the reflection texture on this material is in linear color space
  41463. * @hidden
  41464. */
  41465. _this.IS_REFLECTION_LINEAR = false;
  41466. /**
  41467. * If the refraction texture on this material is in linear color space
  41468. * @hidden
  41469. */
  41470. _this.IS_REFRACTION_LINEAR = false;
  41471. _this.EXPOSURE = false;
  41472. _this.rebuild();
  41473. return _this;
  41474. }
  41475. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41476. var modes = [
  41477. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41478. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41479. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41480. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41481. ];
  41482. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41483. var mode = modes_1[_i];
  41484. this[mode] = (mode === modeToEnable);
  41485. }
  41486. };
  41487. return StandardMaterialDefines;
  41488. }(BABYLON.MaterialDefines));
  41489. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41490. var StandardMaterial = /** @class */ (function (_super) {
  41491. __extends(StandardMaterial, _super);
  41492. function StandardMaterial(name, scene) {
  41493. var _this = _super.call(this, name, scene) || this;
  41494. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41495. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41496. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41497. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41498. _this.specularPower = 64;
  41499. _this._useAlphaFromDiffuseTexture = false;
  41500. _this._useEmissiveAsIllumination = false;
  41501. _this._linkEmissiveWithDiffuse = false;
  41502. _this._useSpecularOverAlpha = false;
  41503. _this._useReflectionOverAlpha = false;
  41504. _this._disableLighting = false;
  41505. _this._useObjectSpaceNormalMap = false;
  41506. _this._useParallax = false;
  41507. _this._useParallaxOcclusion = false;
  41508. _this.parallaxScaleBias = 0.05;
  41509. _this._roughness = 0;
  41510. _this.indexOfRefraction = 0.98;
  41511. _this.invertRefractionY = true;
  41512. /**
  41513. * Defines the alpha limits in alpha test mode
  41514. */
  41515. _this.alphaCutOff = 0.4;
  41516. _this._useLightmapAsShadowmap = false;
  41517. _this._useReflectionFresnelFromSpecular = false;
  41518. _this._useGlossinessFromSpecularMapAlpha = false;
  41519. _this._maxSimultaneousLights = 4;
  41520. /**
  41521. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41522. */
  41523. _this._invertNormalMapX = false;
  41524. /**
  41525. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41526. */
  41527. _this._invertNormalMapY = false;
  41528. /**
  41529. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41530. */
  41531. _this._twoSidedLighting = false;
  41532. _this._renderTargets = new BABYLON.SmartArray(16);
  41533. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41534. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41535. // Setup the default processing configuration to the scene.
  41536. _this._attachImageProcessingConfiguration(null);
  41537. _this.getRenderTargetTextures = function () {
  41538. _this._renderTargets.reset();
  41539. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41540. _this._renderTargets.push(_this._reflectionTexture);
  41541. }
  41542. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41543. _this._renderTargets.push(_this._refractionTexture);
  41544. }
  41545. return _this._renderTargets;
  41546. };
  41547. return _this;
  41548. }
  41549. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41550. /**
  41551. * Gets the image processing configuration used either in this material.
  41552. */
  41553. get: function () {
  41554. return this._imageProcessingConfiguration;
  41555. },
  41556. /**
  41557. * Sets the Default image processing configuration used either in the this material.
  41558. *
  41559. * If sets to null, the scene one is in use.
  41560. */
  41561. set: function (value) {
  41562. this._attachImageProcessingConfiguration(value);
  41563. // Ensure the effect will be rebuilt.
  41564. this._markAllSubMeshesAsTexturesDirty();
  41565. },
  41566. enumerable: true,
  41567. configurable: true
  41568. });
  41569. /**
  41570. * Attaches a new image processing configuration to the Standard Material.
  41571. * @param configuration
  41572. */
  41573. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41574. var _this = this;
  41575. if (configuration === this._imageProcessingConfiguration) {
  41576. return;
  41577. }
  41578. // Detaches observer.
  41579. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41580. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41581. }
  41582. // Pick the scene configuration if needed.
  41583. if (!configuration) {
  41584. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41585. }
  41586. else {
  41587. this._imageProcessingConfiguration = configuration;
  41588. }
  41589. // Attaches observer.
  41590. if (this._imageProcessingConfiguration) {
  41591. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41592. _this._markAllSubMeshesAsImageProcessingDirty();
  41593. });
  41594. }
  41595. };
  41596. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41597. /**
  41598. * Gets wether the color curves effect is enabled.
  41599. */
  41600. get: function () {
  41601. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41602. },
  41603. /**
  41604. * Sets wether the color curves effect is enabled.
  41605. */
  41606. set: function (value) {
  41607. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41608. },
  41609. enumerable: true,
  41610. configurable: true
  41611. });
  41612. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41613. /**
  41614. * Gets wether the color grading effect is enabled.
  41615. */
  41616. get: function () {
  41617. return this.imageProcessingConfiguration.colorGradingEnabled;
  41618. },
  41619. /**
  41620. * Gets wether the color grading effect is enabled.
  41621. */
  41622. set: function (value) {
  41623. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41624. },
  41625. enumerable: true,
  41626. configurable: true
  41627. });
  41628. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41629. /**
  41630. * Gets wether tonemapping is enabled or not.
  41631. */
  41632. get: function () {
  41633. return this._imageProcessingConfiguration.toneMappingEnabled;
  41634. },
  41635. /**
  41636. * Sets wether tonemapping is enabled or not
  41637. */
  41638. set: function (value) {
  41639. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41640. },
  41641. enumerable: true,
  41642. configurable: true
  41643. });
  41644. ;
  41645. ;
  41646. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41647. /**
  41648. * The camera exposure used on this material.
  41649. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41650. * This corresponds to a photographic exposure.
  41651. */
  41652. get: function () {
  41653. return this._imageProcessingConfiguration.exposure;
  41654. },
  41655. /**
  41656. * The camera exposure used on this material.
  41657. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41658. * This corresponds to a photographic exposure.
  41659. */
  41660. set: function (value) {
  41661. this._imageProcessingConfiguration.exposure = value;
  41662. },
  41663. enumerable: true,
  41664. configurable: true
  41665. });
  41666. ;
  41667. ;
  41668. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41669. /**
  41670. * Gets The camera contrast used on this material.
  41671. */
  41672. get: function () {
  41673. return this._imageProcessingConfiguration.contrast;
  41674. },
  41675. /**
  41676. * Sets The camera contrast used on this material.
  41677. */
  41678. set: function (value) {
  41679. this._imageProcessingConfiguration.contrast = value;
  41680. },
  41681. enumerable: true,
  41682. configurable: true
  41683. });
  41684. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41685. /**
  41686. * Gets the Color Grading 2D Lookup Texture.
  41687. */
  41688. get: function () {
  41689. return this._imageProcessingConfiguration.colorGradingTexture;
  41690. },
  41691. /**
  41692. * Sets the Color Grading 2D Lookup Texture.
  41693. */
  41694. set: function (value) {
  41695. this._imageProcessingConfiguration.colorGradingTexture = value;
  41696. },
  41697. enumerable: true,
  41698. configurable: true
  41699. });
  41700. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41701. /**
  41702. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41703. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41704. * 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;
  41705. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41706. */
  41707. get: function () {
  41708. return this._imageProcessingConfiguration.colorCurves;
  41709. },
  41710. /**
  41711. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41712. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41713. * 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;
  41714. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41715. */
  41716. set: function (value) {
  41717. this._imageProcessingConfiguration.colorCurves = value;
  41718. },
  41719. enumerable: true,
  41720. configurable: true
  41721. });
  41722. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41723. /**
  41724. * Gets a boolean indicating that current material needs to register RTT
  41725. */
  41726. get: function () {
  41727. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41728. return true;
  41729. }
  41730. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41731. return true;
  41732. }
  41733. return false;
  41734. },
  41735. enumerable: true,
  41736. configurable: true
  41737. });
  41738. StandardMaterial.prototype.getClassName = function () {
  41739. return "StandardMaterial";
  41740. };
  41741. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41742. get: function () {
  41743. return this._useLogarithmicDepth;
  41744. },
  41745. set: function (value) {
  41746. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41747. this._markAllSubMeshesAsMiscDirty();
  41748. },
  41749. enumerable: true,
  41750. configurable: true
  41751. });
  41752. StandardMaterial.prototype.needAlphaBlending = function () {
  41753. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41754. };
  41755. StandardMaterial.prototype.needAlphaTesting = function () {
  41756. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41757. };
  41758. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41759. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41760. };
  41761. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41762. return this._diffuseTexture;
  41763. };
  41764. /**
  41765. * Child classes can use it to update shaders
  41766. */
  41767. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41768. if (useInstances === void 0) { useInstances = false; }
  41769. if (subMesh.effect && this.isFrozen) {
  41770. if (this._wasPreviouslyReady) {
  41771. return true;
  41772. }
  41773. }
  41774. if (!subMesh._materialDefines) {
  41775. subMesh._materialDefines = new StandardMaterialDefines();
  41776. }
  41777. var scene = this.getScene();
  41778. var defines = subMesh._materialDefines;
  41779. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41780. if (defines._renderId === scene.getRenderId()) {
  41781. return true;
  41782. }
  41783. }
  41784. var engine = scene.getEngine();
  41785. // Lights
  41786. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41787. // Textures
  41788. if (defines._areTexturesDirty) {
  41789. defines._needUVs = false;
  41790. defines.MAINUV1 = false;
  41791. defines.MAINUV2 = false;
  41792. if (scene.texturesEnabled) {
  41793. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41794. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41795. return false;
  41796. }
  41797. else {
  41798. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41799. }
  41800. }
  41801. else {
  41802. defines.DIFFUSE = false;
  41803. }
  41804. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41805. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41806. return false;
  41807. }
  41808. else {
  41809. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41810. }
  41811. }
  41812. else {
  41813. defines.AMBIENT = false;
  41814. }
  41815. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41816. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41817. return false;
  41818. }
  41819. else {
  41820. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41821. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41822. }
  41823. }
  41824. else {
  41825. defines.OPACITY = false;
  41826. }
  41827. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41828. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41829. return false;
  41830. }
  41831. else {
  41832. defines._needNormals = true;
  41833. defines.REFLECTION = true;
  41834. defines.ROUGHNESS = (this._roughness > 0);
  41835. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41836. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41837. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41838. switch (this._reflectionTexture.coordinatesMode) {
  41839. case BABYLON.Texture.EXPLICIT_MODE:
  41840. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41841. break;
  41842. case BABYLON.Texture.PLANAR_MODE:
  41843. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41844. break;
  41845. case BABYLON.Texture.PROJECTION_MODE:
  41846. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41847. break;
  41848. case BABYLON.Texture.SKYBOX_MODE:
  41849. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41850. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41851. break;
  41852. case BABYLON.Texture.SPHERICAL_MODE:
  41853. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41854. break;
  41855. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41856. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41857. break;
  41858. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41859. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41860. break;
  41861. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41862. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41863. break;
  41864. case BABYLON.Texture.CUBIC_MODE:
  41865. case BABYLON.Texture.INVCUBIC_MODE:
  41866. default:
  41867. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41868. break;
  41869. }
  41870. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41871. }
  41872. }
  41873. else {
  41874. defines.REFLECTION = false;
  41875. }
  41876. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41877. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41878. return false;
  41879. }
  41880. else {
  41881. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41882. }
  41883. }
  41884. else {
  41885. defines.EMISSIVE = false;
  41886. }
  41887. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41888. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41889. return false;
  41890. }
  41891. else {
  41892. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41893. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41894. }
  41895. }
  41896. else {
  41897. defines.LIGHTMAP = false;
  41898. }
  41899. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41900. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41901. return false;
  41902. }
  41903. else {
  41904. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41905. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41906. }
  41907. }
  41908. else {
  41909. defines.SPECULAR = false;
  41910. }
  41911. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41912. // Bump texure can not be not blocking.
  41913. if (!this._bumpTexture.isReady()) {
  41914. return false;
  41915. }
  41916. else {
  41917. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41918. defines.PARALLAX = this._useParallax;
  41919. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41920. }
  41921. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41922. }
  41923. else {
  41924. defines.BUMP = false;
  41925. }
  41926. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41927. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41928. return false;
  41929. }
  41930. else {
  41931. defines._needUVs = true;
  41932. defines.REFRACTION = true;
  41933. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41934. }
  41935. }
  41936. else {
  41937. defines.REFRACTION = false;
  41938. }
  41939. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41940. }
  41941. else {
  41942. defines.DIFFUSE = false;
  41943. defines.AMBIENT = false;
  41944. defines.OPACITY = false;
  41945. defines.REFLECTION = false;
  41946. defines.EMISSIVE = false;
  41947. defines.LIGHTMAP = false;
  41948. defines.BUMP = false;
  41949. defines.REFRACTION = false;
  41950. }
  41951. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41952. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41953. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41954. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41955. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41956. }
  41957. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41958. if (!this._imageProcessingConfiguration.isReady()) {
  41959. return false;
  41960. }
  41961. this._imageProcessingConfiguration.prepareDefines(defines);
  41962. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41963. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41964. }
  41965. if (defines._areFresnelDirty) {
  41966. if (StandardMaterial.FresnelEnabled) {
  41967. // Fresnel
  41968. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41969. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41970. this._reflectionFresnelParameters) {
  41971. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41972. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41973. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41974. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41975. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41976. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41977. defines._needNormals = true;
  41978. defines.FRESNEL = true;
  41979. }
  41980. }
  41981. else {
  41982. defines.FRESNEL = false;
  41983. }
  41984. }
  41985. // Misc.
  41986. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41987. // Attribs
  41988. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41989. // Values that need to be evaluated on every frame
  41990. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41991. // Get correct effect
  41992. if (defines.isDirty) {
  41993. defines.markAsProcessed();
  41994. scene.resetCachedMaterial();
  41995. // Fallbacks
  41996. var fallbacks = new BABYLON.EffectFallbacks();
  41997. if (defines.REFLECTION) {
  41998. fallbacks.addFallback(0, "REFLECTION");
  41999. }
  42000. if (defines.SPECULAR) {
  42001. fallbacks.addFallback(0, "SPECULAR");
  42002. }
  42003. if (defines.BUMP) {
  42004. fallbacks.addFallback(0, "BUMP");
  42005. }
  42006. if (defines.PARALLAX) {
  42007. fallbacks.addFallback(1, "PARALLAX");
  42008. }
  42009. if (defines.PARALLAXOCCLUSION) {
  42010. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42011. }
  42012. if (defines.SPECULAROVERALPHA) {
  42013. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42014. }
  42015. if (defines.FOG) {
  42016. fallbacks.addFallback(1, "FOG");
  42017. }
  42018. if (defines.POINTSIZE) {
  42019. fallbacks.addFallback(0, "POINTSIZE");
  42020. }
  42021. if (defines.LOGARITHMICDEPTH) {
  42022. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42023. }
  42024. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42025. if (defines.SPECULARTERM) {
  42026. fallbacks.addFallback(0, "SPECULARTERM");
  42027. }
  42028. if (defines.DIFFUSEFRESNEL) {
  42029. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42030. }
  42031. if (defines.OPACITYFRESNEL) {
  42032. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42033. }
  42034. if (defines.REFLECTIONFRESNEL) {
  42035. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42036. }
  42037. if (defines.EMISSIVEFRESNEL) {
  42038. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42039. }
  42040. if (defines.FRESNEL) {
  42041. fallbacks.addFallback(4, "FRESNEL");
  42042. }
  42043. //Attributes
  42044. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42045. if (defines.NORMAL) {
  42046. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42047. }
  42048. if (defines.UV1) {
  42049. attribs.push(BABYLON.VertexBuffer.UVKind);
  42050. }
  42051. if (defines.UV2) {
  42052. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42053. }
  42054. if (defines.VERTEXCOLOR) {
  42055. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42056. }
  42057. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42058. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42059. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42060. var shaderName = "default";
  42061. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42062. "vFogInfos", "vFogColor", "pointSize",
  42063. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42064. "mBones",
  42065. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42066. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42067. "vReflectionPosition", "vReflectionSize",
  42068. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42069. ];
  42070. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42071. var uniformBuffers = ["Material", "Scene"];
  42072. if (BABYLON.ImageProcessingConfiguration) {
  42073. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42074. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42075. }
  42076. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42077. uniformsNames: uniforms,
  42078. uniformBuffersNames: uniformBuffers,
  42079. samplers: samplers,
  42080. defines: defines,
  42081. maxSimultaneousLights: this._maxSimultaneousLights
  42082. });
  42083. if (this.customShaderNameResolve) {
  42084. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42085. }
  42086. var join = defines.toString();
  42087. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42088. attributes: attribs,
  42089. uniformsNames: uniforms,
  42090. uniformBuffersNames: uniformBuffers,
  42091. samplers: samplers,
  42092. defines: join,
  42093. fallbacks: fallbacks,
  42094. onCompiled: this.onCompiled,
  42095. onError: this.onError,
  42096. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42097. }, engine), defines);
  42098. this.buildUniformLayout();
  42099. }
  42100. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42101. return false;
  42102. }
  42103. defines._renderId = scene.getRenderId();
  42104. this._wasPreviouslyReady = true;
  42105. return true;
  42106. };
  42107. StandardMaterial.prototype.buildUniformLayout = function () {
  42108. // Order is important !
  42109. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42110. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42111. this._uniformBuffer.addUniform("opacityParts", 4);
  42112. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42113. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42114. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42115. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42116. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42117. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42118. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42119. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42120. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42121. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42122. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42123. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42124. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42125. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42126. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42127. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42128. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42129. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42130. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42131. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42132. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42133. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42134. this._uniformBuffer.addUniform("specularMatrix", 16);
  42135. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42136. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42137. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42138. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42139. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42140. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42141. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42142. this._uniformBuffer.addUniform("pointSize", 1);
  42143. this._uniformBuffer.create();
  42144. };
  42145. StandardMaterial.prototype.unbind = function () {
  42146. if (this._activeEffect) {
  42147. var needFlag = false;
  42148. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42149. this._activeEffect.setTexture("reflection2DSampler", null);
  42150. needFlag = true;
  42151. }
  42152. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42153. this._activeEffect.setTexture("refraction2DSampler", null);
  42154. needFlag = true;
  42155. }
  42156. if (needFlag) {
  42157. this._markAllSubMeshesAsTexturesDirty();
  42158. }
  42159. }
  42160. _super.prototype.unbind.call(this);
  42161. };
  42162. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42163. var scene = this.getScene();
  42164. var defines = subMesh._materialDefines;
  42165. if (!defines) {
  42166. return;
  42167. }
  42168. var effect = subMesh.effect;
  42169. if (!effect) {
  42170. return;
  42171. }
  42172. this._activeEffect = effect;
  42173. // Matrices
  42174. this.bindOnlyWorldMatrix(world);
  42175. // Normal Matrix
  42176. if (defines.OBJECTSPACE_NORMALMAP) {
  42177. world.toNormalMatrix(this._normalMatrix);
  42178. this.bindOnlyNormalMatrix(this._normalMatrix);
  42179. }
  42180. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42181. // Bones
  42182. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42183. if (mustRebind) {
  42184. this._uniformBuffer.bindToEffect(effect, "Material");
  42185. this.bindViewProjection(effect);
  42186. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42187. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42188. // Fresnel
  42189. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42190. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42191. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42192. }
  42193. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42194. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42195. }
  42196. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42197. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42198. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42199. }
  42200. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42201. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42202. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42203. }
  42204. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42205. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42206. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42207. }
  42208. }
  42209. // Textures
  42210. if (scene.texturesEnabled) {
  42211. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42212. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42213. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42214. if (this._diffuseTexture.hasAlpha) {
  42215. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42216. }
  42217. }
  42218. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42219. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42220. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42221. }
  42222. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42223. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42224. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42225. }
  42226. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42227. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42228. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42229. if (this._reflectionTexture.boundingBoxSize) {
  42230. var cubeTexture = this._reflectionTexture;
  42231. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42232. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42233. }
  42234. }
  42235. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42236. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42237. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42238. }
  42239. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42240. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42241. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42242. }
  42243. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42244. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42245. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42246. }
  42247. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42248. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42249. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42250. if (scene._mirroredCameraPosition) {
  42251. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42252. }
  42253. else {
  42254. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42255. }
  42256. }
  42257. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42258. var depth = 1.0;
  42259. if (!this._refractionTexture.isCube) {
  42260. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42261. if (this._refractionTexture.depth) {
  42262. depth = this._refractionTexture.depth;
  42263. }
  42264. }
  42265. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42266. }
  42267. }
  42268. // Point size
  42269. if (this.pointsCloud) {
  42270. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42271. }
  42272. if (defines.SPECULARTERM) {
  42273. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42274. }
  42275. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42276. // Diffuse
  42277. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42278. }
  42279. // Textures
  42280. if (scene.texturesEnabled) {
  42281. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42282. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42283. }
  42284. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42285. effect.setTexture("ambientSampler", this._ambientTexture);
  42286. }
  42287. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42288. effect.setTexture("opacitySampler", this._opacityTexture);
  42289. }
  42290. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42291. if (this._reflectionTexture.isCube) {
  42292. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42293. }
  42294. else {
  42295. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42296. }
  42297. }
  42298. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42299. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42300. }
  42301. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42302. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42303. }
  42304. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42305. effect.setTexture("specularSampler", this._specularTexture);
  42306. }
  42307. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42308. effect.setTexture("bumpSampler", this._bumpTexture);
  42309. }
  42310. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42311. var depth = 1.0;
  42312. if (this._refractionTexture.isCube) {
  42313. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42314. }
  42315. else {
  42316. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42317. }
  42318. }
  42319. }
  42320. // Clip plane
  42321. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42322. // Colors
  42323. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42324. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42325. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42326. }
  42327. if (mustRebind || !this.isFrozen) {
  42328. // Lights
  42329. if (scene.lightsEnabled && !this._disableLighting) {
  42330. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42331. }
  42332. // View
  42333. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42334. this.bindView(effect);
  42335. }
  42336. // Fog
  42337. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42338. // Morph targets
  42339. if (defines.NUM_MORPH_INFLUENCERS) {
  42340. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42341. }
  42342. // Log. depth
  42343. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42344. // image processing
  42345. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42346. this._imageProcessingConfiguration.bind(this._activeEffect);
  42347. }
  42348. }
  42349. this._uniformBuffer.update();
  42350. this._afterBind(mesh, this._activeEffect);
  42351. };
  42352. StandardMaterial.prototype.getAnimatables = function () {
  42353. var results = [];
  42354. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42355. results.push(this._diffuseTexture);
  42356. }
  42357. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42358. results.push(this._ambientTexture);
  42359. }
  42360. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42361. results.push(this._opacityTexture);
  42362. }
  42363. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42364. results.push(this._reflectionTexture);
  42365. }
  42366. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42367. results.push(this._emissiveTexture);
  42368. }
  42369. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42370. results.push(this._specularTexture);
  42371. }
  42372. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42373. results.push(this._bumpTexture);
  42374. }
  42375. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42376. results.push(this._lightmapTexture);
  42377. }
  42378. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42379. results.push(this._refractionTexture);
  42380. }
  42381. return results;
  42382. };
  42383. StandardMaterial.prototype.getActiveTextures = function () {
  42384. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42385. if (this._diffuseTexture) {
  42386. activeTextures.push(this._diffuseTexture);
  42387. }
  42388. if (this._ambientTexture) {
  42389. activeTextures.push(this._ambientTexture);
  42390. }
  42391. if (this._opacityTexture) {
  42392. activeTextures.push(this._opacityTexture);
  42393. }
  42394. if (this._reflectionTexture) {
  42395. activeTextures.push(this._reflectionTexture);
  42396. }
  42397. if (this._emissiveTexture) {
  42398. activeTextures.push(this._emissiveTexture);
  42399. }
  42400. if (this._specularTexture) {
  42401. activeTextures.push(this._specularTexture);
  42402. }
  42403. if (this._bumpTexture) {
  42404. activeTextures.push(this._bumpTexture);
  42405. }
  42406. if (this._lightmapTexture) {
  42407. activeTextures.push(this._lightmapTexture);
  42408. }
  42409. if (this._refractionTexture) {
  42410. activeTextures.push(this._refractionTexture);
  42411. }
  42412. return activeTextures;
  42413. };
  42414. StandardMaterial.prototype.hasTexture = function (texture) {
  42415. if (_super.prototype.hasTexture.call(this, texture)) {
  42416. return true;
  42417. }
  42418. if (this._diffuseTexture === texture) {
  42419. return true;
  42420. }
  42421. if (this._ambientTexture === texture) {
  42422. return true;
  42423. }
  42424. if (this._opacityTexture === texture) {
  42425. return true;
  42426. }
  42427. if (this._reflectionTexture === texture) {
  42428. return true;
  42429. }
  42430. if (this._emissiveTexture === texture) {
  42431. return true;
  42432. }
  42433. if (this._specularTexture === texture) {
  42434. return true;
  42435. }
  42436. if (this._bumpTexture === texture) {
  42437. return true;
  42438. }
  42439. if (this._lightmapTexture === texture) {
  42440. return true;
  42441. }
  42442. if (this._refractionTexture === texture) {
  42443. return true;
  42444. }
  42445. return false;
  42446. };
  42447. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42448. if (forceDisposeTextures) {
  42449. if (this._diffuseTexture) {
  42450. this._diffuseTexture.dispose();
  42451. }
  42452. if (this._ambientTexture) {
  42453. this._ambientTexture.dispose();
  42454. }
  42455. if (this._opacityTexture) {
  42456. this._opacityTexture.dispose();
  42457. }
  42458. if (this._reflectionTexture) {
  42459. this._reflectionTexture.dispose();
  42460. }
  42461. if (this._emissiveTexture) {
  42462. this._emissiveTexture.dispose();
  42463. }
  42464. if (this._specularTexture) {
  42465. this._specularTexture.dispose();
  42466. }
  42467. if (this._bumpTexture) {
  42468. this._bumpTexture.dispose();
  42469. }
  42470. if (this._lightmapTexture) {
  42471. this._lightmapTexture.dispose();
  42472. }
  42473. if (this._refractionTexture) {
  42474. this._refractionTexture.dispose();
  42475. }
  42476. }
  42477. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42478. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42479. }
  42480. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42481. };
  42482. StandardMaterial.prototype.clone = function (name) {
  42483. var _this = this;
  42484. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42485. result.name = name;
  42486. result.id = name;
  42487. return result;
  42488. };
  42489. StandardMaterial.prototype.serialize = function () {
  42490. return BABYLON.SerializationHelper.Serialize(this);
  42491. };
  42492. // Statics
  42493. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42494. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42495. };
  42496. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42497. get: function () {
  42498. return StandardMaterial._DiffuseTextureEnabled;
  42499. },
  42500. set: function (value) {
  42501. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42502. return;
  42503. }
  42504. StandardMaterial._DiffuseTextureEnabled = value;
  42505. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42506. },
  42507. enumerable: true,
  42508. configurable: true
  42509. });
  42510. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42511. get: function () {
  42512. return StandardMaterial._AmbientTextureEnabled;
  42513. },
  42514. set: function (value) {
  42515. if (StandardMaterial._AmbientTextureEnabled === value) {
  42516. return;
  42517. }
  42518. StandardMaterial._AmbientTextureEnabled = value;
  42519. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42520. },
  42521. enumerable: true,
  42522. configurable: true
  42523. });
  42524. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42525. get: function () {
  42526. return StandardMaterial._OpacityTextureEnabled;
  42527. },
  42528. set: function (value) {
  42529. if (StandardMaterial._OpacityTextureEnabled === value) {
  42530. return;
  42531. }
  42532. StandardMaterial._OpacityTextureEnabled = value;
  42533. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42534. },
  42535. enumerable: true,
  42536. configurable: true
  42537. });
  42538. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42539. get: function () {
  42540. return StandardMaterial._ReflectionTextureEnabled;
  42541. },
  42542. set: function (value) {
  42543. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42544. return;
  42545. }
  42546. StandardMaterial._ReflectionTextureEnabled = value;
  42547. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42548. },
  42549. enumerable: true,
  42550. configurable: true
  42551. });
  42552. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42553. get: function () {
  42554. return StandardMaterial._EmissiveTextureEnabled;
  42555. },
  42556. set: function (value) {
  42557. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42558. return;
  42559. }
  42560. StandardMaterial._EmissiveTextureEnabled = value;
  42561. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42562. },
  42563. enumerable: true,
  42564. configurable: true
  42565. });
  42566. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42567. get: function () {
  42568. return StandardMaterial._SpecularTextureEnabled;
  42569. },
  42570. set: function (value) {
  42571. if (StandardMaterial._SpecularTextureEnabled === value) {
  42572. return;
  42573. }
  42574. StandardMaterial._SpecularTextureEnabled = value;
  42575. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42576. },
  42577. enumerable: true,
  42578. configurable: true
  42579. });
  42580. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42581. get: function () {
  42582. return StandardMaterial._BumpTextureEnabled;
  42583. },
  42584. set: function (value) {
  42585. if (StandardMaterial._BumpTextureEnabled === value) {
  42586. return;
  42587. }
  42588. StandardMaterial._BumpTextureEnabled = value;
  42589. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42590. },
  42591. enumerable: true,
  42592. configurable: true
  42593. });
  42594. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42595. get: function () {
  42596. return StandardMaterial._LightmapTextureEnabled;
  42597. },
  42598. set: function (value) {
  42599. if (StandardMaterial._LightmapTextureEnabled === value) {
  42600. return;
  42601. }
  42602. StandardMaterial._LightmapTextureEnabled = value;
  42603. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42604. },
  42605. enumerable: true,
  42606. configurable: true
  42607. });
  42608. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42609. get: function () {
  42610. return StandardMaterial._RefractionTextureEnabled;
  42611. },
  42612. set: function (value) {
  42613. if (StandardMaterial._RefractionTextureEnabled === value) {
  42614. return;
  42615. }
  42616. StandardMaterial._RefractionTextureEnabled = value;
  42617. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42618. },
  42619. enumerable: true,
  42620. configurable: true
  42621. });
  42622. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42623. get: function () {
  42624. return StandardMaterial._ColorGradingTextureEnabled;
  42625. },
  42626. set: function (value) {
  42627. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42628. return;
  42629. }
  42630. StandardMaterial._ColorGradingTextureEnabled = value;
  42631. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42632. },
  42633. enumerable: true,
  42634. configurable: true
  42635. });
  42636. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42637. get: function () {
  42638. return StandardMaterial._FresnelEnabled;
  42639. },
  42640. set: function (value) {
  42641. if (StandardMaterial._FresnelEnabled === value) {
  42642. return;
  42643. }
  42644. StandardMaterial._FresnelEnabled = value;
  42645. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42646. },
  42647. enumerable: true,
  42648. configurable: true
  42649. });
  42650. // Flags used to enable or disable a type of texture for all Standard Materials
  42651. StandardMaterial._DiffuseTextureEnabled = true;
  42652. StandardMaterial._AmbientTextureEnabled = true;
  42653. StandardMaterial._OpacityTextureEnabled = true;
  42654. StandardMaterial._ReflectionTextureEnabled = true;
  42655. StandardMaterial._EmissiveTextureEnabled = true;
  42656. StandardMaterial._SpecularTextureEnabled = true;
  42657. StandardMaterial._BumpTextureEnabled = true;
  42658. StandardMaterial._LightmapTextureEnabled = true;
  42659. StandardMaterial._RefractionTextureEnabled = true;
  42660. StandardMaterial._ColorGradingTextureEnabled = true;
  42661. StandardMaterial._FresnelEnabled = true;
  42662. __decorate([
  42663. BABYLON.serializeAsTexture("diffuseTexture")
  42664. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42665. __decorate([
  42666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42667. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42668. __decorate([
  42669. BABYLON.serializeAsTexture("ambientTexture")
  42670. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42671. __decorate([
  42672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42673. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42674. __decorate([
  42675. BABYLON.serializeAsTexture("opacityTexture")
  42676. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42677. __decorate([
  42678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42679. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42680. __decorate([
  42681. BABYLON.serializeAsTexture("reflectionTexture")
  42682. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42683. __decorate([
  42684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42685. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42686. __decorate([
  42687. BABYLON.serializeAsTexture("emissiveTexture")
  42688. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42689. __decorate([
  42690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42691. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42692. __decorate([
  42693. BABYLON.serializeAsTexture("specularTexture")
  42694. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42695. __decorate([
  42696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42697. ], StandardMaterial.prototype, "specularTexture", void 0);
  42698. __decorate([
  42699. BABYLON.serializeAsTexture("bumpTexture")
  42700. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42701. __decorate([
  42702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42703. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42704. __decorate([
  42705. BABYLON.serializeAsTexture("lightmapTexture")
  42706. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42707. __decorate([
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42709. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42710. __decorate([
  42711. BABYLON.serializeAsTexture("refractionTexture")
  42712. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42713. __decorate([
  42714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42715. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42716. __decorate([
  42717. BABYLON.serializeAsColor3("ambient")
  42718. ], StandardMaterial.prototype, "ambientColor", void 0);
  42719. __decorate([
  42720. BABYLON.serializeAsColor3("diffuse")
  42721. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42722. __decorate([
  42723. BABYLON.serializeAsColor3("specular")
  42724. ], StandardMaterial.prototype, "specularColor", void 0);
  42725. __decorate([
  42726. BABYLON.serializeAsColor3("emissive")
  42727. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42728. __decorate([
  42729. BABYLON.serialize()
  42730. ], StandardMaterial.prototype, "specularPower", void 0);
  42731. __decorate([
  42732. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42733. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42734. __decorate([
  42735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42736. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42737. __decorate([
  42738. BABYLON.serialize("useEmissiveAsIllumination")
  42739. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42740. __decorate([
  42741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42742. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42743. __decorate([
  42744. BABYLON.serialize("linkEmissiveWithDiffuse")
  42745. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42746. __decorate([
  42747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42748. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42749. __decorate([
  42750. BABYLON.serialize("useSpecularOverAlpha")
  42751. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42752. __decorate([
  42753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42754. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42755. __decorate([
  42756. BABYLON.serialize("useReflectionOverAlpha")
  42757. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42758. __decorate([
  42759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42760. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42761. __decorate([
  42762. BABYLON.serialize("disableLighting")
  42763. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42764. __decorate([
  42765. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42766. ], StandardMaterial.prototype, "disableLighting", void 0);
  42767. __decorate([
  42768. BABYLON.serialize("useObjectSpaceNormalMap")
  42769. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42770. __decorate([
  42771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42772. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42773. __decorate([
  42774. BABYLON.serialize("useParallax")
  42775. ], StandardMaterial.prototype, "_useParallax", void 0);
  42776. __decorate([
  42777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42778. ], StandardMaterial.prototype, "useParallax", void 0);
  42779. __decorate([
  42780. BABYLON.serialize("useParallaxOcclusion")
  42781. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42782. __decorate([
  42783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42784. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42785. __decorate([
  42786. BABYLON.serialize()
  42787. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42788. __decorate([
  42789. BABYLON.serialize("roughness")
  42790. ], StandardMaterial.prototype, "_roughness", void 0);
  42791. __decorate([
  42792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42793. ], StandardMaterial.prototype, "roughness", void 0);
  42794. __decorate([
  42795. BABYLON.serialize()
  42796. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42797. __decorate([
  42798. BABYLON.serialize()
  42799. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42800. __decorate([
  42801. BABYLON.serialize()
  42802. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42803. __decorate([
  42804. BABYLON.serialize("useLightmapAsShadowmap")
  42805. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42806. __decorate([
  42807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42808. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42809. __decorate([
  42810. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42811. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42812. __decorate([
  42813. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42814. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42815. __decorate([
  42816. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42817. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42818. __decorate([
  42819. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42820. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42821. __decorate([
  42822. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42823. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42824. __decorate([
  42825. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42826. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42827. __decorate([
  42828. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42829. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42830. __decorate([
  42831. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42832. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42833. __decorate([
  42834. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42835. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42836. __decorate([
  42837. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42838. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42839. __decorate([
  42840. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42841. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42842. __decorate([
  42843. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42844. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42845. __decorate([
  42846. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42847. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42848. __decorate([
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42850. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42851. __decorate([
  42852. BABYLON.serialize("maxSimultaneousLights")
  42853. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42854. __decorate([
  42855. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42856. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42857. __decorate([
  42858. BABYLON.serialize("invertNormalMapX")
  42859. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42860. __decorate([
  42861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42862. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42863. __decorate([
  42864. BABYLON.serialize("invertNormalMapY")
  42865. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42866. __decorate([
  42867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42868. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42869. __decorate([
  42870. BABYLON.serialize("twoSidedLighting")
  42871. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42872. __decorate([
  42873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42874. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42875. __decorate([
  42876. BABYLON.serialize()
  42877. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42878. return StandardMaterial;
  42879. }(BABYLON.PushMaterial));
  42880. BABYLON.StandardMaterial = StandardMaterial;
  42881. })(BABYLON || (BABYLON = {}));
  42882. //# sourceMappingURL=babylon.standardMaterial.js.map
  42883. var BABYLON;
  42884. (function (BABYLON) {
  42885. /**
  42886. * Class representing spherical polynomial coefficients to the 3rd degree
  42887. */
  42888. var SphericalPolynomial = /** @class */ (function () {
  42889. function SphericalPolynomial() {
  42890. /**
  42891. * The x coefficients of the spherical polynomial
  42892. */
  42893. this.x = BABYLON.Vector3.Zero();
  42894. /**
  42895. * The y coefficients of the spherical polynomial
  42896. */
  42897. this.y = BABYLON.Vector3.Zero();
  42898. /**
  42899. * The z coefficients of the spherical polynomial
  42900. */
  42901. this.z = BABYLON.Vector3.Zero();
  42902. /**
  42903. * The xx coefficients of the spherical polynomial
  42904. */
  42905. this.xx = BABYLON.Vector3.Zero();
  42906. /**
  42907. * The yy coefficients of the spherical polynomial
  42908. */
  42909. this.yy = BABYLON.Vector3.Zero();
  42910. /**
  42911. * The zz coefficients of the spherical polynomial
  42912. */
  42913. this.zz = BABYLON.Vector3.Zero();
  42914. /**
  42915. * The xy coefficients of the spherical polynomial
  42916. */
  42917. this.xy = BABYLON.Vector3.Zero();
  42918. /**
  42919. * The yz coefficients of the spherical polynomial
  42920. */
  42921. this.yz = BABYLON.Vector3.Zero();
  42922. /**
  42923. * The zx coefficients of the spherical polynomial
  42924. */
  42925. this.zx = BABYLON.Vector3.Zero();
  42926. }
  42927. /**
  42928. * Adds an ambient color to the spherical polynomial
  42929. * @param color the color to add
  42930. */
  42931. SphericalPolynomial.prototype.addAmbient = function (color) {
  42932. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42933. this.xx = this.xx.add(colorVector);
  42934. this.yy = this.yy.add(colorVector);
  42935. this.zz = this.zz.add(colorVector);
  42936. };
  42937. /**
  42938. * Scales the spherical polynomial by the given amount
  42939. * @param scale the amount to scale
  42940. */
  42941. SphericalPolynomial.prototype.scale = function (scale) {
  42942. this.x = this.x.scale(scale);
  42943. this.y = this.y.scale(scale);
  42944. this.z = this.z.scale(scale);
  42945. this.xx = this.xx.scale(scale);
  42946. this.yy = this.yy.scale(scale);
  42947. this.zz = this.zz.scale(scale);
  42948. this.yz = this.yz.scale(scale);
  42949. this.zx = this.zx.scale(scale);
  42950. this.xy = this.xy.scale(scale);
  42951. };
  42952. /**
  42953. * Gets the spherical polynomial from harmonics
  42954. * @param harmonics the spherical harmonics
  42955. * @returns the spherical polynomial
  42956. */
  42957. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42958. var result = new SphericalPolynomial();
  42959. result.x = harmonics.l11.scale(1.02333);
  42960. result.y = harmonics.l1_1.scale(1.02333);
  42961. result.z = harmonics.l10.scale(1.02333);
  42962. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42963. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42964. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42965. result.yz = harmonics.l2_1.scale(0.858086);
  42966. result.zx = harmonics.l21.scale(0.858086);
  42967. result.xy = harmonics.l2_2.scale(0.858086);
  42968. result.scale(1.0 / Math.PI);
  42969. return result;
  42970. };
  42971. /**
  42972. * Constructs a spherical polynomial from an array.
  42973. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42974. * @returns the spherical polynomial
  42975. */
  42976. SphericalPolynomial.FromArray = function (data) {
  42977. var sp = new SphericalPolynomial();
  42978. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42979. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42980. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42981. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42982. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42983. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42984. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42985. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42986. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42987. return sp;
  42988. };
  42989. return SphericalPolynomial;
  42990. }());
  42991. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42992. /**
  42993. * Class representing spherical harmonics coefficients to the 3rd degree
  42994. */
  42995. var SphericalHarmonics = /** @class */ (function () {
  42996. function SphericalHarmonics() {
  42997. /**
  42998. * The l0,0 coefficients of the spherical harmonics
  42999. */
  43000. this.l00 = BABYLON.Vector3.Zero();
  43001. /**
  43002. * The l1,-1 coefficients of the spherical harmonics
  43003. */
  43004. this.l1_1 = BABYLON.Vector3.Zero();
  43005. /**
  43006. * The l1,0 coefficients of the spherical harmonics
  43007. */
  43008. this.l10 = BABYLON.Vector3.Zero();
  43009. /**
  43010. * The l1,1 coefficients of the spherical harmonics
  43011. */
  43012. this.l11 = BABYLON.Vector3.Zero();
  43013. /**
  43014. * The l2,-2 coefficients of the spherical harmonics
  43015. */
  43016. this.l2_2 = BABYLON.Vector3.Zero();
  43017. /**
  43018. * The l2,-1 coefficients of the spherical harmonics
  43019. */
  43020. this.l2_1 = BABYLON.Vector3.Zero();
  43021. /**
  43022. * The l2,0 coefficients of the spherical harmonics
  43023. */
  43024. this.l20 = BABYLON.Vector3.Zero();
  43025. /**
  43026. * The l2,1 coefficients of the spherical harmonics
  43027. */
  43028. this.l21 = BABYLON.Vector3.Zero();
  43029. /**
  43030. * The l2,2 coefficients of the spherical harmonics
  43031. */
  43032. this.lL22 = BABYLON.Vector3.Zero();
  43033. }
  43034. /**
  43035. * Adds a light to the spherical harmonics
  43036. * @param direction the direction of the light
  43037. * @param color the color of the light
  43038. * @param deltaSolidAngle the delta solid angle of the light
  43039. */
  43040. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43041. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43042. var c = colorVector.scale(deltaSolidAngle);
  43043. this.l00 = this.l00.add(c.scale(0.282095));
  43044. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43045. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43046. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43047. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43048. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43049. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43050. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43051. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43052. };
  43053. /**
  43054. * Scales the spherical harmonics by the given amount
  43055. * @param scale the amount to scale
  43056. */
  43057. SphericalHarmonics.prototype.scale = function (scale) {
  43058. this.l00 = this.l00.scale(scale);
  43059. this.l1_1 = this.l1_1.scale(scale);
  43060. this.l10 = this.l10.scale(scale);
  43061. this.l11 = this.l11.scale(scale);
  43062. this.l2_2 = this.l2_2.scale(scale);
  43063. this.l2_1 = this.l2_1.scale(scale);
  43064. this.l20 = this.l20.scale(scale);
  43065. this.l21 = this.l21.scale(scale);
  43066. this.lL22 = this.lL22.scale(scale);
  43067. };
  43068. /**
  43069. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43070. *
  43071. * ```
  43072. * E_lm = A_l * L_lm
  43073. * ```
  43074. *
  43075. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43076. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43077. * the scaling factors are given in equation 9.
  43078. */
  43079. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43080. // Constant (Band 0)
  43081. this.l00 = this.l00.scale(3.141593);
  43082. // Linear (Band 1)
  43083. this.l1_1 = this.l1_1.scale(2.094395);
  43084. this.l10 = this.l10.scale(2.094395);
  43085. this.l11 = this.l11.scale(2.094395);
  43086. // Quadratic (Band 2)
  43087. this.l2_2 = this.l2_2.scale(0.785398);
  43088. this.l2_1 = this.l2_1.scale(0.785398);
  43089. this.l20 = this.l20.scale(0.785398);
  43090. this.l21 = this.l21.scale(0.785398);
  43091. this.lL22 = this.lL22.scale(0.785398);
  43092. };
  43093. /**
  43094. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43095. *
  43096. * ```
  43097. * L = (1/pi) * E * rho
  43098. * ```
  43099. *
  43100. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43101. */
  43102. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43103. this.scale(1.0 / Math.PI);
  43104. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43105. // (The pixel shader must apply albedo after texture fetches, etc).
  43106. };
  43107. /**
  43108. * Gets the spherical harmonics from polynomial
  43109. * @param polynomial the spherical polynomial
  43110. * @returns the spherical harmonics
  43111. */
  43112. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43113. var result = new SphericalHarmonics();
  43114. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43115. result.l1_1 = polynomial.y.scale(0.977204);
  43116. result.l10 = polynomial.z.scale(0.977204);
  43117. result.l11 = polynomial.x.scale(0.977204);
  43118. result.l2_2 = polynomial.xy.scale(1.16538);
  43119. result.l2_1 = polynomial.yz.scale(1.16538);
  43120. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43121. result.l21 = polynomial.zx.scale(1.16538);
  43122. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43123. result.scale(Math.PI);
  43124. return result;
  43125. };
  43126. /**
  43127. * Constructs a spherical harmonics from an array.
  43128. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43129. * @returns the spherical harmonics
  43130. */
  43131. SphericalHarmonics.FromArray = function (data) {
  43132. var sh = new SphericalHarmonics();
  43133. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43134. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43135. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43136. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43137. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43138. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43139. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43140. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43141. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43142. return sh;
  43143. };
  43144. return SphericalHarmonics;
  43145. }());
  43146. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43147. })(BABYLON || (BABYLON = {}));
  43148. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43149. var BABYLON;
  43150. (function (BABYLON) {
  43151. var FileFaceOrientation = /** @class */ (function () {
  43152. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43153. this.name = name;
  43154. this.worldAxisForNormal = worldAxisForNormal;
  43155. this.worldAxisForFileX = worldAxisForFileX;
  43156. this.worldAxisForFileY = worldAxisForFileY;
  43157. }
  43158. return FileFaceOrientation;
  43159. }());
  43160. ;
  43161. /**
  43162. * Helper class dealing with the extraction of spherical polynomial dataArray
  43163. * from a cube map.
  43164. */
  43165. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43166. function CubeMapToSphericalPolynomialTools() {
  43167. }
  43168. /**
  43169. * Converts a texture to the according Spherical Polynomial data.
  43170. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43171. *
  43172. * @param texture The texture to extract the information from.
  43173. * @return The Spherical Polynomial data.
  43174. */
  43175. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43176. if (!texture.isCube) {
  43177. // Only supports cube Textures currently.
  43178. return null;
  43179. }
  43180. var size = texture.getSize().width;
  43181. var right = texture.readPixels(0);
  43182. var left = texture.readPixels(1);
  43183. var up;
  43184. var down;
  43185. if (texture.isRenderTarget) {
  43186. up = texture.readPixels(3);
  43187. down = texture.readPixels(2);
  43188. }
  43189. else {
  43190. up = texture.readPixels(2);
  43191. down = texture.readPixels(3);
  43192. }
  43193. var front = texture.readPixels(4);
  43194. var back = texture.readPixels(5);
  43195. var gammaSpace = texture.gammaSpace;
  43196. // Always read as RGBA.
  43197. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43198. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43199. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43200. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43201. }
  43202. var cubeInfo = {
  43203. size: size,
  43204. right: right,
  43205. left: left,
  43206. up: up,
  43207. down: down,
  43208. front: front,
  43209. back: back,
  43210. format: format,
  43211. type: type,
  43212. gammaSpace: gammaSpace,
  43213. };
  43214. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43215. };
  43216. /**
  43217. * Converts a cubemap to the according Spherical Polynomial data.
  43218. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43219. *
  43220. * @param cubeInfo The Cube map to extract the information from.
  43221. * @return The Spherical Polynomial data.
  43222. */
  43223. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43224. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43225. var totalSolidAngle = 0.0;
  43226. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43227. var du = 2.0 / cubeInfo.size;
  43228. var dv = du;
  43229. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43230. var minUV = du * 0.5 - 1.0;
  43231. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43232. var fileFace = this.FileFaces[faceIndex];
  43233. var dataArray = cubeInfo[fileFace.name];
  43234. var v = minUV;
  43235. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43236. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43237. // Because SP is still linear, so summation is fine in that basis.
  43238. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43239. for (var y = 0; y < cubeInfo.size; y++) {
  43240. var u = minUV;
  43241. for (var x = 0; x < cubeInfo.size; x++) {
  43242. // World direction (not normalised)
  43243. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43244. worldDirection.normalize();
  43245. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43246. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43247. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43248. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43249. // Handle Integer types.
  43250. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43251. r /= 255;
  43252. g /= 255;
  43253. b /= 255;
  43254. }
  43255. // Handle Gamma space textures.
  43256. if (cubeInfo.gammaSpace) {
  43257. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43258. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43259. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43260. }
  43261. var color = new BABYLON.Color3(r, g, b);
  43262. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43263. totalSolidAngle += deltaSolidAngle;
  43264. u += du;
  43265. }
  43266. v += dv;
  43267. }
  43268. }
  43269. // Solid angle for entire sphere is 4*pi
  43270. var sphereSolidAngle = 4.0 * Math.PI;
  43271. // Adjust the solid angle to allow for how many faces we processed.
  43272. var facesProcessed = 6.0;
  43273. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43274. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43275. // This is needed because the numerical integration over the cube uses a
  43276. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43277. // and also to compensate for accumulative error due to float precision in the summation.
  43278. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43279. sphericalHarmonics.scale(correctionFactor);
  43280. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43281. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43282. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43283. };
  43284. CubeMapToSphericalPolynomialTools.FileFaces = [
  43285. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43286. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43287. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43288. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43289. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43290. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43291. ];
  43292. return CubeMapToSphericalPolynomialTools;
  43293. }());
  43294. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43295. })(BABYLON || (BABYLON = {}));
  43296. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43297. var BABYLON;
  43298. (function (BABYLON) {
  43299. /**
  43300. * Manages the defines for the PBR Material.
  43301. * @hiddenChildren
  43302. */
  43303. var PBRMaterialDefines = /** @class */ (function (_super) {
  43304. __extends(PBRMaterialDefines, _super);
  43305. /**
  43306. * Initializes the PBR Material defines.
  43307. */
  43308. function PBRMaterialDefines() {
  43309. var _this = _super.call(this) || this;
  43310. _this.PBR = true;
  43311. _this.MAINUV1 = false;
  43312. _this.MAINUV2 = false;
  43313. _this.UV1 = false;
  43314. _this.UV2 = false;
  43315. _this.ALBEDO = false;
  43316. _this.ALBEDODIRECTUV = 0;
  43317. _this.VERTEXCOLOR = false;
  43318. _this.AMBIENT = false;
  43319. _this.AMBIENTDIRECTUV = 0;
  43320. _this.AMBIENTINGRAYSCALE = false;
  43321. _this.OPACITY = false;
  43322. _this.VERTEXALPHA = false;
  43323. _this.OPACITYDIRECTUV = 0;
  43324. _this.OPACITYRGB = false;
  43325. _this.ALPHATEST = false;
  43326. _this.DEPTHPREPASS = false;
  43327. _this.ALPHABLEND = false;
  43328. _this.ALPHAFROMALBEDO = false;
  43329. _this.ALPHATESTVALUE = "0.5";
  43330. _this.SPECULAROVERALPHA = false;
  43331. _this.RADIANCEOVERALPHA = false;
  43332. _this.ALPHAFRESNEL = false;
  43333. _this.LINEARALPHAFRESNEL = false;
  43334. _this.PREMULTIPLYALPHA = false;
  43335. _this.EMISSIVE = false;
  43336. _this.EMISSIVEDIRECTUV = 0;
  43337. _this.REFLECTIVITY = false;
  43338. _this.REFLECTIVITYDIRECTUV = 0;
  43339. _this.SPECULARTERM = false;
  43340. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43341. _this.MICROSURFACEAUTOMATIC = false;
  43342. _this.LODBASEDMICROSFURACE = false;
  43343. _this.MICROSURFACEMAP = false;
  43344. _this.MICROSURFACEMAPDIRECTUV = 0;
  43345. _this.METALLICWORKFLOW = false;
  43346. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43347. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43348. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43349. _this.AOSTOREINMETALMAPRED = false;
  43350. _this.ENVIRONMENTBRDF = false;
  43351. _this.NORMAL = false;
  43352. _this.TANGENT = false;
  43353. _this.BUMP = false;
  43354. _this.BUMPDIRECTUV = 0;
  43355. _this.OBJECTSPACE_NORMALMAP = false;
  43356. _this.PARALLAX = false;
  43357. _this.PARALLAXOCCLUSION = false;
  43358. _this.NORMALXYSCALE = true;
  43359. _this.LIGHTMAP = false;
  43360. _this.LIGHTMAPDIRECTUV = 0;
  43361. _this.USELIGHTMAPASSHADOWMAP = false;
  43362. _this.GAMMALIGHTMAP = false;
  43363. _this.REFLECTION = false;
  43364. _this.REFLECTIONMAP_3D = false;
  43365. _this.REFLECTIONMAP_SPHERICAL = false;
  43366. _this.REFLECTIONMAP_PLANAR = false;
  43367. _this.REFLECTIONMAP_CUBIC = false;
  43368. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43369. _this.REFLECTIONMAP_PROJECTION = false;
  43370. _this.REFLECTIONMAP_SKYBOX = false;
  43371. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43372. _this.REFLECTIONMAP_EXPLICIT = false;
  43373. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43374. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43375. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43376. _this.INVERTCUBICMAP = false;
  43377. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43378. _this.USESPHERICALINVERTEX = false;
  43379. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43380. _this.LODINREFLECTIONALPHA = false;
  43381. _this.GAMMAREFLECTION = false;
  43382. _this.RGBDREFLECTION = false;
  43383. _this.RADIANCEOCCLUSION = false;
  43384. _this.HORIZONOCCLUSION = false;
  43385. _this.REFRACTION = false;
  43386. _this.REFRACTIONMAP_3D = false;
  43387. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43388. _this.LODINREFRACTIONALPHA = false;
  43389. _this.GAMMAREFRACTION = false;
  43390. _this.RGBDREFRACTION = false;
  43391. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43392. _this.INSTANCES = false;
  43393. _this.NUM_BONE_INFLUENCERS = 0;
  43394. _this.BonesPerMesh = 0;
  43395. _this.NONUNIFORMSCALING = false;
  43396. _this.MORPHTARGETS = false;
  43397. _this.MORPHTARGETS_NORMAL = false;
  43398. _this.MORPHTARGETS_TANGENT = false;
  43399. _this.NUM_MORPH_INFLUENCERS = 0;
  43400. _this.IMAGEPROCESSING = false;
  43401. _this.VIGNETTE = false;
  43402. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43403. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43404. _this.TONEMAPPING = false;
  43405. _this.TONEMAPPING_ACES = false;
  43406. _this.CONTRAST = false;
  43407. _this.COLORCURVES = false;
  43408. _this.COLORGRADING = false;
  43409. _this.COLORGRADING3D = false;
  43410. _this.SAMPLER3DGREENDEPTH = false;
  43411. _this.SAMPLER3DBGRMAP = false;
  43412. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43413. _this.EXPOSURE = false;
  43414. _this.USEPHYSICALLIGHTFALLOFF = false;
  43415. _this.USEGLTFLIGHTFALLOFF = false;
  43416. _this.TWOSIDEDLIGHTING = false;
  43417. _this.SHADOWFLOAT = false;
  43418. _this.CLIPPLANE = false;
  43419. _this.CLIPPLANE2 = false;
  43420. _this.CLIPPLANE3 = false;
  43421. _this.CLIPPLANE4 = false;
  43422. _this.POINTSIZE = false;
  43423. _this.FOG = false;
  43424. _this.LOGARITHMICDEPTH = false;
  43425. _this.FORCENORMALFORWARD = false;
  43426. _this.SPECULARAA = false;
  43427. _this.UNLIT = false;
  43428. _this.rebuild();
  43429. return _this;
  43430. }
  43431. /**
  43432. * Resets the PBR Material defines.
  43433. */
  43434. PBRMaterialDefines.prototype.reset = function () {
  43435. _super.prototype.reset.call(this);
  43436. this.ALPHATESTVALUE = "0.5";
  43437. this.PBR = true;
  43438. };
  43439. return PBRMaterialDefines;
  43440. }(BABYLON.MaterialDefines));
  43441. /**
  43442. * The Physically based material base class of BJS.
  43443. *
  43444. * This offers the main features of a standard PBR material.
  43445. * For more information, please refer to the documentation :
  43446. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43447. */
  43448. var PBRBaseMaterial = /** @class */ (function (_super) {
  43449. __extends(PBRBaseMaterial, _super);
  43450. /**
  43451. * Instantiates a new PBRMaterial instance.
  43452. *
  43453. * @param name The material name
  43454. * @param scene The scene the material will be use in.
  43455. */
  43456. function PBRBaseMaterial(name, scene) {
  43457. var _this = _super.call(this, name, scene) || this;
  43458. /**
  43459. * Intensity of the direct lights e.g. the four lights available in your scene.
  43460. * This impacts both the direct diffuse and specular highlights.
  43461. */
  43462. _this._directIntensity = 1.0;
  43463. /**
  43464. * Intensity of the emissive part of the material.
  43465. * This helps controlling the emissive effect without modifying the emissive color.
  43466. */
  43467. _this._emissiveIntensity = 1.0;
  43468. /**
  43469. * Intensity of the environment e.g. how much the environment will light the object
  43470. * either through harmonics for rough material or through the refelction for shiny ones.
  43471. */
  43472. _this._environmentIntensity = 1.0;
  43473. /**
  43474. * This is a special control allowing the reduction of the specular highlights coming from the
  43475. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43476. */
  43477. _this._specularIntensity = 1.0;
  43478. /**
  43479. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43480. */
  43481. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43482. /**
  43483. * Debug Control allowing disabling the bump map on this material.
  43484. */
  43485. _this._disableBumpMap = false;
  43486. /**
  43487. * AKA Occlusion Texture Intensity in other nomenclature.
  43488. */
  43489. _this._ambientTextureStrength = 1.0;
  43490. /**
  43491. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43492. * 1 means it completely occludes it
  43493. * 0 mean it has no impact
  43494. */
  43495. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43496. /**
  43497. * The color of a material in ambient lighting.
  43498. */
  43499. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43500. /**
  43501. * AKA Diffuse Color in other nomenclature.
  43502. */
  43503. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43504. /**
  43505. * AKA Specular Color in other nomenclature.
  43506. */
  43507. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43508. /**
  43509. * The color applied when light is reflected from a material.
  43510. */
  43511. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43512. /**
  43513. * The color applied when light is emitted from a material.
  43514. */
  43515. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43516. /**
  43517. * AKA Glossiness in other nomenclature.
  43518. */
  43519. _this._microSurface = 0.9;
  43520. /**
  43521. * source material index of refraction (IOR)' / 'destination material IOR.
  43522. */
  43523. _this._indexOfRefraction = 0.66;
  43524. /**
  43525. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43526. */
  43527. _this._invertRefractionY = false;
  43528. /**
  43529. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43530. * Materials half opaque for instance using refraction could benefit from this control.
  43531. */
  43532. _this._linkRefractionWithTransparency = false;
  43533. /**
  43534. * Specifies that the material will use the light map as a show map.
  43535. */
  43536. _this._useLightmapAsShadowmap = false;
  43537. /**
  43538. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43539. * makes the reflect vector face the model (under horizon).
  43540. */
  43541. _this._useHorizonOcclusion = true;
  43542. /**
  43543. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43544. * too much the area relying on ambient texture to define their ambient occlusion.
  43545. */
  43546. _this._useRadianceOcclusion = true;
  43547. /**
  43548. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43549. */
  43550. _this._useAlphaFromAlbedoTexture = false;
  43551. /**
  43552. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43553. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43554. */
  43555. _this._useSpecularOverAlpha = true;
  43556. /**
  43557. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43558. */
  43559. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43560. /**
  43561. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43562. */
  43563. _this._useRoughnessFromMetallicTextureAlpha = true;
  43564. /**
  43565. * Specifies if the metallic texture contains the roughness information in its green channel.
  43566. */
  43567. _this._useRoughnessFromMetallicTextureGreen = false;
  43568. /**
  43569. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43570. */
  43571. _this._useMetallnessFromMetallicTextureBlue = false;
  43572. /**
  43573. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43574. */
  43575. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43576. /**
  43577. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43578. */
  43579. _this._useAmbientInGrayScale = false;
  43580. /**
  43581. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43582. * The material will try to infer what glossiness each pixel should be.
  43583. */
  43584. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43585. /**
  43586. * Defines the falloff type used in this material.
  43587. * It by default is Physical.
  43588. */
  43589. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43590. /**
  43591. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43592. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43593. */
  43594. _this._useRadianceOverAlpha = true;
  43595. /**
  43596. * Allows using an object space normal map (instead of tangent space).
  43597. */
  43598. _this._useObjectSpaceNormalMap = false;
  43599. /**
  43600. * Allows using the bump map in parallax mode.
  43601. */
  43602. _this._useParallax = false;
  43603. /**
  43604. * Allows using the bump map in parallax occlusion mode.
  43605. */
  43606. _this._useParallaxOcclusion = false;
  43607. /**
  43608. * Controls the scale bias of the parallax mode.
  43609. */
  43610. _this._parallaxScaleBias = 0.05;
  43611. /**
  43612. * If sets to true, disables all the lights affecting the material.
  43613. */
  43614. _this._disableLighting = false;
  43615. /**
  43616. * Number of Simultaneous lights allowed on the material.
  43617. */
  43618. _this._maxSimultaneousLights = 4;
  43619. /**
  43620. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43621. */
  43622. _this._invertNormalMapX = false;
  43623. /**
  43624. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43625. */
  43626. _this._invertNormalMapY = false;
  43627. /**
  43628. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43629. */
  43630. _this._twoSidedLighting = false;
  43631. /**
  43632. * Defines the alpha limits in alpha test mode.
  43633. */
  43634. _this._alphaCutOff = 0.4;
  43635. /**
  43636. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43637. */
  43638. _this._forceAlphaTest = false;
  43639. /**
  43640. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43641. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43642. */
  43643. _this._useAlphaFresnel = false;
  43644. /**
  43645. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43646. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43647. */
  43648. _this._useLinearAlphaFresnel = false;
  43649. /**
  43650. * The transparency mode of the material.
  43651. */
  43652. _this._transparencyMode = null;
  43653. /**
  43654. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43655. * from cos thetav and roughness:
  43656. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43657. */
  43658. _this._environmentBRDFTexture = null;
  43659. /**
  43660. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43661. */
  43662. _this._forceIrradianceInFragment = false;
  43663. /**
  43664. * Force normal to face away from face.
  43665. */
  43666. _this._forceNormalForward = false;
  43667. /**
  43668. * Enables specular anti aliasing in the PBR shader.
  43669. * It will both interacts on the Geometry for analytical and IBL lighting.
  43670. * It also prefilter the roughness map based on the bump values.
  43671. */
  43672. _this._enableSpecularAntiAliasing = false;
  43673. /**
  43674. * Stores the available render targets.
  43675. */
  43676. _this._renderTargets = new BABYLON.SmartArray(16);
  43677. /**
  43678. * Sets the global ambient color for the material used in lighting calculations.
  43679. */
  43680. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43681. /**
  43682. * If set to true, no lighting calculations will be applied.
  43683. */
  43684. _this._unlit = false;
  43685. // Setup the default processing configuration to the scene.
  43686. _this._attachImageProcessingConfiguration(null);
  43687. _this.getRenderTargetTextures = function () {
  43688. _this._renderTargets.reset();
  43689. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43690. _this._renderTargets.push(_this._reflectionTexture);
  43691. }
  43692. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43693. _this._renderTargets.push(_this._refractionTexture);
  43694. }
  43695. return _this._renderTargets;
  43696. };
  43697. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43698. return _this;
  43699. }
  43700. /**
  43701. * Attaches a new image processing configuration to the PBR Material.
  43702. * @param configuration
  43703. */
  43704. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43705. var _this = this;
  43706. if (configuration === this._imageProcessingConfiguration) {
  43707. return;
  43708. }
  43709. // Detaches observer.
  43710. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43711. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43712. }
  43713. // Pick the scene configuration if needed.
  43714. if (!configuration) {
  43715. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43716. }
  43717. else {
  43718. this._imageProcessingConfiguration = configuration;
  43719. }
  43720. // Attaches observer.
  43721. if (this._imageProcessingConfiguration) {
  43722. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43723. _this._markAllSubMeshesAsImageProcessingDirty();
  43724. });
  43725. }
  43726. };
  43727. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43728. /**
  43729. * Gets a boolean indicating that current material needs to register RTT
  43730. */
  43731. get: function () {
  43732. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43733. return true;
  43734. }
  43735. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43736. return true;
  43737. }
  43738. return false;
  43739. },
  43740. enumerable: true,
  43741. configurable: true
  43742. });
  43743. /**
  43744. * Gets the name of the material class.
  43745. */
  43746. PBRBaseMaterial.prototype.getClassName = function () {
  43747. return "PBRBaseMaterial";
  43748. };
  43749. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43750. /**
  43751. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43752. */
  43753. get: function () {
  43754. return this._useLogarithmicDepth;
  43755. },
  43756. /**
  43757. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43758. */
  43759. set: function (value) {
  43760. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43761. },
  43762. enumerable: true,
  43763. configurable: true
  43764. });
  43765. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43766. /**
  43767. * Gets the current transparency mode.
  43768. */
  43769. get: function () {
  43770. return this._transparencyMode;
  43771. },
  43772. /**
  43773. * Sets the transparency mode of the material.
  43774. *
  43775. * | Value | Type | Description |
  43776. * | ----- | ----------------------------------- | ----------- |
  43777. * | 0 | OPAQUE | |
  43778. * | 1 | ALPHATEST | |
  43779. * | 2 | ALPHABLEND | |
  43780. * | 3 | ALPHATESTANDBLEND | |
  43781. *
  43782. */
  43783. set: function (value) {
  43784. if (this._transparencyMode === value) {
  43785. return;
  43786. }
  43787. this._transparencyMode = value;
  43788. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43789. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43790. },
  43791. enumerable: true,
  43792. configurable: true
  43793. });
  43794. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43795. /**
  43796. * Returns true if alpha blending should be disabled.
  43797. */
  43798. get: function () {
  43799. return (this._linkRefractionWithTransparency ||
  43800. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43801. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43802. },
  43803. enumerable: true,
  43804. configurable: true
  43805. });
  43806. /**
  43807. * Specifies whether or not this material should be rendered in alpha blend mode.
  43808. */
  43809. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43810. if (this._disableAlphaBlending) {
  43811. return false;
  43812. }
  43813. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43814. };
  43815. /**
  43816. * Specifies if the mesh will require alpha blending.
  43817. * @param mesh - BJS mesh.
  43818. */
  43819. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43820. if (this._disableAlphaBlending) {
  43821. return false;
  43822. }
  43823. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43824. };
  43825. /**
  43826. * Specifies whether or not this material should be rendered in alpha test mode.
  43827. */
  43828. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43829. if (this._forceAlphaTest) {
  43830. return true;
  43831. }
  43832. if (this._linkRefractionWithTransparency) {
  43833. return false;
  43834. }
  43835. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43836. };
  43837. /**
  43838. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43839. */
  43840. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43841. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43842. };
  43843. /**
  43844. * Gets the texture used for the alpha test.
  43845. */
  43846. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43847. return this._albedoTexture;
  43848. };
  43849. /**
  43850. * Specifies that the submesh is ready to be used.
  43851. * @param mesh - BJS mesh.
  43852. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43853. * @param useInstances - Specifies that instances should be used.
  43854. * @returns - boolean indicating that the submesh is ready or not.
  43855. */
  43856. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43857. if (subMesh.effect && this.isFrozen) {
  43858. if (this._wasPreviouslyReady) {
  43859. return true;
  43860. }
  43861. }
  43862. if (!subMesh._materialDefines) {
  43863. subMesh._materialDefines = new PBRMaterialDefines();
  43864. }
  43865. var defines = subMesh._materialDefines;
  43866. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43867. if (defines._renderId === this.getScene().getRenderId()) {
  43868. return true;
  43869. }
  43870. }
  43871. var scene = this.getScene();
  43872. var engine = scene.getEngine();
  43873. if (defines._areTexturesDirty) {
  43874. if (scene.texturesEnabled) {
  43875. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43876. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43877. return false;
  43878. }
  43879. }
  43880. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43881. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43882. return false;
  43883. }
  43884. }
  43885. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43886. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43887. return false;
  43888. }
  43889. }
  43890. var reflectionTexture = this._getReflectionTexture();
  43891. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43892. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43893. return false;
  43894. }
  43895. }
  43896. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43897. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43898. return false;
  43899. }
  43900. }
  43901. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43902. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43903. return false;
  43904. }
  43905. }
  43906. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43907. if (this._metallicTexture) {
  43908. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43909. return false;
  43910. }
  43911. }
  43912. else if (this._reflectivityTexture) {
  43913. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43914. return false;
  43915. }
  43916. }
  43917. if (this._microSurfaceTexture) {
  43918. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43919. return false;
  43920. }
  43921. }
  43922. }
  43923. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43924. // Bump texture cannot be not blocking.
  43925. if (!this._bumpTexture.isReady()) {
  43926. return false;
  43927. }
  43928. }
  43929. var refractionTexture = this._getRefractionTexture();
  43930. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43931. if (!refractionTexture.isReadyOrNotBlocking()) {
  43932. return false;
  43933. }
  43934. }
  43935. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43936. // This is blocking.
  43937. if (!this._environmentBRDFTexture.isReady()) {
  43938. return false;
  43939. }
  43940. }
  43941. }
  43942. }
  43943. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43944. if (!this._imageProcessingConfiguration.isReady()) {
  43945. return false;
  43946. }
  43947. }
  43948. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43949. mesh.createNormals(true);
  43950. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43951. }
  43952. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43953. if (effect) {
  43954. scene.resetCachedMaterial();
  43955. subMesh.setEffect(effect, defines);
  43956. this.buildUniformLayout();
  43957. }
  43958. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43959. return false;
  43960. }
  43961. defines._renderId = scene.getRenderId();
  43962. this._wasPreviouslyReady = true;
  43963. return true;
  43964. };
  43965. /**
  43966. * Specifies if the material uses metallic roughness workflow.
  43967. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43968. */
  43969. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43970. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43971. return true;
  43972. }
  43973. return false;
  43974. };
  43975. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43976. if (onCompiled === void 0) { onCompiled = null; }
  43977. if (onError === void 0) { onError = null; }
  43978. if (useInstances === void 0) { useInstances = null; }
  43979. if (useClipPlane === void 0) { useClipPlane = null; }
  43980. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43981. if (!defines.isDirty) {
  43982. return null;
  43983. }
  43984. defines.markAsProcessed();
  43985. var scene = this.getScene();
  43986. var engine = scene.getEngine();
  43987. // Fallbacks
  43988. var fallbacks = new BABYLON.EffectFallbacks();
  43989. var fallbackRank = 0;
  43990. if (defines.USESPHERICALINVERTEX) {
  43991. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43992. }
  43993. if (defines.FOG) {
  43994. fallbacks.addFallback(fallbackRank, "FOG");
  43995. }
  43996. if (defines.SPECULARAA) {
  43997. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43998. }
  43999. if (defines.POINTSIZE) {
  44000. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44001. }
  44002. if (defines.LOGARITHMICDEPTH) {
  44003. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44004. }
  44005. if (defines.PARALLAX) {
  44006. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44007. }
  44008. if (defines.PARALLAXOCCLUSION) {
  44009. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44010. }
  44011. if (defines.ENVIRONMENTBRDF) {
  44012. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44013. }
  44014. if (defines.TANGENT) {
  44015. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44016. }
  44017. if (defines.BUMP) {
  44018. fallbacks.addFallback(fallbackRank++, "BUMP");
  44019. }
  44020. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44021. if (defines.SPECULARTERM) {
  44022. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44023. }
  44024. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44025. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44026. }
  44027. if (defines.LIGHTMAP) {
  44028. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44029. }
  44030. if (defines.NORMAL) {
  44031. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44032. }
  44033. if (defines.AMBIENT) {
  44034. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44035. }
  44036. if (defines.EMISSIVE) {
  44037. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44038. }
  44039. if (defines.VERTEXCOLOR) {
  44040. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44041. }
  44042. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44043. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44044. }
  44045. if (defines.MORPHTARGETS) {
  44046. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44047. }
  44048. //Attributes
  44049. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44050. if (defines.NORMAL) {
  44051. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44052. }
  44053. if (defines.TANGENT) {
  44054. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44055. }
  44056. if (defines.UV1) {
  44057. attribs.push(BABYLON.VertexBuffer.UVKind);
  44058. }
  44059. if (defines.UV2) {
  44060. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44061. }
  44062. if (defines.VERTEXCOLOR) {
  44063. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44064. }
  44065. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44066. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44067. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44068. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44069. "vFogInfos", "vFogColor", "pointSize",
  44070. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44071. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44072. "mBones",
  44073. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44074. "vLightingIntensity",
  44075. "logarithmicDepthConstant",
  44076. "vSphericalX", "vSphericalY", "vSphericalZ",
  44077. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44078. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44079. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44080. "vTangentSpaceParams"
  44081. ];
  44082. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44083. "bumpSampler", "lightmapSampler", "opacitySampler",
  44084. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44085. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44086. "microSurfaceSampler", "environmentBrdfSampler"];
  44087. var uniformBuffers = ["Material", "Scene"];
  44088. if (BABYLON.ImageProcessingConfiguration) {
  44089. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44090. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44091. }
  44092. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44093. uniformsNames: uniforms,
  44094. uniformBuffersNames: uniformBuffers,
  44095. samplers: samplers,
  44096. defines: defines,
  44097. maxSimultaneousLights: this._maxSimultaneousLights
  44098. });
  44099. var join = defines.toString();
  44100. return engine.createEffect("pbr", {
  44101. attributes: attribs,
  44102. uniformsNames: uniforms,
  44103. uniformBuffersNames: uniformBuffers,
  44104. samplers: samplers,
  44105. defines: join,
  44106. fallbacks: fallbacks,
  44107. onCompiled: onCompiled,
  44108. onError: onError,
  44109. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44110. }, engine);
  44111. };
  44112. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44113. if (useInstances === void 0) { useInstances = null; }
  44114. if (useClipPlane === void 0) { useClipPlane = null; }
  44115. var scene = this.getScene();
  44116. var engine = scene.getEngine();
  44117. // Lights
  44118. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44119. defines._needNormals = true;
  44120. // Textures
  44121. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44122. if (defines._areTexturesDirty) {
  44123. defines._needUVs = false;
  44124. if (scene.texturesEnabled) {
  44125. if (scene.getEngine().getCaps().textureLOD) {
  44126. defines.LODBASEDMICROSFURACE = true;
  44127. }
  44128. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44129. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44130. }
  44131. else {
  44132. defines.ALBEDO = false;
  44133. }
  44134. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44135. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44136. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44137. }
  44138. else {
  44139. defines.AMBIENT = false;
  44140. }
  44141. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44142. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44143. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44144. }
  44145. else {
  44146. defines.OPACITY = false;
  44147. }
  44148. var reflectionTexture = this._getReflectionTexture();
  44149. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44150. defines.REFLECTION = true;
  44151. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44152. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44153. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44154. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44155. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44156. defines.INVERTCUBICMAP = true;
  44157. }
  44158. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44159. switch (reflectionTexture.coordinatesMode) {
  44160. case BABYLON.Texture.EXPLICIT_MODE:
  44161. defines.REFLECTIONMAP_EXPLICIT = true;
  44162. break;
  44163. case BABYLON.Texture.PLANAR_MODE:
  44164. defines.REFLECTIONMAP_PLANAR = true;
  44165. break;
  44166. case BABYLON.Texture.PROJECTION_MODE:
  44167. defines.REFLECTIONMAP_PROJECTION = true;
  44168. break;
  44169. case BABYLON.Texture.SKYBOX_MODE:
  44170. defines.REFLECTIONMAP_SKYBOX = true;
  44171. break;
  44172. case BABYLON.Texture.SPHERICAL_MODE:
  44173. defines.REFLECTIONMAP_SPHERICAL = true;
  44174. break;
  44175. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44176. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44177. break;
  44178. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44179. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44180. break;
  44181. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44182. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44183. break;
  44184. case BABYLON.Texture.CUBIC_MODE:
  44185. case BABYLON.Texture.INVCUBIC_MODE:
  44186. default:
  44187. defines.REFLECTIONMAP_CUBIC = true;
  44188. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44189. break;
  44190. }
  44191. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44192. if (reflectionTexture.sphericalPolynomial) {
  44193. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44194. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44195. defines.USESPHERICALINVERTEX = false;
  44196. }
  44197. else {
  44198. defines.USESPHERICALINVERTEX = true;
  44199. }
  44200. }
  44201. }
  44202. else {
  44203. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44204. }
  44205. }
  44206. else {
  44207. defines.REFLECTION = false;
  44208. defines.REFLECTIONMAP_3D = false;
  44209. defines.REFLECTIONMAP_SPHERICAL = false;
  44210. defines.REFLECTIONMAP_PLANAR = false;
  44211. defines.REFLECTIONMAP_CUBIC = false;
  44212. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44213. defines.REFLECTIONMAP_PROJECTION = false;
  44214. defines.REFLECTIONMAP_SKYBOX = false;
  44215. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44216. defines.REFLECTIONMAP_EXPLICIT = false;
  44217. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44218. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44219. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44220. defines.INVERTCUBICMAP = false;
  44221. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44222. defines.USESPHERICALINVERTEX = false;
  44223. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44224. defines.LODINREFLECTIONALPHA = false;
  44225. defines.GAMMAREFLECTION = false;
  44226. defines.RGBDREFLECTION = false;
  44227. }
  44228. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44229. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44230. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44231. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44232. }
  44233. else {
  44234. defines.LIGHTMAP = false;
  44235. }
  44236. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44238. }
  44239. else {
  44240. defines.EMISSIVE = false;
  44241. }
  44242. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44243. if (this._metallicTexture) {
  44244. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44245. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44246. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44247. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44248. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44249. }
  44250. else if (this._reflectivityTexture) {
  44251. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44252. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44253. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44254. }
  44255. else {
  44256. defines.REFLECTIVITY = false;
  44257. }
  44258. if (this._microSurfaceTexture) {
  44259. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44260. }
  44261. else {
  44262. defines.MICROSURFACEMAP = false;
  44263. }
  44264. }
  44265. else {
  44266. defines.REFLECTIVITY = false;
  44267. defines.MICROSURFACEMAP = false;
  44268. }
  44269. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44270. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44271. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44272. defines.PARALLAX = true;
  44273. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44274. }
  44275. else {
  44276. defines.PARALLAX = false;
  44277. }
  44278. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44279. }
  44280. else {
  44281. defines.BUMP = false;
  44282. }
  44283. var refractionTexture = this._getRefractionTexture();
  44284. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44285. defines.REFRACTION = true;
  44286. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44287. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44288. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44289. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44290. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44291. if (this._linkRefractionWithTransparency) {
  44292. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44293. }
  44294. }
  44295. else {
  44296. defines.REFRACTION = false;
  44297. }
  44298. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44299. defines.ENVIRONMENTBRDF = true;
  44300. }
  44301. else {
  44302. defines.ENVIRONMENTBRDF = false;
  44303. }
  44304. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44305. defines.ALPHAFROMALBEDO = true;
  44306. }
  44307. else {
  44308. defines.ALPHAFROMALBEDO = false;
  44309. }
  44310. }
  44311. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44312. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44313. defines.USEPHYSICALLIGHTFALLOFF = false;
  44314. defines.USEGLTFLIGHTFALLOFF = false;
  44315. }
  44316. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44317. defines.USEPHYSICALLIGHTFALLOFF = false;
  44318. defines.USEGLTFLIGHTFALLOFF = true;
  44319. }
  44320. else {
  44321. defines.USEPHYSICALLIGHTFALLOFF = true;
  44322. defines.USEGLTFLIGHTFALLOFF = false;
  44323. }
  44324. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44325. if (!this.backFaceCulling && this._twoSidedLighting) {
  44326. defines.TWOSIDEDLIGHTING = true;
  44327. }
  44328. else {
  44329. defines.TWOSIDEDLIGHTING = false;
  44330. }
  44331. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44332. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44333. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44334. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44335. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44336. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44337. }
  44338. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44339. this._imageProcessingConfiguration.prepareDefines(defines);
  44340. }
  44341. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44342. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44343. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44344. // Misc.
  44345. if (defines._areMiscDirty) {
  44346. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44347. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44348. }
  44349. // Values that need to be evaluated on every frame
  44350. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44351. // Attribs
  44352. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44353. };
  44354. /**
  44355. * Force shader compilation
  44356. */
  44357. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44358. var _this = this;
  44359. var localOptions = __assign({ clipPlane: false }, options);
  44360. var defines = new PBRMaterialDefines();
  44361. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44362. if (effect.isReady()) {
  44363. if (onCompiled) {
  44364. onCompiled(this);
  44365. }
  44366. }
  44367. else {
  44368. effect.onCompileObservable.add(function () {
  44369. if (onCompiled) {
  44370. onCompiled(_this);
  44371. }
  44372. });
  44373. }
  44374. };
  44375. /**
  44376. * Initializes the uniform buffer layout for the shader.
  44377. */
  44378. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44379. // Order is important !
  44380. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44381. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44382. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44383. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44384. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44385. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44386. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44387. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44388. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44389. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44390. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44391. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44392. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44393. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44394. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44395. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44396. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44397. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44398. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44399. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44400. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44401. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44402. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44403. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44404. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44405. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44406. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44407. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44408. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44409. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44410. this._uniformBuffer.addUniform("pointSize", 1);
  44411. this._uniformBuffer.create();
  44412. };
  44413. /**
  44414. * Unbinds the textures.
  44415. */
  44416. PBRBaseMaterial.prototype.unbind = function () {
  44417. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44418. this._uniformBuffer.setTexture("reflectionSampler", null);
  44419. }
  44420. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44421. this._uniformBuffer.setTexture("refractionSampler", null);
  44422. }
  44423. _super.prototype.unbind.call(this);
  44424. };
  44425. /**
  44426. * Binds the submesh data.
  44427. * @param world - The world matrix.
  44428. * @param mesh - The BJS mesh.
  44429. * @param subMesh - A submesh of the BJS mesh.
  44430. */
  44431. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44432. var scene = this.getScene();
  44433. var defines = subMesh._materialDefines;
  44434. if (!defines) {
  44435. return;
  44436. }
  44437. var effect = subMesh.effect;
  44438. if (!effect) {
  44439. return;
  44440. }
  44441. this._activeEffect = effect;
  44442. // Matrices
  44443. this.bindOnlyWorldMatrix(world);
  44444. // Normal Matrix
  44445. if (defines.OBJECTSPACE_NORMALMAP) {
  44446. world.toNormalMatrix(this._normalMatrix);
  44447. this.bindOnlyNormalMatrix(this._normalMatrix);
  44448. }
  44449. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44450. // Bones
  44451. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44452. var reflectionTexture = null;
  44453. if (mustRebind) {
  44454. this._uniformBuffer.bindToEffect(effect, "Material");
  44455. this.bindViewProjection(effect);
  44456. reflectionTexture = this._getReflectionTexture();
  44457. var refractionTexture = this._getRefractionTexture();
  44458. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44459. // Texture uniforms
  44460. if (scene.texturesEnabled) {
  44461. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44462. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44463. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44464. }
  44465. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44466. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44467. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44468. }
  44469. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44470. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44471. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44472. }
  44473. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44474. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44475. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44476. if (reflectionTexture.boundingBoxSize) {
  44477. var cubeTexture = reflectionTexture;
  44478. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44479. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44480. }
  44481. var polynomials = reflectionTexture.sphericalPolynomial;
  44482. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44483. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44484. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44485. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44486. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44487. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44488. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44489. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44490. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44491. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44492. }
  44493. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44494. }
  44495. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44496. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44497. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44498. }
  44499. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44500. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44501. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44502. }
  44503. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44504. if (this._metallicTexture) {
  44505. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44506. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44507. }
  44508. else if (this._reflectivityTexture) {
  44509. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44510. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44511. }
  44512. if (this._microSurfaceTexture) {
  44513. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44514. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44515. }
  44516. }
  44517. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44518. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44519. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44520. if (scene._mirroredCameraPosition) {
  44521. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44522. }
  44523. else {
  44524. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44525. }
  44526. }
  44527. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44528. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44529. var depth = 1.0;
  44530. if (!refractionTexture.isCube) {
  44531. if (refractionTexture.depth) {
  44532. depth = refractionTexture.depth;
  44533. }
  44534. }
  44535. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44536. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44537. }
  44538. }
  44539. // Point size
  44540. if (this.pointsCloud) {
  44541. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44542. }
  44543. // Colors
  44544. if (defines.METALLICWORKFLOW) {
  44545. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44546. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44547. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44548. }
  44549. else {
  44550. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44551. }
  44552. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44553. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44554. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44555. // Misc
  44556. this._lightingInfos.x = this._directIntensity;
  44557. this._lightingInfos.y = this._emissiveIntensity;
  44558. this._lightingInfos.z = this._environmentIntensity;
  44559. this._lightingInfos.w = this._specularIntensity;
  44560. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44561. }
  44562. // Textures
  44563. if (scene.texturesEnabled) {
  44564. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44565. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44566. }
  44567. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44568. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44569. }
  44570. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44571. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44572. }
  44573. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44574. if (defines.LODBASEDMICROSFURACE) {
  44575. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44576. }
  44577. else {
  44578. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44579. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44580. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44581. }
  44582. }
  44583. if (defines.ENVIRONMENTBRDF) {
  44584. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44585. }
  44586. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44587. if (defines.LODBASEDMICROSFURACE) {
  44588. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44589. }
  44590. else {
  44591. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44592. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44593. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44594. }
  44595. }
  44596. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44597. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44598. }
  44599. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44600. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44601. }
  44602. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44603. if (this._metallicTexture) {
  44604. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44605. }
  44606. else if (this._reflectivityTexture) {
  44607. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44608. }
  44609. if (this._microSurfaceTexture) {
  44610. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44611. }
  44612. }
  44613. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44614. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44615. }
  44616. }
  44617. // Clip plane
  44618. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44619. // Colors
  44620. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44621. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44622. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44623. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44624. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44625. }
  44626. if (mustRebind || !this.isFrozen) {
  44627. // Lights
  44628. if (scene.lightsEnabled && !this._disableLighting) {
  44629. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44630. }
  44631. // View
  44632. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44633. this.bindView(effect);
  44634. }
  44635. // Fog
  44636. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44637. // Morph targets
  44638. if (defines.NUM_MORPH_INFLUENCERS) {
  44639. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44640. }
  44641. // image processing
  44642. this._imageProcessingConfiguration.bind(this._activeEffect);
  44643. // Log. depth
  44644. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44645. }
  44646. this._uniformBuffer.update();
  44647. this._afterBind(mesh, this._activeEffect);
  44648. };
  44649. /**
  44650. * Returns the animatable textures.
  44651. * @returns - Array of animatable textures.
  44652. */
  44653. PBRBaseMaterial.prototype.getAnimatables = function () {
  44654. var results = [];
  44655. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44656. results.push(this._albedoTexture);
  44657. }
  44658. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44659. results.push(this._ambientTexture);
  44660. }
  44661. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44662. results.push(this._opacityTexture);
  44663. }
  44664. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44665. results.push(this._reflectionTexture);
  44666. }
  44667. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44668. results.push(this._emissiveTexture);
  44669. }
  44670. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44671. results.push(this._metallicTexture);
  44672. }
  44673. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44674. results.push(this._reflectivityTexture);
  44675. }
  44676. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44677. results.push(this._bumpTexture);
  44678. }
  44679. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44680. results.push(this._lightmapTexture);
  44681. }
  44682. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44683. results.push(this._refractionTexture);
  44684. }
  44685. return results;
  44686. };
  44687. /**
  44688. * Returns the texture used for reflections.
  44689. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44690. */
  44691. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44692. if (this._reflectionTexture) {
  44693. return this._reflectionTexture;
  44694. }
  44695. return this.getScene().environmentTexture;
  44696. };
  44697. /**
  44698. * Returns the texture used for refraction or null if none is used.
  44699. * @returns - Refection texture if present. If no refraction texture and refraction
  44700. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44701. */
  44702. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44703. if (this._refractionTexture) {
  44704. return this._refractionTexture;
  44705. }
  44706. if (this._linkRefractionWithTransparency) {
  44707. return this.getScene().environmentTexture;
  44708. }
  44709. return null;
  44710. };
  44711. /**
  44712. * Disposes the resources of the material.
  44713. * @param forceDisposeEffect - Forces the disposal of effects.
  44714. * @param forceDisposeTextures - Forces the disposal of all textures.
  44715. */
  44716. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44717. if (forceDisposeTextures) {
  44718. if (this._albedoTexture) {
  44719. this._albedoTexture.dispose();
  44720. }
  44721. if (this._ambientTexture) {
  44722. this._ambientTexture.dispose();
  44723. }
  44724. if (this._opacityTexture) {
  44725. this._opacityTexture.dispose();
  44726. }
  44727. if (this._reflectionTexture) {
  44728. this._reflectionTexture.dispose();
  44729. }
  44730. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44731. this._environmentBRDFTexture.dispose();
  44732. }
  44733. if (this._emissiveTexture) {
  44734. this._emissiveTexture.dispose();
  44735. }
  44736. if (this._metallicTexture) {
  44737. this._metallicTexture.dispose();
  44738. }
  44739. if (this._reflectivityTexture) {
  44740. this._reflectivityTexture.dispose();
  44741. }
  44742. if (this._bumpTexture) {
  44743. this._bumpTexture.dispose();
  44744. }
  44745. if (this._lightmapTexture) {
  44746. this._lightmapTexture.dispose();
  44747. }
  44748. if (this._refractionTexture) {
  44749. this._refractionTexture.dispose();
  44750. }
  44751. }
  44752. this._renderTargets.dispose();
  44753. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44754. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44755. }
  44756. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44757. };
  44758. /**
  44759. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44760. */
  44761. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44762. /**
  44763. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44764. * to enhance interoperability with other engines.
  44765. */
  44766. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44767. /**
  44768. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44769. * to enhance interoperability with other materials.
  44770. */
  44771. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44772. /**
  44773. * Stores the reflectivity values based on metallic roughness workflow.
  44774. */
  44775. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44776. __decorate([
  44777. BABYLON.serializeAsImageProcessingConfiguration()
  44778. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44779. __decorate([
  44780. BABYLON.serialize()
  44781. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44782. __decorate([
  44783. BABYLON.serialize()
  44784. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44785. return PBRBaseMaterial;
  44786. }(BABYLON.PushMaterial));
  44787. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44788. })(BABYLON || (BABYLON = {}));
  44789. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44790. var BABYLON;
  44791. (function (BABYLON) {
  44792. /**
  44793. * The Physically based simple base material of BJS.
  44794. *
  44795. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44796. * It is used as the base class for both the specGloss and metalRough conventions.
  44797. */
  44798. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44799. __extends(PBRBaseSimpleMaterial, _super);
  44800. /**
  44801. * Instantiates a new PBRMaterial instance.
  44802. *
  44803. * @param name The material name
  44804. * @param scene The scene the material will be use in.
  44805. */
  44806. function PBRBaseSimpleMaterial(name, scene) {
  44807. var _this = _super.call(this, name, scene) || this;
  44808. /**
  44809. * Number of Simultaneous lights allowed on the material.
  44810. */
  44811. _this.maxSimultaneousLights = 4;
  44812. /**
  44813. * If sets to true, disables all the lights affecting the material.
  44814. */
  44815. _this.disableLighting = false;
  44816. /**
  44817. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44818. */
  44819. _this.invertNormalMapX = false;
  44820. /**
  44821. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44822. */
  44823. _this.invertNormalMapY = false;
  44824. /**
  44825. * Emissivie color used to self-illuminate the model.
  44826. */
  44827. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44828. /**
  44829. * Occlusion Channel Strenght.
  44830. */
  44831. _this.occlusionStrength = 1.0;
  44832. _this.useLightmapAsShadowmap = false;
  44833. _this._useAlphaFromAlbedoTexture = true;
  44834. _this._useAmbientInGrayScale = true;
  44835. return _this;
  44836. }
  44837. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44838. /**
  44839. * Gets the current double sided mode.
  44840. */
  44841. get: function () {
  44842. return this._twoSidedLighting;
  44843. },
  44844. /**
  44845. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44846. */
  44847. set: function (value) {
  44848. if (this._twoSidedLighting === value) {
  44849. return;
  44850. }
  44851. this._twoSidedLighting = value;
  44852. this.backFaceCulling = !value;
  44853. this._markAllSubMeshesAsTexturesDirty();
  44854. },
  44855. enumerable: true,
  44856. configurable: true
  44857. });
  44858. /**
  44859. * Return the active textures of the material.
  44860. */
  44861. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44862. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44863. if (this.environmentTexture) {
  44864. activeTextures.push(this.environmentTexture);
  44865. }
  44866. if (this.normalTexture) {
  44867. activeTextures.push(this.normalTexture);
  44868. }
  44869. if (this.emissiveTexture) {
  44870. activeTextures.push(this.emissiveTexture);
  44871. }
  44872. if (this.occlusionTexture) {
  44873. activeTextures.push(this.occlusionTexture);
  44874. }
  44875. if (this.lightmapTexture) {
  44876. activeTextures.push(this.lightmapTexture);
  44877. }
  44878. return activeTextures;
  44879. };
  44880. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44881. if (_super.prototype.hasTexture.call(this, texture)) {
  44882. return true;
  44883. }
  44884. if (this.lightmapTexture === texture) {
  44885. return true;
  44886. }
  44887. return false;
  44888. };
  44889. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44890. return "PBRBaseSimpleMaterial";
  44891. };
  44892. __decorate([
  44893. BABYLON.serialize(),
  44894. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44895. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44896. __decorate([
  44897. BABYLON.serialize(),
  44898. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44899. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44900. __decorate([
  44901. BABYLON.serializeAsTexture(),
  44902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44903. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44904. __decorate([
  44905. BABYLON.serialize(),
  44906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44907. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44908. __decorate([
  44909. BABYLON.serialize(),
  44910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44911. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44912. __decorate([
  44913. BABYLON.serializeAsTexture(),
  44914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44915. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44916. __decorate([
  44917. BABYLON.serializeAsColor3("emissive"),
  44918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44919. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44920. __decorate([
  44921. BABYLON.serializeAsTexture(),
  44922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44923. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44924. __decorate([
  44925. BABYLON.serialize(),
  44926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44927. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44928. __decorate([
  44929. BABYLON.serializeAsTexture(),
  44930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44931. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44932. __decorate([
  44933. BABYLON.serialize(),
  44934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44935. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44936. __decorate([
  44937. BABYLON.serialize()
  44938. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44939. __decorate([
  44940. BABYLON.serializeAsTexture(),
  44941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44942. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44943. __decorate([
  44944. BABYLON.serialize(),
  44945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44946. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44947. return PBRBaseSimpleMaterial;
  44948. }(BABYLON.PBRBaseMaterial));
  44949. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44950. })(BABYLON || (BABYLON = {}));
  44951. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44952. var BABYLON;
  44953. (function (BABYLON) {
  44954. /**
  44955. * The Physically based material of BJS.
  44956. *
  44957. * This offers the main features of a standard PBR material.
  44958. * For more information, please refer to the documentation :
  44959. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44960. */
  44961. var PBRMaterial = /** @class */ (function (_super) {
  44962. __extends(PBRMaterial, _super);
  44963. /**
  44964. * Instantiates a new PBRMaterial instance.
  44965. *
  44966. * @param name The material name
  44967. * @param scene The scene the material will be use in.
  44968. */
  44969. function PBRMaterial(name, scene) {
  44970. var _this = _super.call(this, name, scene) || this;
  44971. /**
  44972. * Intensity of the direct lights e.g. the four lights available in your scene.
  44973. * This impacts both the direct diffuse and specular highlights.
  44974. */
  44975. _this.directIntensity = 1.0;
  44976. /**
  44977. * Intensity of the emissive part of the material.
  44978. * This helps controlling the emissive effect without modifying the emissive color.
  44979. */
  44980. _this.emissiveIntensity = 1.0;
  44981. /**
  44982. * Intensity of the environment e.g. how much the environment will light the object
  44983. * either through harmonics for rough material or through the refelction for shiny ones.
  44984. */
  44985. _this.environmentIntensity = 1.0;
  44986. /**
  44987. * This is a special control allowing the reduction of the specular highlights coming from the
  44988. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44989. */
  44990. _this.specularIntensity = 1.0;
  44991. /**
  44992. * Debug Control allowing disabling the bump map on this material.
  44993. */
  44994. _this.disableBumpMap = false;
  44995. /**
  44996. * AKA Occlusion Texture Intensity in other nomenclature.
  44997. */
  44998. _this.ambientTextureStrength = 1.0;
  44999. /**
  45000. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45001. * 1 means it completely occludes it
  45002. * 0 mean it has no impact
  45003. */
  45004. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45005. /**
  45006. * The color of a material in ambient lighting.
  45007. */
  45008. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45009. /**
  45010. * AKA Diffuse Color in other nomenclature.
  45011. */
  45012. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45013. /**
  45014. * AKA Specular Color in other nomenclature.
  45015. */
  45016. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45017. /**
  45018. * The color reflected from the material.
  45019. */
  45020. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45021. /**
  45022. * The color emitted from the material.
  45023. */
  45024. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45025. /**
  45026. * AKA Glossiness in other nomenclature.
  45027. */
  45028. _this.microSurface = 1.0;
  45029. /**
  45030. * source material index of refraction (IOR)' / 'destination material IOR.
  45031. */
  45032. _this.indexOfRefraction = 0.66;
  45033. /**
  45034. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45035. */
  45036. _this.invertRefractionY = false;
  45037. /**
  45038. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45039. * Materials half opaque for instance using refraction could benefit from this control.
  45040. */
  45041. _this.linkRefractionWithTransparency = false;
  45042. _this.useLightmapAsShadowmap = false;
  45043. /**
  45044. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45045. */
  45046. _this.useAlphaFromAlbedoTexture = false;
  45047. /**
  45048. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45049. */
  45050. _this.forceAlphaTest = false;
  45051. /**
  45052. * Defines the alpha limits in alpha test mode.
  45053. */
  45054. _this.alphaCutOff = 0.4;
  45055. /**
  45056. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45057. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45058. */
  45059. _this.useSpecularOverAlpha = true;
  45060. /**
  45061. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45062. */
  45063. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45064. /**
  45065. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45066. */
  45067. _this.useRoughnessFromMetallicTextureAlpha = true;
  45068. /**
  45069. * Specifies if the metallic texture contains the roughness information in its green channel.
  45070. */
  45071. _this.useRoughnessFromMetallicTextureGreen = false;
  45072. /**
  45073. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45074. */
  45075. _this.useMetallnessFromMetallicTextureBlue = false;
  45076. /**
  45077. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45078. */
  45079. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45080. /**
  45081. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45082. */
  45083. _this.useAmbientInGrayScale = false;
  45084. /**
  45085. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45086. * The material will try to infer what glossiness each pixel should be.
  45087. */
  45088. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45089. /**
  45090. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45091. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45092. */
  45093. _this.useRadianceOverAlpha = true;
  45094. /**
  45095. * Allows using an object space normal map (instead of tangent space).
  45096. */
  45097. _this.useObjectSpaceNormalMap = false;
  45098. /**
  45099. * Allows using the bump map in parallax mode.
  45100. */
  45101. _this.useParallax = false;
  45102. /**
  45103. * Allows using the bump map in parallax occlusion mode.
  45104. */
  45105. _this.useParallaxOcclusion = false;
  45106. /**
  45107. * Controls the scale bias of the parallax mode.
  45108. */
  45109. _this.parallaxScaleBias = 0.05;
  45110. /**
  45111. * If sets to true, disables all the lights affecting the material.
  45112. */
  45113. _this.disableLighting = false;
  45114. /**
  45115. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45116. */
  45117. _this.forceIrradianceInFragment = false;
  45118. /**
  45119. * Number of Simultaneous lights allowed on the material.
  45120. */
  45121. _this.maxSimultaneousLights = 4;
  45122. /**
  45123. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45124. */
  45125. _this.invertNormalMapX = false;
  45126. /**
  45127. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45128. */
  45129. _this.invertNormalMapY = false;
  45130. /**
  45131. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45132. */
  45133. _this.twoSidedLighting = false;
  45134. /**
  45135. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45136. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45137. */
  45138. _this.useAlphaFresnel = false;
  45139. /**
  45140. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45141. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45142. */
  45143. _this.useLinearAlphaFresnel = false;
  45144. /**
  45145. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45146. * And/Or occlude the blended part.
  45147. */
  45148. _this.environmentBRDFTexture = null;
  45149. /**
  45150. * Force normal to face away from face.
  45151. */
  45152. _this.forceNormalForward = false;
  45153. /**
  45154. * Enables specular anti aliasing in the PBR shader.
  45155. * It will both interacts on the Geometry for analytical and IBL lighting.
  45156. * It also prefilter the roughness map based on the bump values.
  45157. */
  45158. _this.enableSpecularAntiAliasing = false;
  45159. /**
  45160. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45161. * makes the reflect vector face the model (under horizon).
  45162. */
  45163. _this.useHorizonOcclusion = true;
  45164. /**
  45165. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45166. * too much the area relying on ambient texture to define their ambient occlusion.
  45167. */
  45168. _this.useRadianceOcclusion = true;
  45169. /**
  45170. * If set to true, no lighting calculations will be applied.
  45171. */
  45172. _this.unlit = false;
  45173. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45174. return _this;
  45175. }
  45176. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45177. /**
  45178. * BJS is using an harcoded light falloff based on a manually sets up range.
  45179. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45180. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45181. */
  45182. get: function () {
  45183. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45184. },
  45185. /**
  45186. * BJS is using an harcoded light falloff based on a manually sets up range.
  45187. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45188. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45189. */
  45190. set: function (value) {
  45191. if (value !== this.usePhysicalLightFalloff) {
  45192. // Ensure the effect will be rebuilt.
  45193. this._markAllSubMeshesAsTexturesDirty();
  45194. if (value) {
  45195. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45196. }
  45197. else {
  45198. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45199. }
  45200. }
  45201. },
  45202. enumerable: true,
  45203. configurable: true
  45204. });
  45205. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45206. /**
  45207. * In order to support the falloff compatibility with gltf, a special mode has been added
  45208. * to reproduce the gltf light falloff.
  45209. */
  45210. get: function () {
  45211. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45212. },
  45213. /**
  45214. * In order to support the falloff compatibility with gltf, a special mode has been added
  45215. * to reproduce the gltf light falloff.
  45216. */
  45217. set: function (value) {
  45218. if (value !== this.useGLTFLightFalloff) {
  45219. // Ensure the effect will be rebuilt.
  45220. this._markAllSubMeshesAsTexturesDirty();
  45221. if (value) {
  45222. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45223. }
  45224. else {
  45225. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45226. }
  45227. }
  45228. },
  45229. enumerable: true,
  45230. configurable: true
  45231. });
  45232. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45233. /**
  45234. * Gets the image processing configuration used either in this material.
  45235. */
  45236. get: function () {
  45237. return this._imageProcessingConfiguration;
  45238. },
  45239. /**
  45240. * Sets the Default image processing configuration used either in the this material.
  45241. *
  45242. * If sets to null, the scene one is in use.
  45243. */
  45244. set: function (value) {
  45245. this._attachImageProcessingConfiguration(value);
  45246. // Ensure the effect will be rebuilt.
  45247. this._markAllSubMeshesAsTexturesDirty();
  45248. },
  45249. enumerable: true,
  45250. configurable: true
  45251. });
  45252. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45253. /**
  45254. * Gets wether the color curves effect is enabled.
  45255. */
  45256. get: function () {
  45257. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45258. },
  45259. /**
  45260. * Sets wether the color curves effect is enabled.
  45261. */
  45262. set: function (value) {
  45263. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45264. },
  45265. enumerable: true,
  45266. configurable: true
  45267. });
  45268. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45269. /**
  45270. * Gets wether the color grading effect is enabled.
  45271. */
  45272. get: function () {
  45273. return this.imageProcessingConfiguration.colorGradingEnabled;
  45274. },
  45275. /**
  45276. * Gets wether the color grading effect is enabled.
  45277. */
  45278. set: function (value) {
  45279. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45280. },
  45281. enumerable: true,
  45282. configurable: true
  45283. });
  45284. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45285. /**
  45286. * Gets wether tonemapping is enabled or not.
  45287. */
  45288. get: function () {
  45289. return this._imageProcessingConfiguration.toneMappingEnabled;
  45290. },
  45291. /**
  45292. * Sets wether tonemapping is enabled or not
  45293. */
  45294. set: function (value) {
  45295. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45296. },
  45297. enumerable: true,
  45298. configurable: true
  45299. });
  45300. ;
  45301. ;
  45302. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45303. /**
  45304. * The camera exposure used on this material.
  45305. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45306. * This corresponds to a photographic exposure.
  45307. */
  45308. get: function () {
  45309. return this._imageProcessingConfiguration.exposure;
  45310. },
  45311. /**
  45312. * The camera exposure used on this material.
  45313. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45314. * This corresponds to a photographic exposure.
  45315. */
  45316. set: function (value) {
  45317. this._imageProcessingConfiguration.exposure = value;
  45318. },
  45319. enumerable: true,
  45320. configurable: true
  45321. });
  45322. ;
  45323. ;
  45324. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45325. /**
  45326. * Gets The camera contrast used on this material.
  45327. */
  45328. get: function () {
  45329. return this._imageProcessingConfiguration.contrast;
  45330. },
  45331. /**
  45332. * Sets The camera contrast used on this material.
  45333. */
  45334. set: function (value) {
  45335. this._imageProcessingConfiguration.contrast = value;
  45336. },
  45337. enumerable: true,
  45338. configurable: true
  45339. });
  45340. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45341. /**
  45342. * Gets the Color Grading 2D Lookup Texture.
  45343. */
  45344. get: function () {
  45345. return this._imageProcessingConfiguration.colorGradingTexture;
  45346. },
  45347. /**
  45348. * Sets the Color Grading 2D Lookup Texture.
  45349. */
  45350. set: function (value) {
  45351. this._imageProcessingConfiguration.colorGradingTexture = value;
  45352. },
  45353. enumerable: true,
  45354. configurable: true
  45355. });
  45356. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45357. /**
  45358. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45359. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45360. * 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;
  45361. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45362. */
  45363. get: function () {
  45364. return this._imageProcessingConfiguration.colorCurves;
  45365. },
  45366. /**
  45367. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45368. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45369. * 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;
  45370. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45371. */
  45372. set: function (value) {
  45373. this._imageProcessingConfiguration.colorCurves = value;
  45374. },
  45375. enumerable: true,
  45376. configurable: true
  45377. });
  45378. /**
  45379. * Returns the name of this material class.
  45380. */
  45381. PBRMaterial.prototype.getClassName = function () {
  45382. return "PBRMaterial";
  45383. };
  45384. /**
  45385. * Returns an array of the actively used textures.
  45386. * @returns - Array of BaseTextures
  45387. */
  45388. PBRMaterial.prototype.getActiveTextures = function () {
  45389. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45390. if (this._albedoTexture) {
  45391. activeTextures.push(this._albedoTexture);
  45392. }
  45393. if (this._ambientTexture) {
  45394. activeTextures.push(this._ambientTexture);
  45395. }
  45396. if (this._opacityTexture) {
  45397. activeTextures.push(this._opacityTexture);
  45398. }
  45399. if (this._reflectionTexture) {
  45400. activeTextures.push(this._reflectionTexture);
  45401. }
  45402. if (this._emissiveTexture) {
  45403. activeTextures.push(this._emissiveTexture);
  45404. }
  45405. if (this._reflectivityTexture) {
  45406. activeTextures.push(this._reflectivityTexture);
  45407. }
  45408. if (this._metallicTexture) {
  45409. activeTextures.push(this._metallicTexture);
  45410. }
  45411. if (this._microSurfaceTexture) {
  45412. activeTextures.push(this._microSurfaceTexture);
  45413. }
  45414. if (this._bumpTexture) {
  45415. activeTextures.push(this._bumpTexture);
  45416. }
  45417. if (this._lightmapTexture) {
  45418. activeTextures.push(this._lightmapTexture);
  45419. }
  45420. if (this._refractionTexture) {
  45421. activeTextures.push(this._refractionTexture);
  45422. }
  45423. return activeTextures;
  45424. };
  45425. /**
  45426. * Checks to see if a texture is used in the material.
  45427. * @param texture - Base texture to use.
  45428. * @returns - Boolean specifying if a texture is used in the material.
  45429. */
  45430. PBRMaterial.prototype.hasTexture = function (texture) {
  45431. if (_super.prototype.hasTexture.call(this, texture)) {
  45432. return true;
  45433. }
  45434. if (this._albedoTexture === texture) {
  45435. return true;
  45436. }
  45437. if (this._ambientTexture === texture) {
  45438. return true;
  45439. }
  45440. if (this._opacityTexture === texture) {
  45441. return true;
  45442. }
  45443. if (this._reflectionTexture === texture) {
  45444. return true;
  45445. }
  45446. if (this._reflectivityTexture === texture) {
  45447. return true;
  45448. }
  45449. if (this._metallicTexture === texture) {
  45450. return true;
  45451. }
  45452. if (this._microSurfaceTexture === texture) {
  45453. return true;
  45454. }
  45455. if (this._bumpTexture === texture) {
  45456. return true;
  45457. }
  45458. if (this._lightmapTexture === texture) {
  45459. return true;
  45460. }
  45461. if (this._refractionTexture === texture) {
  45462. return true;
  45463. }
  45464. return false;
  45465. };
  45466. /**
  45467. * Makes a duplicate of the current material.
  45468. * @param name - name to use for the new material.
  45469. */
  45470. PBRMaterial.prototype.clone = function (name) {
  45471. var _this = this;
  45472. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45473. clone.id = name;
  45474. clone.name = name;
  45475. return clone;
  45476. };
  45477. /**
  45478. * Serializes this PBR Material.
  45479. * @returns - An object with the serialized material.
  45480. */
  45481. PBRMaterial.prototype.serialize = function () {
  45482. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45483. serializationObject.customType = "BABYLON.PBRMaterial";
  45484. return serializationObject;
  45485. };
  45486. // Statics
  45487. /**
  45488. * Parses a PBR Material from a serialized object.
  45489. * @param source - Serialized object.
  45490. * @param scene - BJS scene instance.
  45491. * @param rootUrl - url for the scene object
  45492. * @returns - PBRMaterial
  45493. */
  45494. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45495. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45496. };
  45497. /**
  45498. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45499. */
  45500. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45501. /**
  45502. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45503. */
  45504. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45505. /**
  45506. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45507. */
  45508. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45509. /**
  45510. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45511. * They are also discarded below the alpha cutoff threshold to improve performances.
  45512. */
  45513. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45514. /**
  45515. * Defines the default value of how much AO map is occluding the analytical lights
  45516. * (point spot...).
  45517. */
  45518. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45519. __decorate([
  45520. BABYLON.serialize(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "directIntensity", void 0);
  45523. __decorate([
  45524. BABYLON.serialize(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45527. __decorate([
  45528. BABYLON.serialize(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45531. __decorate([
  45532. BABYLON.serialize(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45535. __decorate([
  45536. BABYLON.serialize(),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45539. __decorate([
  45540. BABYLON.serializeAsTexture(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45543. __decorate([
  45544. BABYLON.serializeAsTexture(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45550. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45551. __decorate([
  45552. BABYLON.serialize(),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45555. __decorate([
  45556. BABYLON.serializeAsTexture(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45558. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45559. __decorate([
  45560. BABYLON.serializeAsTexture(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45563. __decorate([
  45564. BABYLON.serializeAsTexture(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45566. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45567. __decorate([
  45568. BABYLON.serializeAsTexture(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45570. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45571. __decorate([
  45572. BABYLON.serializeAsTexture(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45574. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45578. ], PBRMaterial.prototype, "metallic", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45582. ], PBRMaterial.prototype, "roughness", void 0);
  45583. __decorate([
  45584. BABYLON.serializeAsTexture(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45586. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45587. __decorate([
  45588. BABYLON.serializeAsTexture(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45591. __decorate([
  45592. BABYLON.serializeAsTexture(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45594. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45595. __decorate([
  45596. BABYLON.serializeAsTexture(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45599. __decorate([
  45600. BABYLON.serializeAsColor3("ambient"),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "ambientColor", void 0);
  45603. __decorate([
  45604. BABYLON.serializeAsColor3("albedo"),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "albedoColor", void 0);
  45607. __decorate([
  45608. BABYLON.serializeAsColor3("reflectivity"),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45611. __decorate([
  45612. BABYLON.serializeAsColor3("reflection"),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45615. __decorate([
  45616. BABYLON.serializeAsColor3("emissive"),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRMaterial.prototype, "microSurface", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45631. __decorate([
  45632. BABYLON.serialize(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45634. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45635. __decorate([
  45636. BABYLON.serialize(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45638. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45639. __decorate([
  45640. BABYLON.serialize(),
  45641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45642. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45643. __decorate([
  45644. BABYLON.serialize(),
  45645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45646. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45647. __decorate([
  45648. BABYLON.serialize(),
  45649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45650. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45651. __decorate([
  45652. BABYLON.serialize(),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45654. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45655. __decorate([
  45656. BABYLON.serialize(),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45658. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45659. __decorate([
  45660. BABYLON.serialize(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45662. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45663. __decorate([
  45664. BABYLON.serialize(),
  45665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45666. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45667. __decorate([
  45668. BABYLON.serialize(),
  45669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45670. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45671. __decorate([
  45672. BABYLON.serialize(),
  45673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45674. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45675. __decorate([
  45676. BABYLON.serialize(),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45678. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45679. __decorate([
  45680. BABYLON.serialize(),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45682. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45683. __decorate([
  45684. BABYLON.serialize()
  45685. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45686. __decorate([
  45687. BABYLON.serialize()
  45688. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45689. __decorate([
  45690. BABYLON.serialize(),
  45691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45692. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45693. __decorate([
  45694. BABYLON.serialize(),
  45695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45696. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45697. __decorate([
  45698. BABYLON.serialize(),
  45699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45700. ], PBRMaterial.prototype, "useParallax", void 0);
  45701. __decorate([
  45702. BABYLON.serialize(),
  45703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45704. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45705. __decorate([
  45706. BABYLON.serialize(),
  45707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45708. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45709. __decorate([
  45710. BABYLON.serialize(),
  45711. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45712. ], PBRMaterial.prototype, "disableLighting", void 0);
  45713. __decorate([
  45714. BABYLON.serialize(),
  45715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45716. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45717. __decorate([
  45718. BABYLON.serialize(),
  45719. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45720. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45721. __decorate([
  45722. BABYLON.serialize(),
  45723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45724. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45725. __decorate([
  45726. BABYLON.serialize(),
  45727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45728. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45729. __decorate([
  45730. BABYLON.serialize(),
  45731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45732. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45733. __decorate([
  45734. BABYLON.serialize(),
  45735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45736. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45737. __decorate([
  45738. BABYLON.serialize(),
  45739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45740. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45741. __decorate([
  45742. BABYLON.serializeAsTexture(),
  45743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45744. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45745. __decorate([
  45746. BABYLON.serialize(),
  45747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45748. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45749. __decorate([
  45750. BABYLON.serialize(),
  45751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45752. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45753. __decorate([
  45754. BABYLON.serialize(),
  45755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45756. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45757. __decorate([
  45758. BABYLON.serialize(),
  45759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45760. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45761. __decorate([
  45762. BABYLON.serialize(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45764. ], PBRMaterial.prototype, "unlit", void 0);
  45765. return PBRMaterial;
  45766. }(BABYLON.PBRBaseMaterial));
  45767. BABYLON.PBRMaterial = PBRMaterial;
  45768. })(BABYLON || (BABYLON = {}));
  45769. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45770. var BABYLON;
  45771. (function (BABYLON) {
  45772. /**
  45773. * The PBR material of BJS following the metal roughness convention.
  45774. *
  45775. * This fits to the PBR convention in the GLTF definition:
  45776. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45777. */
  45778. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45779. __extends(PBRMetallicRoughnessMaterial, _super);
  45780. /**
  45781. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45782. *
  45783. * @param name The material name
  45784. * @param scene The scene the material will be use in.
  45785. */
  45786. function PBRMetallicRoughnessMaterial(name, scene) {
  45787. var _this = _super.call(this, name, scene) || this;
  45788. _this._useRoughnessFromMetallicTextureAlpha = false;
  45789. _this._useRoughnessFromMetallicTextureGreen = true;
  45790. _this._useMetallnessFromMetallicTextureBlue = true;
  45791. _this.metallic = 1.0;
  45792. _this.roughness = 1.0;
  45793. return _this;
  45794. }
  45795. /**
  45796. * Return the currrent class name of the material.
  45797. */
  45798. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45799. return "PBRMetallicRoughnessMaterial";
  45800. };
  45801. /**
  45802. * Return the active textures of the material.
  45803. */
  45804. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45805. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45806. if (this.baseTexture) {
  45807. activeTextures.push(this.baseTexture);
  45808. }
  45809. if (this.metallicRoughnessTexture) {
  45810. activeTextures.push(this.metallicRoughnessTexture);
  45811. }
  45812. return activeTextures;
  45813. };
  45814. /**
  45815. * Checks to see if a texture is used in the material.
  45816. * @param texture - Base texture to use.
  45817. * @returns - Boolean specifying if a texture is used in the material.
  45818. */
  45819. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45820. if (_super.prototype.hasTexture.call(this, texture)) {
  45821. return true;
  45822. }
  45823. if (this.baseTexture === texture) {
  45824. return true;
  45825. }
  45826. if (this.metallicRoughnessTexture === texture) {
  45827. return true;
  45828. }
  45829. return false;
  45830. };
  45831. /**
  45832. * Makes a duplicate of the current material.
  45833. * @param name - name to use for the new material.
  45834. */
  45835. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45836. var _this = this;
  45837. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45838. clone.id = name;
  45839. clone.name = name;
  45840. return clone;
  45841. };
  45842. /**
  45843. * Serialize the material to a parsable JSON object.
  45844. */
  45845. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45846. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45847. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45848. return serializationObject;
  45849. };
  45850. /**
  45851. * Parses a JSON object correponding to the serialize function.
  45852. */
  45853. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45854. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45855. };
  45856. __decorate([
  45857. BABYLON.serializeAsColor3(),
  45858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45859. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45860. __decorate([
  45861. BABYLON.serializeAsTexture(),
  45862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45863. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45864. __decorate([
  45865. BABYLON.serialize(),
  45866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45867. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45868. __decorate([
  45869. BABYLON.serialize(),
  45870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45871. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45872. __decorate([
  45873. BABYLON.serializeAsTexture(),
  45874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45875. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45876. return PBRMetallicRoughnessMaterial;
  45877. }(BABYLON.PBRBaseSimpleMaterial));
  45878. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45879. })(BABYLON || (BABYLON = {}));
  45880. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45881. var BABYLON;
  45882. (function (BABYLON) {
  45883. /**
  45884. * The PBR material of BJS following the specular glossiness convention.
  45885. *
  45886. * This fits to the PBR convention in the GLTF definition:
  45887. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45888. */
  45889. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45890. __extends(PBRSpecularGlossinessMaterial, _super);
  45891. /**
  45892. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45893. *
  45894. * @param name The material name
  45895. * @param scene The scene the material will be use in.
  45896. */
  45897. function PBRSpecularGlossinessMaterial(name, scene) {
  45898. var _this = _super.call(this, name, scene) || this;
  45899. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45900. return _this;
  45901. }
  45902. /**
  45903. * Return the currrent class name of the material.
  45904. */
  45905. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45906. return "PBRSpecularGlossinessMaterial";
  45907. };
  45908. /**
  45909. * Return the active textures of the material.
  45910. */
  45911. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45912. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45913. if (this.diffuseTexture) {
  45914. activeTextures.push(this.diffuseTexture);
  45915. }
  45916. if (this.specularGlossinessTexture) {
  45917. activeTextures.push(this.specularGlossinessTexture);
  45918. }
  45919. return activeTextures;
  45920. };
  45921. /**
  45922. * Checks to see if a texture is used in the material.
  45923. * @param texture - Base texture to use.
  45924. * @returns - Boolean specifying if a texture is used in the material.
  45925. */
  45926. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45927. if (_super.prototype.hasTexture.call(this, texture)) {
  45928. return true;
  45929. }
  45930. if (this.diffuseTexture === texture) {
  45931. return true;
  45932. }
  45933. if (this.specularGlossinessTexture === texture) {
  45934. return true;
  45935. }
  45936. return false;
  45937. };
  45938. /**
  45939. * Makes a duplicate of the current material.
  45940. * @param name - name to use for the new material.
  45941. */
  45942. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45943. var _this = this;
  45944. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45945. clone.id = name;
  45946. clone.name = name;
  45947. return clone;
  45948. };
  45949. /**
  45950. * Serialize the material to a parsable JSON object.
  45951. */
  45952. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45953. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45954. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45955. return serializationObject;
  45956. };
  45957. /**
  45958. * Parses a JSON object correponding to the serialize function.
  45959. */
  45960. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45961. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45962. };
  45963. __decorate([
  45964. BABYLON.serializeAsColor3("diffuse"),
  45965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45966. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45967. __decorate([
  45968. BABYLON.serializeAsTexture(),
  45969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45970. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45971. __decorate([
  45972. BABYLON.serializeAsColor3("specular"),
  45973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45974. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45975. __decorate([
  45976. BABYLON.serialize(),
  45977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45978. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45979. __decorate([
  45980. BABYLON.serializeAsTexture(),
  45981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45982. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45983. return PBRSpecularGlossinessMaterial;
  45984. }(BABYLON.PBRBaseSimpleMaterial));
  45985. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45986. })(BABYLON || (BABYLON = {}));
  45987. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45988. var BABYLON;
  45989. (function (BABYLON) {
  45990. BABYLON.CameraInputTypes = {};
  45991. var CameraInputsManager = /** @class */ (function () {
  45992. function CameraInputsManager(camera) {
  45993. this.attached = {};
  45994. this.camera = camera;
  45995. this.checkInputs = function () { };
  45996. }
  45997. /**
  45998. * Add an input method to a camera
  45999. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46000. * @param input camera input method
  46001. */
  46002. CameraInputsManager.prototype.add = function (input) {
  46003. var type = input.getSimpleName();
  46004. if (this.attached[type]) {
  46005. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46006. return;
  46007. }
  46008. this.attached[type] = input;
  46009. input.camera = this.camera;
  46010. //for checkInputs, we are dynamically creating a function
  46011. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46012. if (input.checkInputs) {
  46013. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46014. }
  46015. if (this.attachedElement) {
  46016. input.attachControl(this.attachedElement);
  46017. }
  46018. };
  46019. /**
  46020. * Remove a specific input method from a camera
  46021. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46022. * @param inputToRemove camera input method
  46023. */
  46024. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46025. for (var cam in this.attached) {
  46026. var input = this.attached[cam];
  46027. if (input === inputToRemove) {
  46028. input.detachControl(this.attachedElement);
  46029. input.camera = null;
  46030. delete this.attached[cam];
  46031. this.rebuildInputCheck();
  46032. }
  46033. }
  46034. };
  46035. CameraInputsManager.prototype.removeByType = function (inputType) {
  46036. for (var cam in this.attached) {
  46037. var input = this.attached[cam];
  46038. if (input.getClassName() === inputType) {
  46039. input.detachControl(this.attachedElement);
  46040. input.camera = null;
  46041. delete this.attached[cam];
  46042. this.rebuildInputCheck();
  46043. }
  46044. }
  46045. };
  46046. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46047. var current = this.checkInputs;
  46048. return function () {
  46049. current();
  46050. fn();
  46051. };
  46052. };
  46053. CameraInputsManager.prototype.attachInput = function (input) {
  46054. if (this.attachedElement) {
  46055. input.attachControl(this.attachedElement, this.noPreventDefault);
  46056. }
  46057. };
  46058. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46059. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46060. if (this.attachedElement) {
  46061. return;
  46062. }
  46063. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46064. this.attachedElement = element;
  46065. this.noPreventDefault = noPreventDefault;
  46066. for (var cam in this.attached) {
  46067. this.attached[cam].attachControl(element, noPreventDefault);
  46068. }
  46069. };
  46070. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46071. if (disconnect === void 0) { disconnect = false; }
  46072. if (this.attachedElement !== element) {
  46073. return;
  46074. }
  46075. for (var cam in this.attached) {
  46076. this.attached[cam].detachControl(element);
  46077. if (disconnect) {
  46078. this.attached[cam].camera = null;
  46079. }
  46080. }
  46081. this.attachedElement = null;
  46082. };
  46083. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46084. this.checkInputs = function () { };
  46085. for (var cam in this.attached) {
  46086. var input = this.attached[cam];
  46087. if (input.checkInputs) {
  46088. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46089. }
  46090. }
  46091. };
  46092. /**
  46093. * Remove all attached input methods from a camera
  46094. */
  46095. CameraInputsManager.prototype.clear = function () {
  46096. if (this.attachedElement) {
  46097. this.detachElement(this.attachedElement, true);
  46098. }
  46099. this.attached = {};
  46100. this.attachedElement = null;
  46101. this.checkInputs = function () { };
  46102. };
  46103. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46104. var inputs = {};
  46105. for (var cam in this.attached) {
  46106. var input = this.attached[cam];
  46107. var res = BABYLON.SerializationHelper.Serialize(input);
  46108. inputs[input.getClassName()] = res;
  46109. }
  46110. serializedCamera.inputsmgr = inputs;
  46111. };
  46112. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46113. var parsedInputs = parsedCamera.inputsmgr;
  46114. if (parsedInputs) {
  46115. this.clear();
  46116. for (var n in parsedInputs) {
  46117. var construct = BABYLON.CameraInputTypes[n];
  46118. if (construct) {
  46119. var parsedinput = parsedInputs[n];
  46120. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46121. this.add(input);
  46122. }
  46123. }
  46124. }
  46125. else {
  46126. //2016-03-08 this part is for managing backward compatibility
  46127. for (var n in this.attached) {
  46128. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46129. if (construct) {
  46130. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46131. this.remove(this.attached[n]);
  46132. this.add(input);
  46133. }
  46134. }
  46135. }
  46136. };
  46137. return CameraInputsManager;
  46138. }());
  46139. BABYLON.CameraInputsManager = CameraInputsManager;
  46140. })(BABYLON || (BABYLON = {}));
  46141. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46142. var BABYLON;
  46143. (function (BABYLON) {
  46144. var TargetCamera = /** @class */ (function (_super) {
  46145. __extends(TargetCamera, _super);
  46146. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46147. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46148. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46149. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46150. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46151. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46152. _this.speed = 2.0;
  46153. _this.noRotationConstraint = false;
  46154. _this.lockedTarget = null;
  46155. /** @hidden */
  46156. _this._currentTarget = BABYLON.Vector3.Zero();
  46157. /** @hidden */
  46158. _this._viewMatrix = BABYLON.Matrix.Zero();
  46159. /** @hidden */
  46160. _this._camMatrix = BABYLON.Matrix.Zero();
  46161. /** @hidden */
  46162. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46163. /** @hidden */
  46164. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46165. /** @hidden */
  46166. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46167. /** @hidden */
  46168. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46169. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46170. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46171. _this._defaultUp = BABYLON.Vector3.Up();
  46172. _this._cachedRotationZ = 0;
  46173. return _this;
  46174. }
  46175. TargetCamera.prototype.getFrontPosition = function (distance) {
  46176. this.getWorldMatrix();
  46177. var direction = this.getTarget().subtract(this.position);
  46178. direction.normalize();
  46179. direction.scaleInPlace(distance);
  46180. return this.globalPosition.add(direction);
  46181. };
  46182. /** @hidden */
  46183. TargetCamera.prototype._getLockedTargetPosition = function () {
  46184. if (!this.lockedTarget) {
  46185. return null;
  46186. }
  46187. if (this.lockedTarget.absolutePosition) {
  46188. this.lockedTarget.computeWorldMatrix();
  46189. }
  46190. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46191. };
  46192. TargetCamera.prototype.storeState = function () {
  46193. this._storedPosition = this.position.clone();
  46194. this._storedRotation = this.rotation.clone();
  46195. if (this.rotationQuaternion) {
  46196. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46197. }
  46198. return _super.prototype.storeState.call(this);
  46199. };
  46200. /**
  46201. * Restored camera state. You must call storeState() first
  46202. * @returns whether it was successful or not
  46203. * @hidden
  46204. */
  46205. TargetCamera.prototype._restoreStateValues = function () {
  46206. if (!_super.prototype._restoreStateValues.call(this)) {
  46207. return false;
  46208. }
  46209. this.position = this._storedPosition.clone();
  46210. this.rotation = this._storedRotation.clone();
  46211. if (this.rotationQuaternion) {
  46212. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46213. }
  46214. this.cameraDirection.copyFromFloats(0, 0, 0);
  46215. this.cameraRotation.copyFromFloats(0, 0);
  46216. return true;
  46217. };
  46218. // Cache
  46219. /** @hidden */
  46220. TargetCamera.prototype._initCache = function () {
  46221. _super.prototype._initCache.call(this);
  46222. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46223. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46224. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46225. };
  46226. /** @hidden */
  46227. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46228. if (!ignoreParentClass) {
  46229. _super.prototype._updateCache.call(this);
  46230. }
  46231. var lockedTargetPosition = this._getLockedTargetPosition();
  46232. if (!lockedTargetPosition) {
  46233. this._cache.lockedTarget = null;
  46234. }
  46235. else {
  46236. if (!this._cache.lockedTarget) {
  46237. this._cache.lockedTarget = lockedTargetPosition.clone();
  46238. }
  46239. else {
  46240. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46241. }
  46242. }
  46243. this._cache.rotation.copyFrom(this.rotation);
  46244. if (this.rotationQuaternion)
  46245. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46246. };
  46247. // Synchronized
  46248. /** @hidden */
  46249. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46250. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46251. return false;
  46252. }
  46253. var lockedTargetPosition = this._getLockedTargetPosition();
  46254. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46255. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46256. };
  46257. // Methods
  46258. /** @hidden */
  46259. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46260. var engine = this.getEngine();
  46261. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46262. };
  46263. // Target
  46264. /** @hidden */
  46265. TargetCamera.prototype.setTarget = function (target) {
  46266. this.upVector.normalize();
  46267. if (this.position.z === target.z) {
  46268. this.position.z += BABYLON.Epsilon;
  46269. }
  46270. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46271. this._camMatrix.invert();
  46272. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46273. var vDir = target.subtract(this.position);
  46274. if (vDir.x >= 0.0) {
  46275. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46276. }
  46277. else {
  46278. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46279. }
  46280. this.rotation.z = 0;
  46281. if (isNaN(this.rotation.x)) {
  46282. this.rotation.x = 0;
  46283. }
  46284. if (isNaN(this.rotation.y)) {
  46285. this.rotation.y = 0;
  46286. }
  46287. if (isNaN(this.rotation.z)) {
  46288. this.rotation.z = 0;
  46289. }
  46290. if (this.rotationQuaternion) {
  46291. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46292. }
  46293. };
  46294. /**
  46295. * Return the current target position of the camera. This value is expressed in local space.
  46296. */
  46297. TargetCamera.prototype.getTarget = function () {
  46298. return this._currentTarget;
  46299. };
  46300. /** @hidden */
  46301. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46302. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46303. };
  46304. /** @hidden */
  46305. TargetCamera.prototype._updatePosition = function () {
  46306. if (this.parent) {
  46307. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46308. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46309. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46310. return;
  46311. }
  46312. this.position.addInPlace(this.cameraDirection);
  46313. };
  46314. /** @hidden */
  46315. TargetCamera.prototype._checkInputs = function () {
  46316. var needToMove = this._decideIfNeedsToMove();
  46317. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46318. // Move
  46319. if (needToMove) {
  46320. this._updatePosition();
  46321. }
  46322. // Rotate
  46323. if (needToRotate) {
  46324. this.rotation.x += this.cameraRotation.x;
  46325. this.rotation.y += this.cameraRotation.y;
  46326. //rotate, if quaternion is set and rotation was used
  46327. if (this.rotationQuaternion) {
  46328. var len = this.rotation.lengthSquared();
  46329. if (len) {
  46330. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46331. }
  46332. }
  46333. if (!this.noRotationConstraint) {
  46334. var limit = (Math.PI / 2) * 0.95;
  46335. if (this.rotation.x > limit)
  46336. this.rotation.x = limit;
  46337. if (this.rotation.x < -limit)
  46338. this.rotation.x = -limit;
  46339. }
  46340. }
  46341. // Inertia
  46342. if (needToMove) {
  46343. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46344. this.cameraDirection.x = 0;
  46345. }
  46346. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46347. this.cameraDirection.y = 0;
  46348. }
  46349. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46350. this.cameraDirection.z = 0;
  46351. }
  46352. this.cameraDirection.scaleInPlace(this.inertia);
  46353. }
  46354. if (needToRotate) {
  46355. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46356. this.cameraRotation.x = 0;
  46357. }
  46358. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46359. this.cameraRotation.y = 0;
  46360. }
  46361. this.cameraRotation.scaleInPlace(this.inertia);
  46362. }
  46363. _super.prototype._checkInputs.call(this);
  46364. };
  46365. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46366. if (this.rotationQuaternion) {
  46367. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46368. }
  46369. else {
  46370. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46371. }
  46372. };
  46373. /**
  46374. * 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)
  46375. * @returns the current camera
  46376. */
  46377. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46378. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46379. return this;
  46380. };
  46381. /** @hidden */
  46382. TargetCamera.prototype._getViewMatrix = function () {
  46383. if (this.lockedTarget) {
  46384. this.setTarget(this._getLockedTargetPosition());
  46385. }
  46386. // Compute
  46387. this._updateCameraRotationMatrix();
  46388. // Apply the changed rotation to the upVector.
  46389. if (this._cachedRotationZ != this.rotation.z) {
  46390. this._rotateUpVectorWithCameraRotationMatrix();
  46391. this._cachedRotationZ = this.rotation.z;
  46392. }
  46393. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46394. // Computing target and final matrix
  46395. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46396. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46397. return this._viewMatrix;
  46398. };
  46399. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46400. if (this.parent) {
  46401. var parentWorldMatrix = this.parent.getWorldMatrix();
  46402. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46403. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46404. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46405. this._markSyncedWithParent();
  46406. }
  46407. else {
  46408. this._globalPosition.copyFrom(position);
  46409. this._globalCurrentTarget.copyFrom(target);
  46410. this._globalCurrentUpVector.copyFrom(up);
  46411. }
  46412. if (this.getScene().useRightHandedSystem) {
  46413. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46414. }
  46415. else {
  46416. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46417. }
  46418. };
  46419. /**
  46420. * @override
  46421. * Override Camera.createRigCamera
  46422. */
  46423. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46424. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46425. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46426. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46427. if (!this.rotationQuaternion) {
  46428. this.rotationQuaternion = new BABYLON.Quaternion();
  46429. }
  46430. rigCamera._cameraRigParams = {};
  46431. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46432. }
  46433. return rigCamera;
  46434. }
  46435. return null;
  46436. };
  46437. /**
  46438. * @hidden
  46439. * @override
  46440. * Override Camera._updateRigCameras
  46441. */
  46442. TargetCamera.prototype._updateRigCameras = function () {
  46443. var camLeft = this._rigCameras[0];
  46444. var camRight = this._rigCameras[1];
  46445. switch (this.cameraRigMode) {
  46446. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46447. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46448. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46449. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46450. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46451. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46452. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46453. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46454. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46455. camLeft.setTarget(this.getTarget());
  46456. camRight.setTarget(this.getTarget());
  46457. break;
  46458. case BABYLON.Camera.RIG_MODE_VR:
  46459. if (camLeft.rotationQuaternion) {
  46460. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46461. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46462. }
  46463. else {
  46464. camLeft.rotation.copyFrom(this.rotation);
  46465. camRight.rotation.copyFrom(this.rotation);
  46466. }
  46467. camLeft.position.copyFrom(this.position);
  46468. camRight.position.copyFrom(this.position);
  46469. break;
  46470. }
  46471. _super.prototype._updateRigCameras.call(this);
  46472. };
  46473. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46474. if (!this._rigCamTransformMatrix) {
  46475. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46476. }
  46477. var target = this.getTarget();
  46478. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46479. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46480. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46481. };
  46482. TargetCamera.prototype.getClassName = function () {
  46483. return "TargetCamera";
  46484. };
  46485. __decorate([
  46486. BABYLON.serializeAsVector3()
  46487. ], TargetCamera.prototype, "rotation", void 0);
  46488. __decorate([
  46489. BABYLON.serialize()
  46490. ], TargetCamera.prototype, "speed", void 0);
  46491. __decorate([
  46492. BABYLON.serializeAsMeshReference("lockedTargetId")
  46493. ], TargetCamera.prototype, "lockedTarget", void 0);
  46494. return TargetCamera;
  46495. }(BABYLON.Camera));
  46496. BABYLON.TargetCamera = TargetCamera;
  46497. })(BABYLON || (BABYLON = {}));
  46498. //# sourceMappingURL=babylon.targetCamera.js.map
  46499. var BABYLON;
  46500. (function (BABYLON) {
  46501. var FreeCameraMouseInput = /** @class */ (function () {
  46502. function FreeCameraMouseInput(touchEnabled) {
  46503. if (touchEnabled === void 0) { touchEnabled = true; }
  46504. this.touchEnabled = touchEnabled;
  46505. this.buttons = [0, 1, 2];
  46506. this.angularSensibility = 2000.0;
  46507. this.previousPosition = null;
  46508. }
  46509. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46510. var _this = this;
  46511. var engine = this.camera.getEngine();
  46512. if (!this._pointerInput) {
  46513. this._pointerInput = function (p, s) {
  46514. var evt = p.event;
  46515. if (engine.isInVRExclusivePointerMode) {
  46516. return;
  46517. }
  46518. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46519. return;
  46520. }
  46521. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46522. return;
  46523. }
  46524. var srcElement = (evt.srcElement || evt.target);
  46525. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46526. try {
  46527. srcElement.setPointerCapture(evt.pointerId);
  46528. }
  46529. catch (e) {
  46530. //Nothing to do with the error. Execution will continue.
  46531. }
  46532. _this.previousPosition = {
  46533. x: evt.clientX,
  46534. y: evt.clientY
  46535. };
  46536. if (!noPreventDefault) {
  46537. evt.preventDefault();
  46538. element.focus();
  46539. }
  46540. }
  46541. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46542. try {
  46543. srcElement.releasePointerCapture(evt.pointerId);
  46544. }
  46545. catch (e) {
  46546. //Nothing to do with the error.
  46547. }
  46548. _this.previousPosition = null;
  46549. if (!noPreventDefault) {
  46550. evt.preventDefault();
  46551. }
  46552. }
  46553. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46554. if (!_this.previousPosition || engine.isPointerLock) {
  46555. return;
  46556. }
  46557. var offsetX = evt.clientX - _this.previousPosition.x;
  46558. if (_this.camera.getScene().useRightHandedSystem)
  46559. offsetX *= -1;
  46560. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46561. offsetX *= -1;
  46562. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46563. var offsetY = evt.clientY - _this.previousPosition.y;
  46564. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46565. _this.previousPosition = {
  46566. x: evt.clientX,
  46567. y: evt.clientY
  46568. };
  46569. if (!noPreventDefault) {
  46570. evt.preventDefault();
  46571. }
  46572. }
  46573. };
  46574. }
  46575. this._onMouseMove = function (evt) {
  46576. if (!engine.isPointerLock) {
  46577. return;
  46578. }
  46579. if (engine.isInVRExclusivePointerMode) {
  46580. return;
  46581. }
  46582. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46583. if (_this.camera.getScene().useRightHandedSystem)
  46584. offsetX *= -1;
  46585. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46586. offsetX *= -1;
  46587. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46588. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46589. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46590. _this.previousPosition = null;
  46591. if (!noPreventDefault) {
  46592. evt.preventDefault();
  46593. }
  46594. };
  46595. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46596. element.addEventListener("mousemove", this._onMouseMove, false);
  46597. };
  46598. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46599. if (this._observer && element) {
  46600. this.camera.getScene().onPointerObservable.remove(this._observer);
  46601. if (this._onMouseMove) {
  46602. element.removeEventListener("mousemove", this._onMouseMove);
  46603. }
  46604. this._observer = null;
  46605. this._onMouseMove = null;
  46606. this.previousPosition = null;
  46607. }
  46608. };
  46609. FreeCameraMouseInput.prototype.getClassName = function () {
  46610. return "FreeCameraMouseInput";
  46611. };
  46612. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46613. return "mouse";
  46614. };
  46615. __decorate([
  46616. BABYLON.serialize()
  46617. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46618. __decorate([
  46619. BABYLON.serialize()
  46620. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46621. return FreeCameraMouseInput;
  46622. }());
  46623. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46624. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46625. })(BABYLON || (BABYLON = {}));
  46626. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46627. var BABYLON;
  46628. (function (BABYLON) {
  46629. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46630. function FreeCameraKeyboardMoveInput() {
  46631. this._keys = new Array();
  46632. this.keysUp = [38];
  46633. this.keysDown = [40];
  46634. this.keysLeft = [37];
  46635. this.keysRight = [39];
  46636. }
  46637. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46638. var _this = this;
  46639. if (this._onCanvasBlurObserver) {
  46640. return;
  46641. }
  46642. this._scene = this.camera.getScene();
  46643. this._engine = this._scene.getEngine();
  46644. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46645. _this._keys = [];
  46646. });
  46647. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46648. var evt = info.event;
  46649. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46650. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46651. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46652. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46653. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46654. var index = _this._keys.indexOf(evt.keyCode);
  46655. if (index === -1) {
  46656. _this._keys.push(evt.keyCode);
  46657. }
  46658. if (!noPreventDefault) {
  46659. evt.preventDefault();
  46660. }
  46661. }
  46662. }
  46663. else {
  46664. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46665. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46666. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46667. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46668. var index = _this._keys.indexOf(evt.keyCode);
  46669. if (index >= 0) {
  46670. _this._keys.splice(index, 1);
  46671. }
  46672. if (!noPreventDefault) {
  46673. evt.preventDefault();
  46674. }
  46675. }
  46676. }
  46677. });
  46678. };
  46679. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46680. if (this._scene) {
  46681. if (this._onKeyboardObserver) {
  46682. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46683. }
  46684. if (this._onCanvasBlurObserver) {
  46685. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46686. }
  46687. this._onKeyboardObserver = null;
  46688. this._onCanvasBlurObserver = null;
  46689. }
  46690. this._keys = [];
  46691. };
  46692. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46693. if (this._onKeyboardObserver) {
  46694. var camera = this.camera;
  46695. // Keyboard
  46696. for (var index = 0; index < this._keys.length; index++) {
  46697. var keyCode = this._keys[index];
  46698. var speed = camera._computeLocalCameraSpeed();
  46699. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46700. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46701. }
  46702. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46703. camera._localDirection.copyFromFloats(0, 0, speed);
  46704. }
  46705. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46706. camera._localDirection.copyFromFloats(speed, 0, 0);
  46707. }
  46708. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46709. camera._localDirection.copyFromFloats(0, 0, -speed);
  46710. }
  46711. if (camera.getScene().useRightHandedSystem) {
  46712. camera._localDirection.z *= -1;
  46713. }
  46714. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46715. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46716. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46717. }
  46718. }
  46719. };
  46720. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46721. return "FreeCameraKeyboardMoveInput";
  46722. };
  46723. /** @hidden */
  46724. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46725. this._keys = [];
  46726. };
  46727. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46728. return "keyboard";
  46729. };
  46730. __decorate([
  46731. BABYLON.serialize()
  46732. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46733. __decorate([
  46734. BABYLON.serialize()
  46735. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46736. __decorate([
  46737. BABYLON.serialize()
  46738. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46739. __decorate([
  46740. BABYLON.serialize()
  46741. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46742. return FreeCameraKeyboardMoveInput;
  46743. }());
  46744. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46745. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46746. })(BABYLON || (BABYLON = {}));
  46747. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46748. var BABYLON;
  46749. (function (BABYLON) {
  46750. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46751. __extends(FreeCameraInputsManager, _super);
  46752. function FreeCameraInputsManager(camera) {
  46753. return _super.call(this, camera) || this;
  46754. }
  46755. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46756. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46757. return this;
  46758. };
  46759. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46760. if (touchEnabled === void 0) { touchEnabled = true; }
  46761. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46762. return this;
  46763. };
  46764. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46765. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46766. return this;
  46767. };
  46768. FreeCameraInputsManager.prototype.addTouch = function () {
  46769. this.add(new BABYLON.FreeCameraTouchInput());
  46770. return this;
  46771. };
  46772. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46773. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46774. return this;
  46775. };
  46776. return FreeCameraInputsManager;
  46777. }(BABYLON.CameraInputsManager));
  46778. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46779. })(BABYLON || (BABYLON = {}));
  46780. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46781. var BABYLON;
  46782. (function (BABYLON) {
  46783. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46784. // Forcing to use the Universal camera
  46785. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46786. });
  46787. var FreeCamera = /** @class */ (function (_super) {
  46788. __extends(FreeCamera, _super);
  46789. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46790. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46791. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46792. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46793. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46794. _this.checkCollisions = false;
  46795. _this.applyGravity = false;
  46796. _this._needMoveForGravity = false;
  46797. _this._oldPosition = BABYLON.Vector3.Zero();
  46798. _this._diffPosition = BABYLON.Vector3.Zero();
  46799. _this._newPosition = BABYLON.Vector3.Zero();
  46800. // Collisions
  46801. _this._collisionMask = -1;
  46802. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46803. if (collidedMesh === void 0) { collidedMesh = null; }
  46804. //TODO move this to the collision coordinator!
  46805. if (_this.getScene().workerCollisions)
  46806. newPosition.multiplyInPlace(_this._collider._radius);
  46807. var updatePosition = function (newPos) {
  46808. _this._newPosition.copyFrom(newPos);
  46809. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46810. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46811. _this.position.addInPlace(_this._diffPosition);
  46812. if (_this.onCollide && collidedMesh) {
  46813. _this.onCollide(collidedMesh);
  46814. }
  46815. }
  46816. };
  46817. updatePosition(newPosition);
  46818. };
  46819. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46820. _this.inputs.addKeyboard().addMouse();
  46821. return _this;
  46822. }
  46823. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46824. //-- begin properties for backward compatibility for inputs
  46825. /**
  46826. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46827. * Higher values reduce sensitivity.
  46828. */
  46829. get: function () {
  46830. var mouse = this.inputs.attached["mouse"];
  46831. if (mouse)
  46832. return mouse.angularSensibility;
  46833. return 0;
  46834. },
  46835. /**
  46836. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46837. * Higher values reduce sensitivity.
  46838. */
  46839. set: function (value) {
  46840. var mouse = this.inputs.attached["mouse"];
  46841. if (mouse)
  46842. mouse.angularSensibility = value;
  46843. },
  46844. enumerable: true,
  46845. configurable: true
  46846. });
  46847. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46848. get: function () {
  46849. var keyboard = this.inputs.attached["keyboard"];
  46850. if (keyboard)
  46851. return keyboard.keysUp;
  46852. return [];
  46853. },
  46854. set: function (value) {
  46855. var keyboard = this.inputs.attached["keyboard"];
  46856. if (keyboard)
  46857. keyboard.keysUp = value;
  46858. },
  46859. enumerable: true,
  46860. configurable: true
  46861. });
  46862. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46863. get: function () {
  46864. var keyboard = this.inputs.attached["keyboard"];
  46865. if (keyboard)
  46866. return keyboard.keysDown;
  46867. return [];
  46868. },
  46869. set: function (value) {
  46870. var keyboard = this.inputs.attached["keyboard"];
  46871. if (keyboard)
  46872. keyboard.keysDown = value;
  46873. },
  46874. enumerable: true,
  46875. configurable: true
  46876. });
  46877. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46878. get: function () {
  46879. var keyboard = this.inputs.attached["keyboard"];
  46880. if (keyboard)
  46881. return keyboard.keysLeft;
  46882. return [];
  46883. },
  46884. set: function (value) {
  46885. var keyboard = this.inputs.attached["keyboard"];
  46886. if (keyboard)
  46887. keyboard.keysLeft = value;
  46888. },
  46889. enumerable: true,
  46890. configurable: true
  46891. });
  46892. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46893. get: function () {
  46894. var keyboard = this.inputs.attached["keyboard"];
  46895. if (keyboard)
  46896. return keyboard.keysRight;
  46897. return [];
  46898. },
  46899. set: function (value) {
  46900. var keyboard = this.inputs.attached["keyboard"];
  46901. if (keyboard)
  46902. keyboard.keysRight = value;
  46903. },
  46904. enumerable: true,
  46905. configurable: true
  46906. });
  46907. // Controls
  46908. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46909. this.inputs.attachElement(element, noPreventDefault);
  46910. };
  46911. FreeCamera.prototype.detachControl = function (element) {
  46912. this.inputs.detachElement(element);
  46913. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46914. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46915. };
  46916. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46917. get: function () {
  46918. return this._collisionMask;
  46919. },
  46920. set: function (mask) {
  46921. this._collisionMask = !isNaN(mask) ? mask : -1;
  46922. },
  46923. enumerable: true,
  46924. configurable: true
  46925. });
  46926. /** @hidden */
  46927. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46928. var globalPosition;
  46929. if (this.parent) {
  46930. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46931. }
  46932. else {
  46933. globalPosition = this.position;
  46934. }
  46935. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46936. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46937. if (!this._collider) {
  46938. this._collider = new BABYLON.Collider();
  46939. }
  46940. this._collider._radius = this.ellipsoid;
  46941. this._collider.collisionMask = this._collisionMask;
  46942. //no need for clone, as long as gravity is not on.
  46943. var actualDisplacement = displacement;
  46944. //add gravity to the direction to prevent the dual-collision checking
  46945. if (this.applyGravity) {
  46946. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46947. actualDisplacement = displacement.add(this.getScene().gravity);
  46948. }
  46949. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46950. };
  46951. /** @hidden */
  46952. FreeCamera.prototype._checkInputs = function () {
  46953. if (!this._localDirection) {
  46954. this._localDirection = BABYLON.Vector3.Zero();
  46955. this._transformedDirection = BABYLON.Vector3.Zero();
  46956. }
  46957. this.inputs.checkInputs();
  46958. _super.prototype._checkInputs.call(this);
  46959. };
  46960. /** @hidden */
  46961. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46962. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46963. };
  46964. /** @hidden */
  46965. FreeCamera.prototype._updatePosition = function () {
  46966. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46967. this._collideWithWorld(this.cameraDirection);
  46968. }
  46969. else {
  46970. _super.prototype._updatePosition.call(this);
  46971. }
  46972. };
  46973. FreeCamera.prototype.dispose = function () {
  46974. this.inputs.clear();
  46975. _super.prototype.dispose.call(this);
  46976. };
  46977. FreeCamera.prototype.getClassName = function () {
  46978. return "FreeCamera";
  46979. };
  46980. __decorate([
  46981. BABYLON.serializeAsVector3()
  46982. ], FreeCamera.prototype, "ellipsoid", void 0);
  46983. __decorate([
  46984. BABYLON.serializeAsVector3()
  46985. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46986. __decorate([
  46987. BABYLON.serialize()
  46988. ], FreeCamera.prototype, "checkCollisions", void 0);
  46989. __decorate([
  46990. BABYLON.serialize()
  46991. ], FreeCamera.prototype, "applyGravity", void 0);
  46992. return FreeCamera;
  46993. }(BABYLON.TargetCamera));
  46994. BABYLON.FreeCamera = FreeCamera;
  46995. })(BABYLON || (BABYLON = {}));
  46996. //# sourceMappingURL=babylon.freeCamera.js.map
  46997. var BABYLON;
  46998. (function (BABYLON) {
  46999. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47000. function ArcRotateCameraKeyboardMoveInput() {
  47001. this._keys = new Array();
  47002. this.keysUp = [38];
  47003. this.keysDown = [40];
  47004. this.keysLeft = [37];
  47005. this.keysRight = [39];
  47006. this.keysReset = [220];
  47007. this.panningSensibility = 50.0;
  47008. this.zoomingSensibility = 25.0;
  47009. this.useAltToZoom = true;
  47010. }
  47011. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47012. var _this = this;
  47013. if (this._onCanvasBlurObserver) {
  47014. return;
  47015. }
  47016. this._scene = this.camera.getScene();
  47017. this._engine = this._scene.getEngine();
  47018. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47019. _this._keys = [];
  47020. });
  47021. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47022. var evt = info.event;
  47023. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47024. _this._ctrlPressed = evt.ctrlKey;
  47025. _this._altPressed = evt.altKey;
  47026. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47027. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47028. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47029. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47030. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47031. var index = _this._keys.indexOf(evt.keyCode);
  47032. if (index === -1) {
  47033. _this._keys.push(evt.keyCode);
  47034. }
  47035. if (evt.preventDefault) {
  47036. if (!noPreventDefault) {
  47037. evt.preventDefault();
  47038. }
  47039. }
  47040. }
  47041. }
  47042. else {
  47043. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47044. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47045. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47046. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47047. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47048. var index = _this._keys.indexOf(evt.keyCode);
  47049. if (index >= 0) {
  47050. _this._keys.splice(index, 1);
  47051. }
  47052. if (evt.preventDefault) {
  47053. if (!noPreventDefault) {
  47054. evt.preventDefault();
  47055. }
  47056. }
  47057. }
  47058. }
  47059. });
  47060. };
  47061. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47062. if (this._scene) {
  47063. if (this._onKeyboardObserver) {
  47064. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47065. }
  47066. if (this._onCanvasBlurObserver) {
  47067. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47068. }
  47069. this._onKeyboardObserver = null;
  47070. this._onCanvasBlurObserver = null;
  47071. }
  47072. this._keys = [];
  47073. };
  47074. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47075. if (this._onKeyboardObserver) {
  47076. var camera = this.camera;
  47077. for (var index = 0; index < this._keys.length; index++) {
  47078. var keyCode = this._keys[index];
  47079. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47080. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47081. camera.inertialPanningX -= 1 / this.panningSensibility;
  47082. }
  47083. else {
  47084. camera.inertialAlphaOffset -= 0.01;
  47085. }
  47086. }
  47087. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47088. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47089. camera.inertialPanningY += 1 / this.panningSensibility;
  47090. }
  47091. else if (this._altPressed && this.useAltToZoom) {
  47092. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47093. }
  47094. else {
  47095. camera.inertialBetaOffset -= 0.01;
  47096. }
  47097. }
  47098. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47099. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47100. camera.inertialPanningX += 1 / this.panningSensibility;
  47101. }
  47102. else {
  47103. camera.inertialAlphaOffset += 0.01;
  47104. }
  47105. }
  47106. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47107. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47108. camera.inertialPanningY -= 1 / this.panningSensibility;
  47109. }
  47110. else if (this._altPressed && this.useAltToZoom) {
  47111. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47112. }
  47113. else {
  47114. camera.inertialBetaOffset += 0.01;
  47115. }
  47116. }
  47117. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47118. camera.restoreState();
  47119. }
  47120. }
  47121. }
  47122. };
  47123. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47124. return "ArcRotateCameraKeyboardMoveInput";
  47125. };
  47126. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47127. return "keyboard";
  47128. };
  47129. __decorate([
  47130. BABYLON.serialize()
  47131. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47132. __decorate([
  47133. BABYLON.serialize()
  47134. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47135. __decorate([
  47136. BABYLON.serialize()
  47137. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47138. __decorate([
  47139. BABYLON.serialize()
  47140. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47141. __decorate([
  47142. BABYLON.serialize()
  47143. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47144. __decorate([
  47145. BABYLON.serialize()
  47146. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47147. __decorate([
  47148. BABYLON.serialize()
  47149. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47150. __decorate([
  47151. BABYLON.serialize()
  47152. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47153. return ArcRotateCameraKeyboardMoveInput;
  47154. }());
  47155. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47156. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47157. })(BABYLON || (BABYLON = {}));
  47158. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47159. var BABYLON;
  47160. (function (BABYLON) {
  47161. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47162. function ArcRotateCameraMouseWheelInput() {
  47163. this.wheelPrecision = 3.0;
  47164. /**
  47165. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47166. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47167. */
  47168. this.wheelDeltaPercentage = 0;
  47169. }
  47170. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47171. var _this = this;
  47172. this._wheel = function (p, s) {
  47173. //sanity check - this should be a PointerWheel event.
  47174. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47175. return;
  47176. var event = p.event;
  47177. var delta = 0;
  47178. if (event.wheelDelta) {
  47179. if (_this.wheelDeltaPercentage) {
  47180. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47181. if (event.wheelDelta > 0) {
  47182. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47183. }
  47184. else {
  47185. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47186. }
  47187. }
  47188. else {
  47189. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47190. }
  47191. }
  47192. else if (event.detail) {
  47193. delta = -event.detail / _this.wheelPrecision;
  47194. }
  47195. if (delta)
  47196. _this.camera.inertialRadiusOffset += delta;
  47197. if (event.preventDefault) {
  47198. if (!noPreventDefault) {
  47199. event.preventDefault();
  47200. }
  47201. }
  47202. };
  47203. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47204. };
  47205. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47206. if (this._observer && element) {
  47207. this.camera.getScene().onPointerObservable.remove(this._observer);
  47208. this._observer = null;
  47209. this._wheel = null;
  47210. }
  47211. };
  47212. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47213. return "ArcRotateCameraMouseWheelInput";
  47214. };
  47215. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47216. return "mousewheel";
  47217. };
  47218. __decorate([
  47219. BABYLON.serialize()
  47220. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47221. __decorate([
  47222. BABYLON.serialize()
  47223. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47224. return ArcRotateCameraMouseWheelInput;
  47225. }());
  47226. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47227. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47228. })(BABYLON || (BABYLON = {}));
  47229. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47230. var BABYLON;
  47231. (function (BABYLON) {
  47232. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47233. function ArcRotateCameraPointersInput() {
  47234. this.buttons = [0, 1, 2];
  47235. this.angularSensibilityX = 1000.0;
  47236. this.angularSensibilityY = 1000.0;
  47237. this.pinchPrecision = 12.0;
  47238. /**
  47239. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47240. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47241. */
  47242. this.pinchDeltaPercentage = 0;
  47243. this.panningSensibility = 1000.0;
  47244. this.multiTouchPanning = true;
  47245. this.multiTouchPanAndZoom = true;
  47246. this._isPanClick = false;
  47247. this.pinchInwards = true;
  47248. }
  47249. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47250. var _this = this;
  47251. var engine = this.camera.getEngine();
  47252. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47253. var pointA = null;
  47254. var pointB = null;
  47255. var previousPinchSquaredDistance = 0;
  47256. var initialDistance = 0;
  47257. var twoFingerActivityCount = 0;
  47258. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47259. this._pointerInput = function (p, s) {
  47260. var evt = p.event;
  47261. var isTouch = p.event.pointerType === "touch";
  47262. if (engine.isInVRExclusivePointerMode) {
  47263. return;
  47264. }
  47265. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47266. return;
  47267. }
  47268. var srcElement = (evt.srcElement || evt.target);
  47269. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47270. try {
  47271. srcElement.setPointerCapture(evt.pointerId);
  47272. }
  47273. catch (e) {
  47274. //Nothing to do with the error. Execution will continue.
  47275. }
  47276. // Manage panning with pan button click
  47277. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47278. // manage pointers
  47279. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47280. if (pointA === null) {
  47281. pointA = cacheSoloPointer;
  47282. }
  47283. else if (pointB === null) {
  47284. pointB = cacheSoloPointer;
  47285. }
  47286. if (!noPreventDefault) {
  47287. evt.preventDefault();
  47288. element.focus();
  47289. }
  47290. }
  47291. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47292. _this.camera.restoreState();
  47293. }
  47294. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47295. try {
  47296. srcElement.releasePointerCapture(evt.pointerId);
  47297. }
  47298. catch (e) {
  47299. //Nothing to do with the error.
  47300. }
  47301. cacheSoloPointer = null;
  47302. previousPinchSquaredDistance = 0;
  47303. previousMultiTouchPanPosition.isPaning = false;
  47304. previousMultiTouchPanPosition.isPinching = false;
  47305. twoFingerActivityCount = 0;
  47306. initialDistance = 0;
  47307. if (!isTouch) {
  47308. pointB = null; // Mouse and pen are mono pointer
  47309. }
  47310. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47311. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47312. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47313. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47314. if (engine._badOS) {
  47315. pointA = pointB = null;
  47316. }
  47317. else {
  47318. //only remove the impacted pointer in case of multitouch allowing on most
  47319. //platforms switching from rotate to zoom and pan seamlessly.
  47320. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47321. pointA = pointB;
  47322. pointB = null;
  47323. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47324. }
  47325. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47326. pointB = null;
  47327. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47328. }
  47329. else {
  47330. pointA = pointB = null;
  47331. }
  47332. }
  47333. if (!noPreventDefault) {
  47334. evt.preventDefault();
  47335. }
  47336. }
  47337. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47338. if (!noPreventDefault) {
  47339. evt.preventDefault();
  47340. }
  47341. // One button down
  47342. if (pointA && pointB === null && cacheSoloPointer) {
  47343. if (_this.panningSensibility !== 0 &&
  47344. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47345. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47346. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47347. }
  47348. else {
  47349. var offsetX = evt.clientX - cacheSoloPointer.x;
  47350. var offsetY = evt.clientY - cacheSoloPointer.y;
  47351. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47352. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47353. }
  47354. cacheSoloPointer.x = evt.clientX;
  47355. cacheSoloPointer.y = evt.clientY;
  47356. }
  47357. // Two buttons down: pinch/pan
  47358. else if (pointA && pointB) {
  47359. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47360. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47361. ed.x = evt.clientX;
  47362. ed.y = evt.clientY;
  47363. var direction = _this.pinchInwards ? 1 : -1;
  47364. var distX = pointA.x - pointB.x;
  47365. var distY = pointA.y - pointB.y;
  47366. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47367. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47368. if (previousPinchSquaredDistance === 0) {
  47369. initialDistance = pinchDistance;
  47370. previousPinchSquaredDistance = pinchSquaredDistance;
  47371. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47372. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47373. return;
  47374. }
  47375. if (_this.multiTouchPanAndZoom) {
  47376. if (_this.pinchDeltaPercentage) {
  47377. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47378. }
  47379. else {
  47380. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47381. (_this.pinchPrecision *
  47382. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47383. direction);
  47384. }
  47385. if (_this.panningSensibility !== 0) {
  47386. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47387. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47388. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47389. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47390. previousMultiTouchPanPosition.x = pointersCenterX;
  47391. previousMultiTouchPanPosition.y = pointersCenterY;
  47392. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47393. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47394. }
  47395. }
  47396. else {
  47397. twoFingerActivityCount++;
  47398. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47399. if (_this.pinchDeltaPercentage) {
  47400. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47401. }
  47402. else {
  47403. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47404. (_this.pinchPrecision *
  47405. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47406. direction);
  47407. }
  47408. previousMultiTouchPanPosition.isPaning = false;
  47409. previousMultiTouchPanPosition.isPinching = true;
  47410. }
  47411. else {
  47412. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47413. if (!previousMultiTouchPanPosition.isPaning) {
  47414. previousMultiTouchPanPosition.isPaning = true;
  47415. previousMultiTouchPanPosition.isPinching = false;
  47416. previousMultiTouchPanPosition.x = ed.x;
  47417. previousMultiTouchPanPosition.y = ed.y;
  47418. return;
  47419. }
  47420. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47421. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47422. }
  47423. }
  47424. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47425. previousMultiTouchPanPosition.x = ed.x;
  47426. previousMultiTouchPanPosition.y = ed.y;
  47427. }
  47428. }
  47429. previousPinchSquaredDistance = pinchSquaredDistance;
  47430. }
  47431. }
  47432. };
  47433. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47434. this._onContextMenu = function (evt) {
  47435. evt.preventDefault();
  47436. };
  47437. if (!this.camera._useCtrlForPanning) {
  47438. element.addEventListener("contextmenu", this._onContextMenu, false);
  47439. }
  47440. this._onLostFocus = function () {
  47441. //this._keys = [];
  47442. pointA = pointB = null;
  47443. previousPinchSquaredDistance = 0;
  47444. previousMultiTouchPanPosition.isPaning = false;
  47445. previousMultiTouchPanPosition.isPinching = false;
  47446. twoFingerActivityCount = 0;
  47447. cacheSoloPointer = null;
  47448. initialDistance = 0;
  47449. };
  47450. this._onMouseMove = function (evt) {
  47451. if (!engine.isPointerLock) {
  47452. return;
  47453. }
  47454. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47455. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47456. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47457. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47458. if (!noPreventDefault) {
  47459. evt.preventDefault();
  47460. }
  47461. };
  47462. this._onGestureStart = function (e) {
  47463. if (window.MSGesture === undefined) {
  47464. return;
  47465. }
  47466. if (!_this._MSGestureHandler) {
  47467. _this._MSGestureHandler = new MSGesture();
  47468. _this._MSGestureHandler.target = element;
  47469. }
  47470. _this._MSGestureHandler.addPointer(e.pointerId);
  47471. };
  47472. this._onGesture = function (e) {
  47473. _this.camera.radius *= e.scale;
  47474. if (e.preventDefault) {
  47475. if (!noPreventDefault) {
  47476. e.stopPropagation();
  47477. e.preventDefault();
  47478. }
  47479. }
  47480. };
  47481. element.addEventListener("mousemove", this._onMouseMove, false);
  47482. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47483. element.addEventListener("MSGestureChange", this._onGesture, false);
  47484. BABYLON.Tools.RegisterTopRootEvents([
  47485. { name: "blur", handler: this._onLostFocus }
  47486. ]);
  47487. };
  47488. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47489. if (this._onLostFocus) {
  47490. BABYLON.Tools.UnregisterTopRootEvents([
  47491. { name: "blur", handler: this._onLostFocus }
  47492. ]);
  47493. }
  47494. if (element && this._observer) {
  47495. this.camera.getScene().onPointerObservable.remove(this._observer);
  47496. this._observer = null;
  47497. if (this._onContextMenu) {
  47498. element.removeEventListener("contextmenu", this._onContextMenu);
  47499. }
  47500. if (this._onMouseMove) {
  47501. element.removeEventListener("mousemove", this._onMouseMove);
  47502. }
  47503. if (this._onGestureStart) {
  47504. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47505. }
  47506. if (this._onGesture) {
  47507. element.removeEventListener("MSGestureChange", this._onGesture);
  47508. }
  47509. this._isPanClick = false;
  47510. this.pinchInwards = true;
  47511. this._onMouseMove = null;
  47512. this._onGestureStart = null;
  47513. this._onGesture = null;
  47514. this._MSGestureHandler = null;
  47515. this._onLostFocus = null;
  47516. this._onContextMenu = null;
  47517. }
  47518. };
  47519. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47520. return "ArcRotateCameraPointersInput";
  47521. };
  47522. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47523. return "pointers";
  47524. };
  47525. __decorate([
  47526. BABYLON.serialize()
  47527. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47528. __decorate([
  47529. BABYLON.serialize()
  47530. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47531. __decorate([
  47532. BABYLON.serialize()
  47533. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47534. __decorate([
  47535. BABYLON.serialize()
  47536. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47537. __decorate([
  47538. BABYLON.serialize()
  47539. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47540. __decorate([
  47541. BABYLON.serialize()
  47542. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47543. __decorate([
  47544. BABYLON.serialize()
  47545. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47546. __decorate([
  47547. BABYLON.serialize()
  47548. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47549. return ArcRotateCameraPointersInput;
  47550. }());
  47551. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47552. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47553. })(BABYLON || (BABYLON = {}));
  47554. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47555. var BABYLON;
  47556. (function (BABYLON) {
  47557. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47558. __extends(ArcRotateCameraInputsManager, _super);
  47559. function ArcRotateCameraInputsManager(camera) {
  47560. return _super.call(this, camera) || this;
  47561. }
  47562. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47563. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47564. return this;
  47565. };
  47566. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47567. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47568. return this;
  47569. };
  47570. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47571. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47572. return this;
  47573. };
  47574. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47575. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47576. return this;
  47577. };
  47578. return ArcRotateCameraInputsManager;
  47579. }(BABYLON.CameraInputsManager));
  47580. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47581. })(BABYLON || (BABYLON = {}));
  47582. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47583. var BABYLON;
  47584. (function (BABYLON) {
  47585. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47586. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47587. });
  47588. var ArcRotateCamera = /** @class */ (function (_super) {
  47589. __extends(ArcRotateCamera, _super);
  47590. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47591. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47592. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47593. _this.inertialAlphaOffset = 0;
  47594. _this.inertialBetaOffset = 0;
  47595. _this.inertialRadiusOffset = 0;
  47596. _this.lowerAlphaLimit = null;
  47597. _this.upperAlphaLimit = null;
  47598. _this.lowerBetaLimit = 0.01;
  47599. _this.upperBetaLimit = Math.PI;
  47600. _this.lowerRadiusLimit = null;
  47601. _this.upperRadiusLimit = null;
  47602. _this.inertialPanningX = 0;
  47603. _this.inertialPanningY = 0;
  47604. _this.pinchToPanMaxDistance = 20;
  47605. _this.panningDistanceLimit = null;
  47606. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47607. _this.panningInertia = 0.9;
  47608. //-- end properties for backward compatibility for inputs
  47609. _this.zoomOnFactor = 1;
  47610. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47611. _this.allowUpsideDown = true;
  47612. /** @hidden */
  47613. _this._viewMatrix = new BABYLON.Matrix();
  47614. // Panning
  47615. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47616. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47617. _this.checkCollisions = false;
  47618. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47619. _this._previousPosition = BABYLON.Vector3.Zero();
  47620. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47621. _this._newPosition = BABYLON.Vector3.Zero();
  47622. _this._computationVector = BABYLON.Vector3.Zero();
  47623. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47624. if (collidedMesh === void 0) { collidedMesh = null; }
  47625. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47626. newPosition.multiplyInPlace(_this._collider._radius);
  47627. }
  47628. if (!collidedMesh) {
  47629. _this._previousPosition.copyFrom(_this.position);
  47630. }
  47631. else {
  47632. _this.setPosition(newPosition);
  47633. if (_this.onCollide) {
  47634. _this.onCollide(collidedMesh);
  47635. }
  47636. }
  47637. // Recompute because of constraints
  47638. var cosa = Math.cos(_this.alpha);
  47639. var sina = Math.sin(_this.alpha);
  47640. var cosb = Math.cos(_this.beta);
  47641. var sinb = Math.sin(_this.beta);
  47642. if (sinb === 0) {
  47643. sinb = 0.0001;
  47644. }
  47645. var target = _this._getTargetPosition();
  47646. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47647. target.addToRef(_this._computationVector, _this._newPosition);
  47648. _this.position.copyFrom(_this._newPosition);
  47649. var up = _this.upVector;
  47650. if (_this.allowUpsideDown && _this.beta < 0) {
  47651. up = up.clone();
  47652. up = up.negate();
  47653. }
  47654. _this._computeViewMatrix(_this.position, target, up);
  47655. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47656. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47657. _this._collisionTriggered = false;
  47658. };
  47659. _this._target = BABYLON.Vector3.Zero();
  47660. if (target) {
  47661. _this.setTarget(target);
  47662. }
  47663. _this.alpha = alpha;
  47664. _this.beta = beta;
  47665. _this.radius = radius;
  47666. _this.getViewMatrix();
  47667. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47668. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47669. return _this;
  47670. }
  47671. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47672. get: function () {
  47673. return this._target;
  47674. },
  47675. set: function (value) {
  47676. this.setTarget(value);
  47677. },
  47678. enumerable: true,
  47679. configurable: true
  47680. });
  47681. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47682. //-- begin properties for backward compatibility for inputs
  47683. get: function () {
  47684. var pointers = this.inputs.attached["pointers"];
  47685. if (pointers)
  47686. return pointers.angularSensibilityX;
  47687. return 0;
  47688. },
  47689. set: function (value) {
  47690. var pointers = this.inputs.attached["pointers"];
  47691. if (pointers) {
  47692. pointers.angularSensibilityX = value;
  47693. }
  47694. },
  47695. enumerable: true,
  47696. configurable: true
  47697. });
  47698. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47699. get: function () {
  47700. var pointers = this.inputs.attached["pointers"];
  47701. if (pointers)
  47702. return pointers.angularSensibilityY;
  47703. return 0;
  47704. },
  47705. set: function (value) {
  47706. var pointers = this.inputs.attached["pointers"];
  47707. if (pointers) {
  47708. pointers.angularSensibilityY = value;
  47709. }
  47710. },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47715. get: function () {
  47716. var pointers = this.inputs.attached["pointers"];
  47717. if (pointers)
  47718. return pointers.pinchPrecision;
  47719. return 0;
  47720. },
  47721. set: function (value) {
  47722. var pointers = this.inputs.attached["pointers"];
  47723. if (pointers) {
  47724. pointers.pinchPrecision = value;
  47725. }
  47726. },
  47727. enumerable: true,
  47728. configurable: true
  47729. });
  47730. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47731. get: function () {
  47732. var pointers = this.inputs.attached["pointers"];
  47733. if (pointers)
  47734. return pointers.pinchDeltaPercentage;
  47735. return 0;
  47736. },
  47737. set: function (value) {
  47738. var pointers = this.inputs.attached["pointers"];
  47739. if (pointers) {
  47740. pointers.pinchDeltaPercentage = value;
  47741. }
  47742. },
  47743. enumerable: true,
  47744. configurable: true
  47745. });
  47746. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47747. get: function () {
  47748. var pointers = this.inputs.attached["pointers"];
  47749. if (pointers)
  47750. return pointers.panningSensibility;
  47751. return 0;
  47752. },
  47753. set: function (value) {
  47754. var pointers = this.inputs.attached["pointers"];
  47755. if (pointers) {
  47756. pointers.panningSensibility = value;
  47757. }
  47758. },
  47759. enumerable: true,
  47760. configurable: true
  47761. });
  47762. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47763. get: function () {
  47764. var keyboard = this.inputs.attached["keyboard"];
  47765. if (keyboard)
  47766. return keyboard.keysUp;
  47767. return [];
  47768. },
  47769. set: function (value) {
  47770. var keyboard = this.inputs.attached["keyboard"];
  47771. if (keyboard)
  47772. keyboard.keysUp = value;
  47773. },
  47774. enumerable: true,
  47775. configurable: true
  47776. });
  47777. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47778. get: function () {
  47779. var keyboard = this.inputs.attached["keyboard"];
  47780. if (keyboard)
  47781. return keyboard.keysDown;
  47782. return [];
  47783. },
  47784. set: function (value) {
  47785. var keyboard = this.inputs.attached["keyboard"];
  47786. if (keyboard)
  47787. keyboard.keysDown = value;
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47793. get: function () {
  47794. var keyboard = this.inputs.attached["keyboard"];
  47795. if (keyboard)
  47796. return keyboard.keysLeft;
  47797. return [];
  47798. },
  47799. set: function (value) {
  47800. var keyboard = this.inputs.attached["keyboard"];
  47801. if (keyboard)
  47802. keyboard.keysLeft = value;
  47803. },
  47804. enumerable: true,
  47805. configurable: true
  47806. });
  47807. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47808. get: function () {
  47809. var keyboard = this.inputs.attached["keyboard"];
  47810. if (keyboard)
  47811. return keyboard.keysRight;
  47812. return [];
  47813. },
  47814. set: function (value) {
  47815. var keyboard = this.inputs.attached["keyboard"];
  47816. if (keyboard)
  47817. keyboard.keysRight = value;
  47818. },
  47819. enumerable: true,
  47820. configurable: true
  47821. });
  47822. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47823. get: function () {
  47824. var mousewheel = this.inputs.attached["mousewheel"];
  47825. if (mousewheel)
  47826. return mousewheel.wheelPrecision;
  47827. return 0;
  47828. },
  47829. set: function (value) {
  47830. var mousewheel = this.inputs.attached["mousewheel"];
  47831. if (mousewheel)
  47832. mousewheel.wheelPrecision = value;
  47833. },
  47834. enumerable: true,
  47835. configurable: true
  47836. });
  47837. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47838. get: function () {
  47839. var mousewheel = this.inputs.attached["mousewheel"];
  47840. if (mousewheel)
  47841. return mousewheel.wheelDeltaPercentage;
  47842. return 0;
  47843. },
  47844. set: function (value) {
  47845. var mousewheel = this.inputs.attached["mousewheel"];
  47846. if (mousewheel)
  47847. mousewheel.wheelDeltaPercentage = value;
  47848. },
  47849. enumerable: true,
  47850. configurable: true
  47851. });
  47852. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47853. get: function () {
  47854. return this._bouncingBehavior;
  47855. },
  47856. enumerable: true,
  47857. configurable: true
  47858. });
  47859. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47860. get: function () {
  47861. return this._bouncingBehavior != null;
  47862. },
  47863. set: function (value) {
  47864. if (value === this.useBouncingBehavior) {
  47865. return;
  47866. }
  47867. if (value) {
  47868. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47869. this.addBehavior(this._bouncingBehavior);
  47870. }
  47871. else if (this._bouncingBehavior) {
  47872. this.removeBehavior(this._bouncingBehavior);
  47873. this._bouncingBehavior = null;
  47874. }
  47875. },
  47876. enumerable: true,
  47877. configurable: true
  47878. });
  47879. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47880. get: function () {
  47881. return this._framingBehavior;
  47882. },
  47883. enumerable: true,
  47884. configurable: true
  47885. });
  47886. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47887. get: function () {
  47888. return this._framingBehavior != null;
  47889. },
  47890. set: function (value) {
  47891. if (value === this.useFramingBehavior) {
  47892. return;
  47893. }
  47894. if (value) {
  47895. this._framingBehavior = new BABYLON.FramingBehavior();
  47896. this.addBehavior(this._framingBehavior);
  47897. }
  47898. else if (this._framingBehavior) {
  47899. this.removeBehavior(this._framingBehavior);
  47900. this._framingBehavior = null;
  47901. }
  47902. },
  47903. enumerable: true,
  47904. configurable: true
  47905. });
  47906. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47907. get: function () {
  47908. return this._autoRotationBehavior;
  47909. },
  47910. enumerable: true,
  47911. configurable: true
  47912. });
  47913. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47914. get: function () {
  47915. return this._autoRotationBehavior != null;
  47916. },
  47917. set: function (value) {
  47918. if (value === this.useAutoRotationBehavior) {
  47919. return;
  47920. }
  47921. if (value) {
  47922. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47923. this.addBehavior(this._autoRotationBehavior);
  47924. }
  47925. else if (this._autoRotationBehavior) {
  47926. this.removeBehavior(this._autoRotationBehavior);
  47927. this._autoRotationBehavior = null;
  47928. }
  47929. },
  47930. enumerable: true,
  47931. configurable: true
  47932. });
  47933. // Cache
  47934. /** @hidden */
  47935. ArcRotateCamera.prototype._initCache = function () {
  47936. _super.prototype._initCache.call(this);
  47937. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47938. this._cache.alpha = undefined;
  47939. this._cache.beta = undefined;
  47940. this._cache.radius = undefined;
  47941. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47942. };
  47943. /** @hidden */
  47944. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47945. if (!ignoreParentClass) {
  47946. _super.prototype._updateCache.call(this);
  47947. }
  47948. this._cache._target.copyFrom(this._getTargetPosition());
  47949. this._cache.alpha = this.alpha;
  47950. this._cache.beta = this.beta;
  47951. this._cache.radius = this.radius;
  47952. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47953. };
  47954. ArcRotateCamera.prototype._getTargetPosition = function () {
  47955. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47956. var pos = this._targetHost.getAbsolutePosition();
  47957. if (this._targetBoundingCenter) {
  47958. pos.addToRef(this._targetBoundingCenter, this._target);
  47959. }
  47960. else {
  47961. this._target.copyFrom(pos);
  47962. }
  47963. }
  47964. var lockedTargetPosition = this._getLockedTargetPosition();
  47965. if (lockedTargetPosition) {
  47966. return lockedTargetPosition;
  47967. }
  47968. return this._target;
  47969. };
  47970. ArcRotateCamera.prototype.storeState = function () {
  47971. this._storedAlpha = this.alpha;
  47972. this._storedBeta = this.beta;
  47973. this._storedRadius = this.radius;
  47974. this._storedTarget = this._getTargetPosition().clone();
  47975. return _super.prototype.storeState.call(this);
  47976. };
  47977. /**
  47978. * @hidden
  47979. * Restored camera state. You must call storeState() first
  47980. */
  47981. ArcRotateCamera.prototype._restoreStateValues = function () {
  47982. if (!_super.prototype._restoreStateValues.call(this)) {
  47983. return false;
  47984. }
  47985. this.alpha = this._storedAlpha;
  47986. this.beta = this._storedBeta;
  47987. this.radius = this._storedRadius;
  47988. this.setTarget(this._storedTarget.clone());
  47989. this.inertialAlphaOffset = 0;
  47990. this.inertialBetaOffset = 0;
  47991. this.inertialRadiusOffset = 0;
  47992. this.inertialPanningX = 0;
  47993. this.inertialPanningY = 0;
  47994. return true;
  47995. };
  47996. // Synchronized
  47997. /** @hidden */
  47998. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47999. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48000. return false;
  48001. return this._cache._target.equals(this._getTargetPosition())
  48002. && this._cache.alpha === this.alpha
  48003. && this._cache.beta === this.beta
  48004. && this._cache.radius === this.radius
  48005. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48006. };
  48007. // Methods
  48008. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48009. var _this = this;
  48010. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48011. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48012. this._useCtrlForPanning = useCtrlForPanning;
  48013. this._panningMouseButton = panningMouseButton;
  48014. this.inputs.attachElement(element, noPreventDefault);
  48015. this._reset = function () {
  48016. _this.inertialAlphaOffset = 0;
  48017. _this.inertialBetaOffset = 0;
  48018. _this.inertialRadiusOffset = 0;
  48019. _this.inertialPanningX = 0;
  48020. _this.inertialPanningY = 0;
  48021. };
  48022. };
  48023. ArcRotateCamera.prototype.detachControl = function (element) {
  48024. this.inputs.detachElement(element);
  48025. if (this._reset) {
  48026. this._reset();
  48027. }
  48028. };
  48029. /** @hidden */
  48030. ArcRotateCamera.prototype._checkInputs = function () {
  48031. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48032. if (this._collisionTriggered) {
  48033. return;
  48034. }
  48035. this.inputs.checkInputs();
  48036. // Inertia
  48037. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48038. var inertialAlphaOffset = this.inertialAlphaOffset;
  48039. if (this.beta <= 0)
  48040. inertialAlphaOffset *= -1;
  48041. if (this.getScene().useRightHandedSystem)
  48042. inertialAlphaOffset *= -1;
  48043. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48044. inertialAlphaOffset *= -1;
  48045. this.alpha += inertialAlphaOffset;
  48046. this.beta += this.inertialBetaOffset;
  48047. this.radius -= this.inertialRadiusOffset;
  48048. this.inertialAlphaOffset *= this.inertia;
  48049. this.inertialBetaOffset *= this.inertia;
  48050. this.inertialRadiusOffset *= this.inertia;
  48051. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48052. this.inertialAlphaOffset = 0;
  48053. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48054. this.inertialBetaOffset = 0;
  48055. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48056. this.inertialRadiusOffset = 0;
  48057. }
  48058. // Panning inertia
  48059. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48060. if (!this._localDirection) {
  48061. this._localDirection = BABYLON.Vector3.Zero();
  48062. this._transformedDirection = BABYLON.Vector3.Zero();
  48063. }
  48064. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48065. this._localDirection.multiplyInPlace(this.panningAxis);
  48066. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48067. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48068. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48069. if (!this.panningAxis.y) {
  48070. this._transformedDirection.y = 0;
  48071. }
  48072. if (!this._targetHost) {
  48073. if (this.panningDistanceLimit) {
  48074. this._transformedDirection.addInPlace(this._target);
  48075. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48076. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48077. this._target.copyFrom(this._transformedDirection);
  48078. }
  48079. }
  48080. else {
  48081. this._target.addInPlace(this._transformedDirection);
  48082. }
  48083. }
  48084. this.inertialPanningX *= this.panningInertia;
  48085. this.inertialPanningY *= this.panningInertia;
  48086. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48087. this.inertialPanningX = 0;
  48088. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48089. this.inertialPanningY = 0;
  48090. }
  48091. // Limits
  48092. this._checkLimits();
  48093. _super.prototype._checkInputs.call(this);
  48094. };
  48095. ArcRotateCamera.prototype._checkLimits = function () {
  48096. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48097. if (this.allowUpsideDown && this.beta > Math.PI) {
  48098. this.beta = this.beta - (2 * Math.PI);
  48099. }
  48100. }
  48101. else {
  48102. if (this.beta < this.lowerBetaLimit) {
  48103. this.beta = this.lowerBetaLimit;
  48104. }
  48105. }
  48106. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48107. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48108. this.beta = this.beta + (2 * Math.PI);
  48109. }
  48110. }
  48111. else {
  48112. if (this.beta > this.upperBetaLimit) {
  48113. this.beta = this.upperBetaLimit;
  48114. }
  48115. }
  48116. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48117. this.alpha = this.lowerAlphaLimit;
  48118. }
  48119. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48120. this.alpha = this.upperAlphaLimit;
  48121. }
  48122. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48123. this.radius = this.lowerRadiusLimit;
  48124. }
  48125. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48126. this.radius = this.upperRadiusLimit;
  48127. }
  48128. };
  48129. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48130. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48131. this.radius = this._computationVector.length();
  48132. if (this.radius === 0) {
  48133. this.radius = 0.0001; // Just to avoid division by zero
  48134. }
  48135. // Alpha
  48136. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48137. if (this._computationVector.z < 0) {
  48138. this.alpha = 2 * Math.PI - this.alpha;
  48139. }
  48140. // Beta
  48141. this.beta = Math.acos(this._computationVector.y / this.radius);
  48142. this._checkLimits();
  48143. };
  48144. ArcRotateCamera.prototype.setPosition = function (position) {
  48145. if (this.position.equals(position)) {
  48146. return;
  48147. }
  48148. this.position.copyFrom(position);
  48149. this.rebuildAnglesAndRadius();
  48150. };
  48151. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48152. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48153. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48154. if (target.getBoundingInfo) {
  48155. if (toBoundingCenter) {
  48156. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48157. }
  48158. else {
  48159. this._targetBoundingCenter = null;
  48160. }
  48161. this._targetHost = target;
  48162. this._target = this._getTargetPosition();
  48163. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48164. }
  48165. else {
  48166. var newTarget = target;
  48167. var currentTarget = this._getTargetPosition();
  48168. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48169. return;
  48170. }
  48171. this._targetHost = null;
  48172. this._target = newTarget;
  48173. this._targetBoundingCenter = null;
  48174. this.onMeshTargetChangedObservable.notifyObservers(null);
  48175. }
  48176. this.rebuildAnglesAndRadius();
  48177. };
  48178. /** @hidden */
  48179. ArcRotateCamera.prototype._getViewMatrix = function () {
  48180. // Compute
  48181. var cosa = Math.cos(this.alpha);
  48182. var sina = Math.sin(this.alpha);
  48183. var cosb = Math.cos(this.beta);
  48184. var sinb = Math.sin(this.beta);
  48185. if (sinb === 0) {
  48186. sinb = 0.0001;
  48187. }
  48188. var target = this._getTargetPosition();
  48189. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48190. target.addToRef(this._computationVector, this._newPosition);
  48191. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48192. if (!this._collider) {
  48193. this._collider = new BABYLON.Collider();
  48194. }
  48195. this._collider._radius = this.collisionRadius;
  48196. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48197. this._collisionTriggered = true;
  48198. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48199. }
  48200. else {
  48201. this.position.copyFrom(this._newPosition);
  48202. var up = this.upVector;
  48203. if (this.allowUpsideDown && sinb < 0) {
  48204. up = up.clone();
  48205. up = up.negate();
  48206. }
  48207. this._computeViewMatrix(this.position, target, up);
  48208. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48209. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48210. }
  48211. this._currentTarget = target;
  48212. return this._viewMatrix;
  48213. };
  48214. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48215. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48216. meshes = meshes || this.getScene().meshes;
  48217. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48218. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48219. this.radius = distance * this.zoomOnFactor;
  48220. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48221. };
  48222. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48223. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48224. var meshesOrMinMaxVector;
  48225. var distance;
  48226. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48227. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48228. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48229. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48230. }
  48231. else { //minMaxVector and distance
  48232. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48233. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48234. distance = minMaxVectorAndDistance.distance;
  48235. }
  48236. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48237. if (!doNotUpdateMaxZ) {
  48238. this.maxZ = distance * 2;
  48239. }
  48240. };
  48241. /**
  48242. * @override
  48243. * Override Camera.createRigCamera
  48244. */
  48245. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48246. var alphaShift = 0;
  48247. switch (this.cameraRigMode) {
  48248. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48249. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48250. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48251. case BABYLON.Camera.RIG_MODE_VR:
  48252. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48253. break;
  48254. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48255. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48256. break;
  48257. }
  48258. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48259. rigCam._cameraRigParams = {};
  48260. return rigCam;
  48261. };
  48262. /**
  48263. * @hidden
  48264. * @override
  48265. * Override Camera._updateRigCameras
  48266. */
  48267. ArcRotateCamera.prototype._updateRigCameras = function () {
  48268. var camLeft = this._rigCameras[0];
  48269. var camRight = this._rigCameras[1];
  48270. camLeft.beta = camRight.beta = this.beta;
  48271. camLeft.radius = camRight.radius = this.radius;
  48272. switch (this.cameraRigMode) {
  48273. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48275. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48276. case BABYLON.Camera.RIG_MODE_VR:
  48277. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48278. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48279. break;
  48280. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48281. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48282. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48283. break;
  48284. }
  48285. _super.prototype._updateRigCameras.call(this);
  48286. };
  48287. ArcRotateCamera.prototype.dispose = function () {
  48288. this.inputs.clear();
  48289. _super.prototype.dispose.call(this);
  48290. };
  48291. ArcRotateCamera.prototype.getClassName = function () {
  48292. return "ArcRotateCamera";
  48293. };
  48294. __decorate([
  48295. BABYLON.serialize()
  48296. ], ArcRotateCamera.prototype, "alpha", void 0);
  48297. __decorate([
  48298. BABYLON.serialize()
  48299. ], ArcRotateCamera.prototype, "beta", void 0);
  48300. __decorate([
  48301. BABYLON.serialize()
  48302. ], ArcRotateCamera.prototype, "radius", void 0);
  48303. __decorate([
  48304. BABYLON.serializeAsVector3("target")
  48305. ], ArcRotateCamera.prototype, "_target", void 0);
  48306. __decorate([
  48307. BABYLON.serialize()
  48308. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48309. __decorate([
  48310. BABYLON.serialize()
  48311. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48312. __decorate([
  48313. BABYLON.serialize()
  48314. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48315. __decorate([
  48316. BABYLON.serialize()
  48317. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48318. __decorate([
  48319. BABYLON.serialize()
  48320. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48321. __decorate([
  48322. BABYLON.serialize()
  48323. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48324. __decorate([
  48325. BABYLON.serialize()
  48326. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48327. __decorate([
  48328. BABYLON.serialize()
  48329. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48330. __decorate([
  48331. BABYLON.serialize()
  48332. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48333. __decorate([
  48334. BABYLON.serialize()
  48335. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48336. __decorate([
  48337. BABYLON.serialize()
  48338. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48339. __decorate([
  48340. BABYLON.serialize()
  48341. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48342. __decorate([
  48343. BABYLON.serialize()
  48344. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48345. __decorate([
  48346. BABYLON.serializeAsVector3()
  48347. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48348. __decorate([
  48349. BABYLON.serialize()
  48350. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48351. __decorate([
  48352. BABYLON.serialize()
  48353. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48354. __decorate([
  48355. BABYLON.serialize()
  48356. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48357. return ArcRotateCamera;
  48358. }(BABYLON.TargetCamera));
  48359. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48360. })(BABYLON || (BABYLON = {}));
  48361. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48362. var BABYLON;
  48363. (function (BABYLON) {
  48364. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48365. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48366. });
  48367. /**
  48368. * The HemisphericLight simulates the ambient environment light,
  48369. * so the passed direction is the light reflection direction, not the incoming direction.
  48370. */
  48371. var HemisphericLight = /** @class */ (function (_super) {
  48372. __extends(HemisphericLight, _super);
  48373. /**
  48374. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48375. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48376. * The HemisphericLight can't cast shadows.
  48377. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48378. * @param name The friendly name of the light
  48379. * @param direction The direction of the light reflection
  48380. * @param scene The scene the light belongs to
  48381. */
  48382. function HemisphericLight(name, direction, scene) {
  48383. var _this = _super.call(this, name, scene) || this;
  48384. /**
  48385. * The groundColor is the light in the opposite direction to the one specified during creation.
  48386. * 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.
  48387. */
  48388. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48389. _this.direction = direction || BABYLON.Vector3.Up();
  48390. return _this;
  48391. }
  48392. HemisphericLight.prototype._buildUniformLayout = function () {
  48393. this._uniformBuffer.addUniform("vLightData", 4);
  48394. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48395. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48396. this._uniformBuffer.addUniform("vLightGround", 3);
  48397. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48398. this._uniformBuffer.addUniform("depthValues", 2);
  48399. this._uniformBuffer.create();
  48400. };
  48401. /**
  48402. * Returns the string "HemisphericLight".
  48403. * @return The class name
  48404. */
  48405. HemisphericLight.prototype.getClassName = function () {
  48406. return "HemisphericLight";
  48407. };
  48408. /**
  48409. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48410. * Returns the updated direction.
  48411. * @param target The target the direction should point to
  48412. * @return The computed direction
  48413. */
  48414. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48415. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48416. return this.direction;
  48417. };
  48418. /**
  48419. * Returns the shadow generator associated to the light.
  48420. * @returns Always null for hemispheric lights because it does not support shadows.
  48421. */
  48422. HemisphericLight.prototype.getShadowGenerator = function () {
  48423. return null;
  48424. };
  48425. /**
  48426. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48427. * @param effect The effect to update
  48428. * @param lightIndex The index of the light in the effect to update
  48429. * @returns The hemispheric light
  48430. */
  48431. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48432. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48433. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48434. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48435. return this;
  48436. };
  48437. /**
  48438. * @hidden internal use only.
  48439. */
  48440. HemisphericLight.prototype._getWorldMatrix = function () {
  48441. if (!this._worldMatrix) {
  48442. this._worldMatrix = BABYLON.Matrix.Identity();
  48443. }
  48444. return this._worldMatrix;
  48445. };
  48446. /**
  48447. * Returns the integer 3.
  48448. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48449. */
  48450. HemisphericLight.prototype.getTypeID = function () {
  48451. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48452. };
  48453. /**
  48454. * Prepares the list of defines specific to the light type.
  48455. * @param defines the list of defines
  48456. * @param lightIndex defines the index of the light for the effect
  48457. */
  48458. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48459. defines["HEMILIGHT" + lightIndex] = true;
  48460. };
  48461. __decorate([
  48462. BABYLON.serializeAsColor3()
  48463. ], HemisphericLight.prototype, "groundColor", void 0);
  48464. __decorate([
  48465. BABYLON.serializeAsVector3()
  48466. ], HemisphericLight.prototype, "direction", void 0);
  48467. return HemisphericLight;
  48468. }(BABYLON.Light));
  48469. BABYLON.HemisphericLight = HemisphericLight;
  48470. })(BABYLON || (BABYLON = {}));
  48471. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48472. var BABYLON;
  48473. (function (BABYLON) {
  48474. /**
  48475. * Base implementation IShadowLight
  48476. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48477. */
  48478. var ShadowLight = /** @class */ (function (_super) {
  48479. __extends(ShadowLight, _super);
  48480. function ShadowLight() {
  48481. var _this = _super !== null && _super.apply(this, arguments) || this;
  48482. _this._needProjectionMatrixCompute = true;
  48483. return _this;
  48484. }
  48485. ShadowLight.prototype._setPosition = function (value) {
  48486. this._position = value;
  48487. };
  48488. Object.defineProperty(ShadowLight.prototype, "position", {
  48489. /**
  48490. * Sets the position the shadow will be casted from. Also use as the light position for both
  48491. * point and spot lights.
  48492. */
  48493. get: function () {
  48494. return this._position;
  48495. },
  48496. /**
  48497. * Sets the position the shadow will be casted from. Also use as the light position for both
  48498. * point and spot lights.
  48499. */
  48500. set: function (value) {
  48501. this._setPosition(value);
  48502. },
  48503. enumerable: true,
  48504. configurable: true
  48505. });
  48506. ShadowLight.prototype._setDirection = function (value) {
  48507. this._direction = value;
  48508. };
  48509. Object.defineProperty(ShadowLight.prototype, "direction", {
  48510. /**
  48511. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48512. * Also use as the light direction on spot and directional lights.
  48513. */
  48514. get: function () {
  48515. return this._direction;
  48516. },
  48517. /**
  48518. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48519. * Also use as the light direction on spot and directional lights.
  48520. */
  48521. set: function (value) {
  48522. this._setDirection(value);
  48523. },
  48524. enumerable: true,
  48525. configurable: true
  48526. });
  48527. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48528. /**
  48529. * Gets the shadow projection clipping minimum z value.
  48530. */
  48531. get: function () {
  48532. return this._shadowMinZ;
  48533. },
  48534. /**
  48535. * Sets the shadow projection clipping minimum z value.
  48536. */
  48537. set: function (value) {
  48538. this._shadowMinZ = value;
  48539. this.forceProjectionMatrixCompute();
  48540. },
  48541. enumerable: true,
  48542. configurable: true
  48543. });
  48544. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48545. /**
  48546. * Sets the shadow projection clipping maximum z value.
  48547. */
  48548. get: function () {
  48549. return this._shadowMaxZ;
  48550. },
  48551. /**
  48552. * Gets the shadow projection clipping maximum z value.
  48553. */
  48554. set: function (value) {
  48555. this._shadowMaxZ = value;
  48556. this.forceProjectionMatrixCompute();
  48557. },
  48558. enumerable: true,
  48559. configurable: true
  48560. });
  48561. /**
  48562. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48563. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48564. */
  48565. ShadowLight.prototype.computeTransformedInformation = function () {
  48566. if (this.parent && this.parent.getWorldMatrix) {
  48567. if (!this.transformedPosition) {
  48568. this.transformedPosition = BABYLON.Vector3.Zero();
  48569. }
  48570. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48571. // In case the direction is present.
  48572. if (this.direction) {
  48573. if (!this.transformedDirection) {
  48574. this.transformedDirection = BABYLON.Vector3.Zero();
  48575. }
  48576. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48577. }
  48578. return true;
  48579. }
  48580. return false;
  48581. };
  48582. /**
  48583. * Return the depth scale used for the shadow map.
  48584. * @returns the depth scale.
  48585. */
  48586. ShadowLight.prototype.getDepthScale = function () {
  48587. return 50.0;
  48588. };
  48589. /**
  48590. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48591. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48592. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48593. */
  48594. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48595. return this.transformedDirection ? this.transformedDirection : this.direction;
  48596. };
  48597. /**
  48598. * Returns the ShadowLight absolute position in the World.
  48599. * @returns the position vector in world space
  48600. */
  48601. ShadowLight.prototype.getAbsolutePosition = function () {
  48602. return this.transformedPosition ? this.transformedPosition : this.position;
  48603. };
  48604. /**
  48605. * Sets the ShadowLight direction toward the passed target.
  48606. * @param target The point tot target in local space
  48607. * @returns the updated ShadowLight direction
  48608. */
  48609. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48610. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48611. return this.direction;
  48612. };
  48613. /**
  48614. * Returns the light rotation in euler definition.
  48615. * @returns the x y z rotation in local space.
  48616. */
  48617. ShadowLight.prototype.getRotation = function () {
  48618. this.direction.normalize();
  48619. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48620. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48621. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48622. };
  48623. /**
  48624. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48625. * @returns true if a cube texture needs to be use
  48626. */
  48627. ShadowLight.prototype.needCube = function () {
  48628. return false;
  48629. };
  48630. /**
  48631. * Detects if the projection matrix requires to be recomputed this frame.
  48632. * @returns true if it requires to be recomputed otherwise, false.
  48633. */
  48634. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48635. return this._needProjectionMatrixCompute;
  48636. };
  48637. /**
  48638. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48639. */
  48640. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48641. this._needProjectionMatrixCompute = true;
  48642. };
  48643. /**
  48644. * Get the world matrix of the sahdow lights.
  48645. * @hidden Internal Use Only
  48646. */
  48647. ShadowLight.prototype._getWorldMatrix = function () {
  48648. if (!this._worldMatrix) {
  48649. this._worldMatrix = BABYLON.Matrix.Identity();
  48650. }
  48651. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48652. return this._worldMatrix;
  48653. };
  48654. /**
  48655. * Gets the minZ used for shadow according to both the scene and the light.
  48656. * @param activeCamera The camera we are returning the min for
  48657. * @returns the depth min z
  48658. */
  48659. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48660. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48661. };
  48662. /**
  48663. * Gets the maxZ used for shadow according to both the scene and the light.
  48664. * @param activeCamera The camera we are returning the max for
  48665. * @returns the depth max z
  48666. */
  48667. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48668. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48669. };
  48670. /**
  48671. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48672. * @param matrix The materix to updated with the projection information
  48673. * @param viewMatrix The transform matrix of the light
  48674. * @param renderList The list of mesh to render in the map
  48675. * @returns The current light
  48676. */
  48677. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48678. if (this.customProjectionMatrixBuilder) {
  48679. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48680. }
  48681. else {
  48682. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48683. }
  48684. return this;
  48685. };
  48686. __decorate([
  48687. BABYLON.serializeAsVector3()
  48688. ], ShadowLight.prototype, "position", null);
  48689. __decorate([
  48690. BABYLON.serializeAsVector3()
  48691. ], ShadowLight.prototype, "direction", null);
  48692. __decorate([
  48693. BABYLON.serialize()
  48694. ], ShadowLight.prototype, "shadowMinZ", null);
  48695. __decorate([
  48696. BABYLON.serialize()
  48697. ], ShadowLight.prototype, "shadowMaxZ", null);
  48698. return ShadowLight;
  48699. }(BABYLON.Light));
  48700. BABYLON.ShadowLight = ShadowLight;
  48701. })(BABYLON || (BABYLON = {}));
  48702. //# sourceMappingURL=babylon.shadowLight.js.map
  48703. var BABYLON;
  48704. (function (BABYLON) {
  48705. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48706. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48707. });
  48708. /**
  48709. * A point light is a light defined by an unique point in world space.
  48710. * The light is emitted in every direction from this point.
  48711. * A good example of a point light is a standard light bulb.
  48712. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48713. */
  48714. var PointLight = /** @class */ (function (_super) {
  48715. __extends(PointLight, _super);
  48716. /**
  48717. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48718. * A PointLight emits the light in every direction.
  48719. * It can cast shadows.
  48720. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48721. * ```javascript
  48722. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48723. * ```
  48724. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48725. * @param name The light friendly name
  48726. * @param position The position of the point light in the scene
  48727. * @param scene The scene the lights belongs to
  48728. */
  48729. function PointLight(name, position, scene) {
  48730. var _this = _super.call(this, name, scene) || this;
  48731. _this._shadowAngle = Math.PI / 2;
  48732. _this.position = position;
  48733. return _this;
  48734. }
  48735. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48736. /**
  48737. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48738. * This specifies what angle the shadow will use to be created.
  48739. *
  48740. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48741. */
  48742. get: function () {
  48743. return this._shadowAngle;
  48744. },
  48745. /**
  48746. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48747. * This specifies what angle the shadow will use to be created.
  48748. *
  48749. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48750. */
  48751. set: function (value) {
  48752. this._shadowAngle = value;
  48753. this.forceProjectionMatrixCompute();
  48754. },
  48755. enumerable: true,
  48756. configurable: true
  48757. });
  48758. Object.defineProperty(PointLight.prototype, "direction", {
  48759. /**
  48760. * Gets the direction if it has been set.
  48761. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48762. */
  48763. get: function () {
  48764. return this._direction;
  48765. },
  48766. /**
  48767. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48768. */
  48769. set: function (value) {
  48770. var previousNeedCube = this.needCube();
  48771. this._direction = value;
  48772. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48773. this._shadowGenerator.recreateShadowMap();
  48774. }
  48775. },
  48776. enumerable: true,
  48777. configurable: true
  48778. });
  48779. /**
  48780. * Returns the string "PointLight"
  48781. * @returns the class name
  48782. */
  48783. PointLight.prototype.getClassName = function () {
  48784. return "PointLight";
  48785. };
  48786. /**
  48787. * Returns the integer 0.
  48788. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48789. */
  48790. PointLight.prototype.getTypeID = function () {
  48791. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48792. };
  48793. /**
  48794. * Specifies wether or not the shadowmap should be a cube texture.
  48795. * @returns true if the shadowmap needs to be a cube texture.
  48796. */
  48797. PointLight.prototype.needCube = function () {
  48798. return !this.direction;
  48799. };
  48800. /**
  48801. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48802. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48803. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48804. */
  48805. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48806. if (this.direction) {
  48807. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48808. }
  48809. else {
  48810. switch (faceIndex) {
  48811. case 0:
  48812. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48813. case 1:
  48814. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48815. case 2:
  48816. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48817. case 3:
  48818. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48819. case 4:
  48820. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48821. case 5:
  48822. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48823. }
  48824. }
  48825. return BABYLON.Vector3.Zero();
  48826. };
  48827. /**
  48828. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48829. * - fov = PI / 2
  48830. * - aspect ratio : 1.0
  48831. * - z-near and far equal to the active camera minZ and maxZ.
  48832. * Returns the PointLight.
  48833. */
  48834. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48835. var activeCamera = this.getScene().activeCamera;
  48836. if (!activeCamera) {
  48837. return;
  48838. }
  48839. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48840. };
  48841. PointLight.prototype._buildUniformLayout = function () {
  48842. this._uniformBuffer.addUniform("vLightData", 4);
  48843. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48844. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48845. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48846. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48847. this._uniformBuffer.addUniform("depthValues", 2);
  48848. this._uniformBuffer.create();
  48849. };
  48850. /**
  48851. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48852. * @param effect The effect to update
  48853. * @param lightIndex The index of the light in the effect to update
  48854. * @returns The point light
  48855. */
  48856. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48857. if (this.computeTransformedInformation()) {
  48858. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48859. }
  48860. else {
  48861. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48862. }
  48863. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48864. return this;
  48865. };
  48866. /**
  48867. * Prepares the list of defines specific to the light type.
  48868. * @param defines the list of defines
  48869. * @param lightIndex defines the index of the light for the effect
  48870. */
  48871. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48872. defines["POINTLIGHT" + lightIndex] = true;
  48873. };
  48874. __decorate([
  48875. BABYLON.serialize()
  48876. ], PointLight.prototype, "shadowAngle", null);
  48877. return PointLight;
  48878. }(BABYLON.ShadowLight));
  48879. BABYLON.PointLight = PointLight;
  48880. })(BABYLON || (BABYLON = {}));
  48881. //# sourceMappingURL=babylon.pointLight.js.map
  48882. var BABYLON;
  48883. (function (BABYLON) {
  48884. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48885. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48886. });
  48887. /**
  48888. * A directional light is defined by a direction (what a surprise!).
  48889. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48890. * 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.
  48891. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48892. */
  48893. var DirectionalLight = /** @class */ (function (_super) {
  48894. __extends(DirectionalLight, _super);
  48895. /**
  48896. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48897. * The directional light is emitted from everywhere in the given direction.
  48898. * It can cast shawdows.
  48899. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48900. * @param name The friendly name of the light
  48901. * @param direction The direction of the light
  48902. * @param scene The scene the light belongs to
  48903. */
  48904. function DirectionalLight(name, direction, scene) {
  48905. var _this = _super.call(this, name, scene) || this;
  48906. _this._shadowFrustumSize = 0;
  48907. _this._shadowOrthoScale = 0.1;
  48908. /**
  48909. * Automatically compute the projection matrix to best fit (including all the casters)
  48910. * on each frame.
  48911. */
  48912. _this.autoUpdateExtends = true;
  48913. // Cache
  48914. _this._orthoLeft = Number.MAX_VALUE;
  48915. _this._orthoRight = Number.MIN_VALUE;
  48916. _this._orthoTop = Number.MIN_VALUE;
  48917. _this._orthoBottom = Number.MAX_VALUE;
  48918. _this.position = direction.scale(-1.0);
  48919. _this.direction = direction;
  48920. return _this;
  48921. }
  48922. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48923. /**
  48924. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48925. */
  48926. get: function () {
  48927. return this._shadowFrustumSize;
  48928. },
  48929. /**
  48930. * Specifies a fix frustum size for the shadow generation.
  48931. */
  48932. set: function (value) {
  48933. this._shadowFrustumSize = value;
  48934. this.forceProjectionMatrixCompute();
  48935. },
  48936. enumerable: true,
  48937. configurable: true
  48938. });
  48939. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48940. /**
  48941. * Gets the shadow projection scale against the optimal computed one.
  48942. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48943. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48944. */
  48945. get: function () {
  48946. return this._shadowOrthoScale;
  48947. },
  48948. /**
  48949. * Sets the shadow projection scale against the optimal computed one.
  48950. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48951. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48952. */
  48953. set: function (value) {
  48954. this._shadowOrthoScale = value;
  48955. this.forceProjectionMatrixCompute();
  48956. },
  48957. enumerable: true,
  48958. configurable: true
  48959. });
  48960. /**
  48961. * Returns the string "DirectionalLight".
  48962. * @return The class name
  48963. */
  48964. DirectionalLight.prototype.getClassName = function () {
  48965. return "DirectionalLight";
  48966. };
  48967. /**
  48968. * Returns the integer 1.
  48969. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48970. */
  48971. DirectionalLight.prototype.getTypeID = function () {
  48972. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48973. };
  48974. /**
  48975. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48976. * Returns the DirectionalLight Shadow projection matrix.
  48977. */
  48978. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48979. if (this.shadowFrustumSize > 0) {
  48980. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48981. }
  48982. else {
  48983. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48984. }
  48985. };
  48986. /**
  48987. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48988. * Returns the DirectionalLight Shadow projection matrix.
  48989. */
  48990. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48991. var activeCamera = this.getScene().activeCamera;
  48992. if (!activeCamera) {
  48993. return;
  48994. }
  48995. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48996. };
  48997. /**
  48998. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48999. * Returns the DirectionalLight Shadow projection matrix.
  49000. */
  49001. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49002. var activeCamera = this.getScene().activeCamera;
  49003. if (!activeCamera) {
  49004. return;
  49005. }
  49006. // Check extends
  49007. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49008. var tempVector3 = BABYLON.Vector3.Zero();
  49009. this._orthoLeft = Number.MAX_VALUE;
  49010. this._orthoRight = Number.MIN_VALUE;
  49011. this._orthoTop = Number.MIN_VALUE;
  49012. this._orthoBottom = Number.MAX_VALUE;
  49013. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49014. var mesh = renderList[meshIndex];
  49015. if (!mesh) {
  49016. continue;
  49017. }
  49018. var boundingInfo = mesh.getBoundingInfo();
  49019. var boundingBox = boundingInfo.boundingBox;
  49020. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49021. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49022. if (tempVector3.x < this._orthoLeft)
  49023. this._orthoLeft = tempVector3.x;
  49024. if (tempVector3.y < this._orthoBottom)
  49025. this._orthoBottom = tempVector3.y;
  49026. if (tempVector3.x > this._orthoRight)
  49027. this._orthoRight = tempVector3.x;
  49028. if (tempVector3.y > this._orthoTop)
  49029. this._orthoTop = tempVector3.y;
  49030. }
  49031. }
  49032. }
  49033. var xOffset = this._orthoRight - this._orthoLeft;
  49034. var yOffset = this._orthoTop - this._orthoBottom;
  49035. 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);
  49036. };
  49037. DirectionalLight.prototype._buildUniformLayout = function () {
  49038. this._uniformBuffer.addUniform("vLightData", 4);
  49039. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49040. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49041. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49042. this._uniformBuffer.addUniform("depthValues", 2);
  49043. this._uniformBuffer.create();
  49044. };
  49045. /**
  49046. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49047. * @param effect The effect to update
  49048. * @param lightIndex The index of the light in the effect to update
  49049. * @returns The directional light
  49050. */
  49051. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49052. if (this.computeTransformedInformation()) {
  49053. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49054. return this;
  49055. }
  49056. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49057. return this;
  49058. };
  49059. /**
  49060. * Gets the minZ used for shadow according to both the scene and the light.
  49061. *
  49062. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49063. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49064. * @param activeCamera The camera we are returning the min for
  49065. * @returns the depth min z
  49066. */
  49067. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49068. return 1;
  49069. };
  49070. /**
  49071. * Gets the maxZ used for shadow according to both the scene and the light.
  49072. *
  49073. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49074. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49075. * @param activeCamera The camera we are returning the max for
  49076. * @returns the depth max z
  49077. */
  49078. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49079. return 1;
  49080. };
  49081. /**
  49082. * Prepares the list of defines specific to the light type.
  49083. * @param defines the list of defines
  49084. * @param lightIndex defines the index of the light for the effect
  49085. */
  49086. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49087. defines["DIRLIGHT" + lightIndex] = true;
  49088. };
  49089. __decorate([
  49090. BABYLON.serialize()
  49091. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49092. __decorate([
  49093. BABYLON.serialize()
  49094. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49095. __decorate([
  49096. BABYLON.serialize()
  49097. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49098. return DirectionalLight;
  49099. }(BABYLON.ShadowLight));
  49100. BABYLON.DirectionalLight = DirectionalLight;
  49101. })(BABYLON || (BABYLON = {}));
  49102. //# sourceMappingURL=babylon.directionalLight.js.map
  49103. var BABYLON;
  49104. (function (BABYLON) {
  49105. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49106. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49107. });
  49108. /**
  49109. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49110. * These values define a cone of light starting from the position, emitting toward the direction.
  49111. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49112. * and the exponent defines the speed of the decay of the light with distance (reach).
  49113. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49114. */
  49115. var SpotLight = /** @class */ (function (_super) {
  49116. __extends(SpotLight, _super);
  49117. /**
  49118. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49119. * It can cast shadows.
  49120. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49121. * @param name The light friendly name
  49122. * @param position The position of the spot light in the scene
  49123. * @param direction The direction of the light in the scene
  49124. * @param angle The cone angle of the light in Radians
  49125. * @param exponent The light decay speed with the distance from the emission spot
  49126. * @param scene The scene the lights belongs to
  49127. */
  49128. function SpotLight(name, position, direction, angle, exponent, scene) {
  49129. var _this = _super.call(this, name, scene) || this;
  49130. _this._innerAngle = 0;
  49131. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49132. _this._projectionTextureLightNear = 1e-6;
  49133. _this._projectionTextureLightFar = 1000.0;
  49134. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49135. _this._projectionTextureViewLightDirty = true;
  49136. _this._projectionTextureProjectionLightDirty = true;
  49137. _this._projectionTextureDirty = true;
  49138. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49139. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49140. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49141. _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);
  49142. _this.position = position;
  49143. _this.direction = direction;
  49144. _this.angle = angle;
  49145. _this.exponent = exponent;
  49146. return _this;
  49147. }
  49148. Object.defineProperty(SpotLight.prototype, "angle", {
  49149. /**
  49150. * Gets the cone angle of the spot light in Radians.
  49151. */
  49152. get: function () {
  49153. return this._angle;
  49154. },
  49155. /**
  49156. * Sets the cone angle of the spot light in Radians.
  49157. */
  49158. set: function (value) {
  49159. this._angle = value;
  49160. this._cosHalfAngle = Math.cos(value * 0.5);
  49161. this._projectionTextureProjectionLightDirty = true;
  49162. this.forceProjectionMatrixCompute();
  49163. this._computeAngleValues();
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49169. /**
  49170. * Only used in gltf falloff mode, this defines the angle where
  49171. * the directional falloff will start before cutting at angle which could be seen
  49172. * as outer angle.
  49173. */
  49174. get: function () {
  49175. return this._angle;
  49176. },
  49177. /**
  49178. * Only used in gltf falloff mode, this defines the angle where
  49179. * the directional falloff will start before cutting at angle which could be seen
  49180. * as outer angle.
  49181. */
  49182. set: function (value) {
  49183. this._innerAngle = value;
  49184. this._computeAngleValues();
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49190. /**
  49191. * Allows scaling the angle of the light for shadow generation only.
  49192. */
  49193. get: function () {
  49194. return this._shadowAngleScale;
  49195. },
  49196. /**
  49197. * Allows scaling the angle of the light for shadow generation only.
  49198. */
  49199. set: function (value) {
  49200. this._shadowAngleScale = value;
  49201. this.forceProjectionMatrixCompute();
  49202. },
  49203. enumerable: true,
  49204. configurable: true
  49205. });
  49206. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49207. /**
  49208. * Allows reading the projecton texture
  49209. */
  49210. get: function () {
  49211. return this._projectionTextureMatrix;
  49212. },
  49213. enumerable: true,
  49214. configurable: true
  49215. });
  49216. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49217. /**
  49218. * Gets the near clip of the Spotlight for texture projection.
  49219. */
  49220. get: function () {
  49221. return this._projectionTextureLightNear;
  49222. },
  49223. /**
  49224. * Sets the near clip of the Spotlight for texture projection.
  49225. */
  49226. set: function (value) {
  49227. this._projectionTextureLightNear = value;
  49228. this._projectionTextureProjectionLightDirty = true;
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49234. /**
  49235. * Gets the far clip of the Spotlight for texture projection.
  49236. */
  49237. get: function () {
  49238. return this._projectionTextureLightFar;
  49239. },
  49240. /**
  49241. * Sets the far clip of the Spotlight for texture projection.
  49242. */
  49243. set: function (value) {
  49244. this._projectionTextureLightFar = value;
  49245. this._projectionTextureProjectionLightDirty = true;
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49251. /**
  49252. * Gets the Up vector of the Spotlight for texture projection.
  49253. */
  49254. get: function () {
  49255. return this._projectionTextureUpDirection;
  49256. },
  49257. /**
  49258. * Sets the Up vector of the Spotlight for texture projection.
  49259. */
  49260. set: function (value) {
  49261. this._projectionTextureUpDirection = value;
  49262. this._projectionTextureProjectionLightDirty = true;
  49263. },
  49264. enumerable: true,
  49265. configurable: true
  49266. });
  49267. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49268. /**
  49269. * Gets the projection texture of the light.
  49270. */
  49271. get: function () {
  49272. return this._projectionTexture;
  49273. },
  49274. /**
  49275. * Sets the projection texture of the light.
  49276. */
  49277. set: function (value) {
  49278. this._projectionTexture = value;
  49279. this._projectionTextureDirty = true;
  49280. },
  49281. enumerable: true,
  49282. configurable: true
  49283. });
  49284. /**
  49285. * Returns the string "SpotLight".
  49286. * @returns the class name
  49287. */
  49288. SpotLight.prototype.getClassName = function () {
  49289. return "SpotLight";
  49290. };
  49291. /**
  49292. * Returns the integer 2.
  49293. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49294. */
  49295. SpotLight.prototype.getTypeID = function () {
  49296. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49297. };
  49298. /**
  49299. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49300. */
  49301. SpotLight.prototype._setDirection = function (value) {
  49302. _super.prototype._setDirection.call(this, value);
  49303. this._projectionTextureViewLightDirty = true;
  49304. };
  49305. /**
  49306. * Overrides the position setter to recompute the projection texture view light Matrix.
  49307. */
  49308. SpotLight.prototype._setPosition = function (value) {
  49309. _super.prototype._setPosition.call(this, value);
  49310. this._projectionTextureViewLightDirty = true;
  49311. };
  49312. /**
  49313. * 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.
  49314. * Returns the SpotLight.
  49315. */
  49316. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49317. var activeCamera = this.getScene().activeCamera;
  49318. if (!activeCamera) {
  49319. return;
  49320. }
  49321. this._shadowAngleScale = this._shadowAngleScale || 1;
  49322. var angle = this._shadowAngleScale * this._angle;
  49323. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49324. };
  49325. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49326. this._projectionTextureViewLightDirty = false;
  49327. this._projectionTextureDirty = true;
  49328. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49329. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49330. };
  49331. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49332. this._projectionTextureProjectionLightDirty = false;
  49333. this._projectionTextureDirty = true;
  49334. var light_far = this.projectionTextureLightFar;
  49335. var light_near = this.projectionTextureLightNear;
  49336. var P = light_far / (light_far - light_near);
  49337. var Q = -P * light_near;
  49338. var S = 1.0 / Math.tan(this._angle / 2.0);
  49339. var A = 1.0;
  49340. 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);
  49341. };
  49342. /**
  49343. * Main function for light texture projection matrix computing.
  49344. */
  49345. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49346. this._projectionTextureDirty = false;
  49347. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49348. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49349. };
  49350. SpotLight.prototype._buildUniformLayout = function () {
  49351. this._uniformBuffer.addUniform("vLightData", 4);
  49352. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49353. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49354. this._uniformBuffer.addUniform("vLightDirection", 3);
  49355. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49356. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49357. this._uniformBuffer.addUniform("depthValues", 2);
  49358. this._uniformBuffer.create();
  49359. };
  49360. SpotLight.prototype._computeAngleValues = function () {
  49361. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49362. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49363. };
  49364. /**
  49365. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49366. * @param effect The effect to update
  49367. * @param lightIndex The index of the light in the effect to update
  49368. * @returns The spot light
  49369. */
  49370. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49371. var normalizeDirection;
  49372. if (this.computeTransformedInformation()) {
  49373. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49374. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49375. }
  49376. else {
  49377. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49378. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49379. }
  49380. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49381. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49382. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49383. if (this._projectionTextureViewLightDirty) {
  49384. this._computeProjectionTextureViewLightMatrix();
  49385. }
  49386. if (this._projectionTextureProjectionLightDirty) {
  49387. this._computeProjectionTextureProjectionLightMatrix();
  49388. }
  49389. if (this._projectionTextureDirty) {
  49390. this._computeProjectionTextureMatrix();
  49391. }
  49392. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49393. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49394. }
  49395. return this;
  49396. };
  49397. /**
  49398. * Disposes the light and the associated resources.
  49399. */
  49400. SpotLight.prototype.dispose = function () {
  49401. _super.prototype.dispose.call(this);
  49402. if (this._projectionTexture) {
  49403. this._projectionTexture.dispose();
  49404. }
  49405. };
  49406. /**
  49407. * Prepares the list of defines specific to the light type.
  49408. * @param defines the list of defines
  49409. * @param lightIndex defines the index of the light for the effect
  49410. */
  49411. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49412. defines["SPOTLIGHT" + lightIndex] = true;
  49413. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49414. };
  49415. __decorate([
  49416. BABYLON.serialize()
  49417. ], SpotLight.prototype, "angle", null);
  49418. __decorate([
  49419. BABYLON.serialize()
  49420. ], SpotLight.prototype, "innerAngle", null);
  49421. __decorate([
  49422. BABYLON.serialize()
  49423. ], SpotLight.prototype, "shadowAngleScale", null);
  49424. __decorate([
  49425. BABYLON.serialize()
  49426. ], SpotLight.prototype, "exponent", void 0);
  49427. __decorate([
  49428. BABYLON.serialize()
  49429. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49430. __decorate([
  49431. BABYLON.serialize()
  49432. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49433. __decorate([
  49434. BABYLON.serialize()
  49435. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49436. __decorate([
  49437. BABYLON.serializeAsTexture("projectedLightTexture")
  49438. ], SpotLight.prototype, "_projectionTexture", void 0);
  49439. return SpotLight;
  49440. }(BABYLON.ShadowLight));
  49441. BABYLON.SpotLight = SpotLight;
  49442. })(BABYLON || (BABYLON = {}));
  49443. //# sourceMappingURL=babylon.spotLight.js.map
  49444. var BABYLON;
  49445. (function (BABYLON) {
  49446. /**
  49447. * Class used to override all child animations of a given target
  49448. */
  49449. var AnimationPropertiesOverride = /** @class */ (function () {
  49450. function AnimationPropertiesOverride() {
  49451. /**
  49452. * Gets or sets a value indicating if animation blending must be used
  49453. */
  49454. this.enableBlending = false;
  49455. /**
  49456. * Gets or sets the blending speed to use when enableBlending is true
  49457. */
  49458. this.blendingSpeed = 0.01;
  49459. /**
  49460. * Gets or sets the default loop mode to use
  49461. */
  49462. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49463. }
  49464. return AnimationPropertiesOverride;
  49465. }());
  49466. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49467. })(BABYLON || (BABYLON = {}));
  49468. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49469. var BABYLON;
  49470. (function (BABYLON) {
  49471. /**
  49472. * Represents the range of an animation
  49473. */
  49474. var AnimationRange = /** @class */ (function () {
  49475. /**
  49476. * Initializes the range of an animation
  49477. * @param name The name of the animation range
  49478. * @param from The starting frame of the animation
  49479. * @param to The ending frame of the animation
  49480. */
  49481. function AnimationRange(
  49482. /**The name of the animation range**/
  49483. name,
  49484. /**The starting frame of the animation */
  49485. from,
  49486. /**The ending frame of the animation*/
  49487. to) {
  49488. this.name = name;
  49489. this.from = from;
  49490. this.to = to;
  49491. }
  49492. /**
  49493. * Makes a copy of the animation range
  49494. * @returns A copy of the animation range
  49495. */
  49496. AnimationRange.prototype.clone = function () {
  49497. return new AnimationRange(this.name, this.from, this.to);
  49498. };
  49499. return AnimationRange;
  49500. }());
  49501. BABYLON.AnimationRange = AnimationRange;
  49502. /**
  49503. * Composed of a frame, and an action function
  49504. */
  49505. var AnimationEvent = /** @class */ (function () {
  49506. /**
  49507. * Initializes the animation event
  49508. * @param frame The frame for which the event is triggered
  49509. * @param action The event to perform when triggered
  49510. * @param onlyOnce Specifies if the event should be triggered only once
  49511. */
  49512. function AnimationEvent(
  49513. /** The frame for which the event is triggered **/
  49514. frame,
  49515. /** The event to perform when triggered **/
  49516. action,
  49517. /** Specifies if the event should be triggered only once**/
  49518. onlyOnce) {
  49519. this.frame = frame;
  49520. this.action = action;
  49521. this.onlyOnce = onlyOnce;
  49522. /**
  49523. * Specifies if the animation event is done
  49524. */
  49525. this.isDone = false;
  49526. }
  49527. /** @hidden */
  49528. AnimationEvent.prototype._clone = function () {
  49529. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49530. };
  49531. return AnimationEvent;
  49532. }());
  49533. BABYLON.AnimationEvent = AnimationEvent;
  49534. /**
  49535. * A cursor which tracks a point on a path
  49536. */
  49537. var PathCursor = /** @class */ (function () {
  49538. /**
  49539. * Initializes the path cursor
  49540. * @param path The path to track
  49541. */
  49542. function PathCursor(path) {
  49543. this.path = path;
  49544. /**
  49545. * Stores path cursor callbacks for when an onchange event is triggered
  49546. */
  49547. this._onchange = new Array();
  49548. /**
  49549. * The value of the path cursor
  49550. */
  49551. this.value = 0;
  49552. /**
  49553. * The animation array of the path cursor
  49554. */
  49555. this.animations = new Array();
  49556. }
  49557. /**
  49558. * Gets the cursor point on the path
  49559. * @returns A point on the path cursor at the cursor location
  49560. */
  49561. PathCursor.prototype.getPoint = function () {
  49562. var point = this.path.getPointAtLengthPosition(this.value);
  49563. return new BABYLON.Vector3(point.x, 0, point.y);
  49564. };
  49565. /**
  49566. * Moves the cursor ahead by the step amount
  49567. * @param step The amount to move the cursor forward
  49568. * @returns This path cursor
  49569. */
  49570. PathCursor.prototype.moveAhead = function (step) {
  49571. if (step === void 0) { step = 0.002; }
  49572. this.move(step);
  49573. return this;
  49574. };
  49575. /**
  49576. * Moves the cursor behind by the step amount
  49577. * @param step The amount to move the cursor back
  49578. * @returns This path cursor
  49579. */
  49580. PathCursor.prototype.moveBack = function (step) {
  49581. if (step === void 0) { step = 0.002; }
  49582. this.move(-step);
  49583. return this;
  49584. };
  49585. /**
  49586. * Moves the cursor by the step amount
  49587. * If the step amount is greater than one, an exception is thrown
  49588. * @param step The amount to move the cursor
  49589. * @returns This path cursor
  49590. */
  49591. PathCursor.prototype.move = function (step) {
  49592. if (Math.abs(step) > 1) {
  49593. throw "step size should be less than 1.";
  49594. }
  49595. this.value += step;
  49596. this.ensureLimits();
  49597. this.raiseOnChange();
  49598. return this;
  49599. };
  49600. /**
  49601. * Ensures that the value is limited between zero and one
  49602. * @returns This path cursor
  49603. */
  49604. PathCursor.prototype.ensureLimits = function () {
  49605. while (this.value > 1) {
  49606. this.value -= 1;
  49607. }
  49608. while (this.value < 0) {
  49609. this.value += 1;
  49610. }
  49611. return this;
  49612. };
  49613. /**
  49614. * Runs onchange callbacks on change (used by the animation engine)
  49615. * @returns This path cursor
  49616. */
  49617. PathCursor.prototype.raiseOnChange = function () {
  49618. var _this = this;
  49619. this._onchange.forEach(function (f) { return f(_this); });
  49620. return this;
  49621. };
  49622. /**
  49623. * Executes a function on change
  49624. * @param f A path cursor onchange callback
  49625. * @returns This path cursor
  49626. */
  49627. PathCursor.prototype.onchange = function (f) {
  49628. this._onchange.push(f);
  49629. return this;
  49630. };
  49631. return PathCursor;
  49632. }());
  49633. BABYLON.PathCursor = PathCursor;
  49634. /**
  49635. * Enum for the animation key frame interpolation type
  49636. */
  49637. var AnimationKeyInterpolation;
  49638. (function (AnimationKeyInterpolation) {
  49639. /**
  49640. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49641. */
  49642. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49643. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49644. /**
  49645. * Class used to store any kind of animation
  49646. */
  49647. var Animation = /** @class */ (function () {
  49648. /**
  49649. * Initializes the animation
  49650. * @param name Name of the animation
  49651. * @param targetProperty Property to animate
  49652. * @param framePerSecond The frames per second of the animation
  49653. * @param dataType The data type of the animation
  49654. * @param loopMode The loop mode of the animation
  49655. * @param enableBlendings Specifies if blending should be enabled
  49656. */
  49657. function Animation(
  49658. /**Name of the animation */
  49659. name,
  49660. /**Property to animate */
  49661. targetProperty,
  49662. /**The frames per second of the animation */
  49663. framePerSecond,
  49664. /**The data type of the animation */
  49665. dataType,
  49666. /**The loop mode of the animation */
  49667. loopMode,
  49668. /**Specifies if blending should be enabled */
  49669. enableBlending) {
  49670. this.name = name;
  49671. this.targetProperty = targetProperty;
  49672. this.framePerSecond = framePerSecond;
  49673. this.dataType = dataType;
  49674. this.loopMode = loopMode;
  49675. this.enableBlending = enableBlending;
  49676. /**
  49677. * @hidden Internal use only
  49678. */
  49679. this._runtimeAnimations = new Array();
  49680. /**
  49681. * The set of event that will be linked to this animation
  49682. */
  49683. this._events = new Array();
  49684. /**
  49685. * Stores the blending speed of the animation
  49686. */
  49687. this.blendingSpeed = 0.01;
  49688. /**
  49689. * Stores the animation ranges for the animation
  49690. */
  49691. this._ranges = {};
  49692. this.targetPropertyPath = targetProperty.split(".");
  49693. this.dataType = dataType;
  49694. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49695. }
  49696. /**
  49697. * @hidden Internal use
  49698. */
  49699. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49700. var dataType = undefined;
  49701. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49702. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49703. }
  49704. else if (from instanceof BABYLON.Quaternion) {
  49705. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49706. }
  49707. else if (from instanceof BABYLON.Vector3) {
  49708. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49709. }
  49710. else if (from instanceof BABYLON.Vector2) {
  49711. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49712. }
  49713. else if (from instanceof BABYLON.Color3) {
  49714. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49715. }
  49716. else if (from instanceof BABYLON.Size) {
  49717. dataType = Animation.ANIMATIONTYPE_SIZE;
  49718. }
  49719. if (dataType == undefined) {
  49720. return null;
  49721. }
  49722. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49723. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49724. animation.setKeys(keys);
  49725. if (easingFunction !== undefined) {
  49726. animation.setEasingFunction(easingFunction);
  49727. }
  49728. return animation;
  49729. };
  49730. /**
  49731. * Sets up an animation
  49732. * @param property The property to animate
  49733. * @param animationType The animation type to apply
  49734. * @param framePerSecond The frames per second of the animation
  49735. * @param easingFunction The easing function used in the animation
  49736. * @returns The created animation
  49737. */
  49738. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49739. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49740. animation.setEasingFunction(easingFunction);
  49741. return animation;
  49742. };
  49743. /**
  49744. * Create and start an animation on a node
  49745. * @param name defines the name of the global animation that will be run on all nodes
  49746. * @param node defines the root node where the animation will take place
  49747. * @param targetProperty defines property to animate
  49748. * @param framePerSecond defines the number of frame per second yo use
  49749. * @param totalFrame defines the number of frames in total
  49750. * @param from defines the initial value
  49751. * @param to defines the final value
  49752. * @param loopMode defines which loop mode you want to use (off by default)
  49753. * @param easingFunction defines the easing function to use (linear by default)
  49754. * @param onAnimationEnd defines the callback to call when animation end
  49755. * @returns the animatable created for this animation
  49756. */
  49757. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49758. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49759. if (!animation) {
  49760. return null;
  49761. }
  49762. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49763. };
  49764. /**
  49765. * Create and start an animation on a node and its descendants
  49766. * @param name defines the name of the global animation that will be run on all nodes
  49767. * @param node defines the root node where the animation will take place
  49768. * @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
  49769. * @param targetProperty defines property to animate
  49770. * @param framePerSecond defines the number of frame per second to use
  49771. * @param totalFrame defines the number of frames in total
  49772. * @param from defines the initial value
  49773. * @param to defines the final value
  49774. * @param loopMode defines which loop mode you want to use (off by default)
  49775. * @param easingFunction defines the easing function to use (linear by default)
  49776. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49777. * @returns the list of animatables created for all nodes
  49778. * @example https://www.babylonjs-playground.com/#MH0VLI
  49779. */
  49780. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49781. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49782. if (!animation) {
  49783. return null;
  49784. }
  49785. var scene = node.getScene();
  49786. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49787. };
  49788. /**
  49789. * Creates a new animation, merges it with the existing animations and starts it
  49790. * @param name Name of the animation
  49791. * @param node Node which contains the scene that begins the animations
  49792. * @param targetProperty Specifies which property to animate
  49793. * @param framePerSecond The frames per second of the animation
  49794. * @param totalFrame The total number of frames
  49795. * @param from The frame at the beginning of the animation
  49796. * @param to The frame at the end of the animation
  49797. * @param loopMode Specifies the loop mode of the animation
  49798. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49799. * @param onAnimationEnd Callback to run once the animation is complete
  49800. * @returns Nullable animation
  49801. */
  49802. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49803. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49804. if (!animation) {
  49805. return null;
  49806. }
  49807. node.animations.push(animation);
  49808. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49809. };
  49810. /**
  49811. * Transition property of an host to the target Value
  49812. * @param property The property to transition
  49813. * @param targetValue The target Value of the property
  49814. * @param host The object where the property to animate belongs
  49815. * @param scene Scene used to run the animation
  49816. * @param frameRate Framerate (in frame/s) to use
  49817. * @param transition The transition type we want to use
  49818. * @param duration The duration of the animation, in milliseconds
  49819. * @param onAnimationEnd Callback trigger at the end of the animation
  49820. * @returns Nullable animation
  49821. */
  49822. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49823. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49824. if (duration <= 0) {
  49825. host[property] = targetValue;
  49826. if (onAnimationEnd) {
  49827. onAnimationEnd();
  49828. }
  49829. return null;
  49830. }
  49831. var endFrame = frameRate * (duration / 1000);
  49832. transition.setKeys([{
  49833. frame: 0,
  49834. value: host[property].clone ? host[property].clone() : host[property]
  49835. },
  49836. {
  49837. frame: endFrame,
  49838. value: targetValue
  49839. }]);
  49840. if (!host.animations) {
  49841. host.animations = [];
  49842. }
  49843. host.animations.push(transition);
  49844. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49845. animation.onAnimationEnd = onAnimationEnd;
  49846. return animation;
  49847. };
  49848. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49849. /**
  49850. * Return the array of runtime animations currently using this animation
  49851. */
  49852. get: function () {
  49853. return this._runtimeAnimations;
  49854. },
  49855. enumerable: true,
  49856. configurable: true
  49857. });
  49858. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49859. /**
  49860. * Specifies if any of the runtime animations are currently running
  49861. */
  49862. get: function () {
  49863. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49864. var runtimeAnimation = _a[_i];
  49865. if (!runtimeAnimation.isStopped) {
  49866. return true;
  49867. }
  49868. }
  49869. return false;
  49870. },
  49871. enumerable: true,
  49872. configurable: true
  49873. });
  49874. // Methods
  49875. /**
  49876. * Converts the animation to a string
  49877. * @param fullDetails support for multiple levels of logging within scene loading
  49878. * @returns String form of the animation
  49879. */
  49880. Animation.prototype.toString = function (fullDetails) {
  49881. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49882. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49883. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49884. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49885. if (fullDetails) {
  49886. ret += ", Ranges: {";
  49887. var first = true;
  49888. for (var name in this._ranges) {
  49889. if (first) {
  49890. ret += ", ";
  49891. first = false;
  49892. }
  49893. ret += name;
  49894. }
  49895. ret += "}";
  49896. }
  49897. return ret;
  49898. };
  49899. /**
  49900. * Add an event to this animation
  49901. * @param event Event to add
  49902. */
  49903. Animation.prototype.addEvent = function (event) {
  49904. this._events.push(event);
  49905. };
  49906. /**
  49907. * Remove all events found at the given frame
  49908. * @param frame The frame to remove events from
  49909. */
  49910. Animation.prototype.removeEvents = function (frame) {
  49911. for (var index = 0; index < this._events.length; index++) {
  49912. if (this._events[index].frame === frame) {
  49913. this._events.splice(index, 1);
  49914. index--;
  49915. }
  49916. }
  49917. };
  49918. /**
  49919. * Retrieves all the events from the animation
  49920. * @returns Events from the animation
  49921. */
  49922. Animation.prototype.getEvents = function () {
  49923. return this._events;
  49924. };
  49925. /**
  49926. * Creates an animation range
  49927. * @param name Name of the animation range
  49928. * @param from Starting frame of the animation range
  49929. * @param to Ending frame of the animation
  49930. */
  49931. Animation.prototype.createRange = function (name, from, to) {
  49932. // check name not already in use; could happen for bones after serialized
  49933. if (!this._ranges[name]) {
  49934. this._ranges[name] = new AnimationRange(name, from, to);
  49935. }
  49936. };
  49937. /**
  49938. * Deletes an animation range by name
  49939. * @param name Name of the animation range to delete
  49940. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49941. */
  49942. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49943. if (deleteFrames === void 0) { deleteFrames = true; }
  49944. var range = this._ranges[name];
  49945. if (!range) {
  49946. return;
  49947. }
  49948. if (deleteFrames) {
  49949. var from = range.from;
  49950. var to = range.to;
  49951. // this loop MUST go high to low for multiple splices to work
  49952. for (var key = this._keys.length - 1; key >= 0; key--) {
  49953. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49954. this._keys.splice(key, 1);
  49955. }
  49956. }
  49957. }
  49958. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49959. };
  49960. /**
  49961. * Gets the animation range by name, or null if not defined
  49962. * @param name Name of the animation range
  49963. * @returns Nullable animation range
  49964. */
  49965. Animation.prototype.getRange = function (name) {
  49966. return this._ranges[name];
  49967. };
  49968. /**
  49969. * Gets the key frames from the animation
  49970. * @returns The key frames of the animation
  49971. */
  49972. Animation.prototype.getKeys = function () {
  49973. return this._keys;
  49974. };
  49975. /**
  49976. * Gets the highest frame rate of the animation
  49977. * @returns Highest frame rate of the animation
  49978. */
  49979. Animation.prototype.getHighestFrame = function () {
  49980. var ret = 0;
  49981. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49982. if (ret < this._keys[key].frame) {
  49983. ret = this._keys[key].frame;
  49984. }
  49985. }
  49986. return ret;
  49987. };
  49988. /**
  49989. * Gets the easing function of the animation
  49990. * @returns Easing function of the animation
  49991. */
  49992. Animation.prototype.getEasingFunction = function () {
  49993. return this._easingFunction;
  49994. };
  49995. /**
  49996. * Sets the easing function of the animation
  49997. * @param easingFunction A custom mathematical formula for animation
  49998. */
  49999. Animation.prototype.setEasingFunction = function (easingFunction) {
  50000. this._easingFunction = easingFunction;
  50001. };
  50002. /**
  50003. * Interpolates a scalar linearly
  50004. * @param startValue Start value of the animation curve
  50005. * @param endValue End value of the animation curve
  50006. * @param gradient Scalar amount to interpolate
  50007. * @returns Interpolated scalar value
  50008. */
  50009. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50010. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50011. };
  50012. /**
  50013. * Interpolates a scalar cubically
  50014. * @param startValue Start value of the animation curve
  50015. * @param outTangent End tangent of the animation
  50016. * @param endValue End value of the animation curve
  50017. * @param inTangent Start tangent of the animation curve
  50018. * @param gradient Scalar amount to interpolate
  50019. * @returns Interpolated scalar value
  50020. */
  50021. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50022. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50023. };
  50024. /**
  50025. * Interpolates a quaternion using a spherical linear interpolation
  50026. * @param startValue Start value of the animation curve
  50027. * @param endValue End value of the animation curve
  50028. * @param gradient Scalar amount to interpolate
  50029. * @returns Interpolated quaternion value
  50030. */
  50031. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50032. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50033. };
  50034. /**
  50035. * Interpolates a quaternion cubically
  50036. * @param startValue Start value of the animation curve
  50037. * @param outTangent End tangent of the animation curve
  50038. * @param endValue End value of the animation curve
  50039. * @param inTangent Start tangent of the animation curve
  50040. * @param gradient Scalar amount to interpolate
  50041. * @returns Interpolated quaternion value
  50042. */
  50043. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50044. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50045. };
  50046. /**
  50047. * Interpolates a Vector3 linearl
  50048. * @param startValue Start value of the animation curve
  50049. * @param endValue End value of the animation curve
  50050. * @param gradient Scalar amount to interpolate
  50051. * @returns Interpolated scalar value
  50052. */
  50053. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50054. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50055. };
  50056. /**
  50057. * Interpolates a Vector3 cubically
  50058. * @param startValue Start value of the animation curve
  50059. * @param outTangent End tangent of the animation
  50060. * @param endValue End value of the animation curve
  50061. * @param inTangent Start tangent of the animation curve
  50062. * @param gradient Scalar amount to interpolate
  50063. * @returns InterpolatedVector3 value
  50064. */
  50065. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50066. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50067. };
  50068. /**
  50069. * Interpolates a Vector2 linearly
  50070. * @param startValue Start value of the animation curve
  50071. * @param endValue End value of the animation curve
  50072. * @param gradient Scalar amount to interpolate
  50073. * @returns Interpolated Vector2 value
  50074. */
  50075. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50076. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50077. };
  50078. /**
  50079. * Interpolates a Vector2 cubically
  50080. * @param startValue Start value of the animation curve
  50081. * @param outTangent End tangent of the animation
  50082. * @param endValue End value of the animation curve
  50083. * @param inTangent Start tangent of the animation curve
  50084. * @param gradient Scalar amount to interpolate
  50085. * @returns Interpolated Vector2 value
  50086. */
  50087. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50088. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50089. };
  50090. /**
  50091. * Interpolates a size linearly
  50092. * @param startValue Start value of the animation curve
  50093. * @param endValue End value of the animation curve
  50094. * @param gradient Scalar amount to interpolate
  50095. * @returns Interpolated Size value
  50096. */
  50097. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50098. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50099. };
  50100. /**
  50101. * Interpolates a Color3 linearly
  50102. * @param startValue Start value of the animation curve
  50103. * @param endValue End value of the animation curve
  50104. * @param gradient Scalar amount to interpolate
  50105. * @returns Interpolated Color3 value
  50106. */
  50107. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50108. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50109. };
  50110. /**
  50111. * @hidden Internal use only
  50112. */
  50113. Animation.prototype._getKeyValue = function (value) {
  50114. if (typeof value === "function") {
  50115. return value();
  50116. }
  50117. return value;
  50118. };
  50119. /**
  50120. * @hidden Internal use only
  50121. */
  50122. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50123. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50124. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50125. }
  50126. var keys = this.getKeys();
  50127. // Try to get a hash to find the right key
  50128. 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));
  50129. if (keys[startKeyIndex].frame >= currentFrame) {
  50130. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50131. startKeyIndex--;
  50132. }
  50133. }
  50134. for (var key = startKeyIndex; key < keys.length; key++) {
  50135. var endKey = keys[key + 1];
  50136. if (endKey.frame >= currentFrame) {
  50137. var startKey = keys[key];
  50138. var startValue = this._getKeyValue(startKey.value);
  50139. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50140. return startValue;
  50141. }
  50142. var endValue = this._getKeyValue(endKey.value);
  50143. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50144. var frameDelta = endKey.frame - startKey.frame;
  50145. // gradient : percent of currentFrame between the frame inf and the frame sup
  50146. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50147. // check for easingFunction and correction of gradient
  50148. var easingFunction = this.getEasingFunction();
  50149. if (easingFunction != null) {
  50150. gradient = easingFunction.ease(gradient);
  50151. }
  50152. switch (this.dataType) {
  50153. // Float
  50154. case Animation.ANIMATIONTYPE_FLOAT:
  50155. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50156. switch (loopMode) {
  50157. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50158. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50159. return floatValue;
  50160. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50161. return offsetValue * repeatCount + floatValue;
  50162. }
  50163. break;
  50164. // Quaternion
  50165. case Animation.ANIMATIONTYPE_QUATERNION:
  50166. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50167. switch (loopMode) {
  50168. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50169. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50170. return quatValue;
  50171. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50172. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50173. }
  50174. return quatValue;
  50175. // Vector3
  50176. case Animation.ANIMATIONTYPE_VECTOR3:
  50177. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50178. switch (loopMode) {
  50179. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50180. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50181. return vec3Value;
  50182. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50183. return vec3Value.add(offsetValue.scale(repeatCount));
  50184. }
  50185. // Vector2
  50186. case Animation.ANIMATIONTYPE_VECTOR2:
  50187. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50188. switch (loopMode) {
  50189. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50190. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50191. return vec2Value;
  50192. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50193. return vec2Value.add(offsetValue.scale(repeatCount));
  50194. }
  50195. // Size
  50196. case Animation.ANIMATIONTYPE_SIZE:
  50197. switch (loopMode) {
  50198. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50199. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50200. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50201. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50202. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50203. }
  50204. // Color3
  50205. case Animation.ANIMATIONTYPE_COLOR3:
  50206. switch (loopMode) {
  50207. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50208. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50209. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50210. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50211. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50212. }
  50213. // Matrix
  50214. case Animation.ANIMATIONTYPE_MATRIX:
  50215. switch (loopMode) {
  50216. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50217. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50218. if (Animation.AllowMatricesInterpolation) {
  50219. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50220. }
  50221. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50222. return startValue;
  50223. }
  50224. default:
  50225. break;
  50226. }
  50227. break;
  50228. }
  50229. }
  50230. return this._getKeyValue(keys[keys.length - 1].value);
  50231. };
  50232. /**
  50233. * Defines the function to use to interpolate matrices
  50234. * @param startValue defines the start matrix
  50235. * @param endValue defines the end matrix
  50236. * @param gradient defines the gradient between both matrices
  50237. * @param result defines an optional target matrix where to store the interpolation
  50238. * @returns the interpolated matrix
  50239. */
  50240. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50241. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50242. if (result) {
  50243. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50244. return result;
  50245. }
  50246. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50247. }
  50248. if (result) {
  50249. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50250. return result;
  50251. }
  50252. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50253. };
  50254. /**
  50255. * Makes a copy of the animation
  50256. * @returns Cloned animation
  50257. */
  50258. Animation.prototype.clone = function () {
  50259. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50260. clone.enableBlending = this.enableBlending;
  50261. clone.blendingSpeed = this.blendingSpeed;
  50262. if (this._keys) {
  50263. clone.setKeys(this._keys);
  50264. }
  50265. if (this._ranges) {
  50266. clone._ranges = {};
  50267. for (var name in this._ranges) {
  50268. var range = this._ranges[name];
  50269. if (!range) {
  50270. continue;
  50271. }
  50272. clone._ranges[name] = range.clone();
  50273. }
  50274. }
  50275. return clone;
  50276. };
  50277. /**
  50278. * Sets the key frames of the animation
  50279. * @param values The animation key frames to set
  50280. */
  50281. Animation.prototype.setKeys = function (values) {
  50282. this._keys = values.slice(0);
  50283. };
  50284. /**
  50285. * Serializes the animation to an object
  50286. * @returns Serialized object
  50287. */
  50288. Animation.prototype.serialize = function () {
  50289. var serializationObject = {};
  50290. serializationObject.name = this.name;
  50291. serializationObject.property = this.targetProperty;
  50292. serializationObject.framePerSecond = this.framePerSecond;
  50293. serializationObject.dataType = this.dataType;
  50294. serializationObject.loopBehavior = this.loopMode;
  50295. serializationObject.enableBlending = this.enableBlending;
  50296. serializationObject.blendingSpeed = this.blendingSpeed;
  50297. var dataType = this.dataType;
  50298. serializationObject.keys = [];
  50299. var keys = this.getKeys();
  50300. for (var index = 0; index < keys.length; index++) {
  50301. var animationKey = keys[index];
  50302. var key = {};
  50303. key.frame = animationKey.frame;
  50304. switch (dataType) {
  50305. case Animation.ANIMATIONTYPE_FLOAT:
  50306. key.values = [animationKey.value];
  50307. break;
  50308. case Animation.ANIMATIONTYPE_QUATERNION:
  50309. case Animation.ANIMATIONTYPE_MATRIX:
  50310. case Animation.ANIMATIONTYPE_VECTOR3:
  50311. case Animation.ANIMATIONTYPE_COLOR3:
  50312. key.values = animationKey.value.asArray();
  50313. break;
  50314. }
  50315. serializationObject.keys.push(key);
  50316. }
  50317. serializationObject.ranges = [];
  50318. for (var name in this._ranges) {
  50319. var source = this._ranges[name];
  50320. if (!source) {
  50321. continue;
  50322. }
  50323. var range = {};
  50324. range.name = name;
  50325. range.from = source.from;
  50326. range.to = source.to;
  50327. serializationObject.ranges.push(range);
  50328. }
  50329. return serializationObject;
  50330. };
  50331. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50332. /**
  50333. * Get the float animation type
  50334. */
  50335. get: function () {
  50336. return Animation._ANIMATIONTYPE_FLOAT;
  50337. },
  50338. enumerable: true,
  50339. configurable: true
  50340. });
  50341. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50342. /**
  50343. * Get the Vector3 animation type
  50344. */
  50345. get: function () {
  50346. return Animation._ANIMATIONTYPE_VECTOR3;
  50347. },
  50348. enumerable: true,
  50349. configurable: true
  50350. });
  50351. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50352. /**
  50353. * Get the Vector2 animation type
  50354. */
  50355. get: function () {
  50356. return Animation._ANIMATIONTYPE_VECTOR2;
  50357. },
  50358. enumerable: true,
  50359. configurable: true
  50360. });
  50361. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50362. /**
  50363. * Get the Size animation type
  50364. */
  50365. get: function () {
  50366. return Animation._ANIMATIONTYPE_SIZE;
  50367. },
  50368. enumerable: true,
  50369. configurable: true
  50370. });
  50371. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50372. /**
  50373. * Get the Quaternion animation type
  50374. */
  50375. get: function () {
  50376. return Animation._ANIMATIONTYPE_QUATERNION;
  50377. },
  50378. enumerable: true,
  50379. configurable: true
  50380. });
  50381. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50382. /**
  50383. * Get the Matrix animation type
  50384. */
  50385. get: function () {
  50386. return Animation._ANIMATIONTYPE_MATRIX;
  50387. },
  50388. enumerable: true,
  50389. configurable: true
  50390. });
  50391. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50392. /**
  50393. * Get the Color3 animation type
  50394. */
  50395. get: function () {
  50396. return Animation._ANIMATIONTYPE_COLOR3;
  50397. },
  50398. enumerable: true,
  50399. configurable: true
  50400. });
  50401. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50402. /**
  50403. * Get the Relative Loop Mode
  50404. */
  50405. get: function () {
  50406. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50407. },
  50408. enumerable: true,
  50409. configurable: true
  50410. });
  50411. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50412. /**
  50413. * Get the Cycle Loop Mode
  50414. */
  50415. get: function () {
  50416. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50417. },
  50418. enumerable: true,
  50419. configurable: true
  50420. });
  50421. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50422. /**
  50423. * Get the Constant Loop Mode
  50424. */
  50425. get: function () {
  50426. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50427. },
  50428. enumerable: true,
  50429. configurable: true
  50430. });
  50431. /** @hidden */
  50432. Animation._UniversalLerp = function (left, right, amount) {
  50433. var constructor = left.constructor;
  50434. if (constructor.Lerp) { // Lerp supported
  50435. return constructor.Lerp(left, right, amount);
  50436. }
  50437. else if (constructor.Slerp) { // Slerp supported
  50438. return constructor.Slerp(left, right, amount);
  50439. }
  50440. else if (left.toFixed) { // Number
  50441. return left * (1.0 - amount) + amount * right;
  50442. }
  50443. else { // Blending not supported
  50444. return right;
  50445. }
  50446. };
  50447. /**
  50448. * Parses an animation object and creates an animation
  50449. * @param parsedAnimation Parsed animation object
  50450. * @returns Animation object
  50451. */
  50452. Animation.Parse = function (parsedAnimation) {
  50453. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50454. var dataType = parsedAnimation.dataType;
  50455. var keys = [];
  50456. var data;
  50457. var index;
  50458. if (parsedAnimation.enableBlending) {
  50459. animation.enableBlending = parsedAnimation.enableBlending;
  50460. }
  50461. if (parsedAnimation.blendingSpeed) {
  50462. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50463. }
  50464. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50465. var key = parsedAnimation.keys[index];
  50466. var inTangent;
  50467. var outTangent;
  50468. switch (dataType) {
  50469. case Animation.ANIMATIONTYPE_FLOAT:
  50470. data = key.values[0];
  50471. if (key.values.length >= 1) {
  50472. inTangent = key.values[1];
  50473. }
  50474. if (key.values.length >= 2) {
  50475. outTangent = key.values[2];
  50476. }
  50477. break;
  50478. case Animation.ANIMATIONTYPE_QUATERNION:
  50479. data = BABYLON.Quaternion.FromArray(key.values);
  50480. if (key.values.length >= 8) {
  50481. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50482. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50483. inTangent = _inTangent;
  50484. }
  50485. }
  50486. if (key.values.length >= 12) {
  50487. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50488. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50489. outTangent = _outTangent;
  50490. }
  50491. }
  50492. break;
  50493. case Animation.ANIMATIONTYPE_MATRIX:
  50494. data = BABYLON.Matrix.FromArray(key.values);
  50495. break;
  50496. case Animation.ANIMATIONTYPE_COLOR3:
  50497. data = BABYLON.Color3.FromArray(key.values);
  50498. break;
  50499. case Animation.ANIMATIONTYPE_VECTOR3:
  50500. default:
  50501. data = BABYLON.Vector3.FromArray(key.values);
  50502. break;
  50503. }
  50504. var keyData = {};
  50505. keyData.frame = key.frame;
  50506. keyData.value = data;
  50507. if (inTangent != undefined) {
  50508. keyData.inTangent = inTangent;
  50509. }
  50510. if (outTangent != undefined) {
  50511. keyData.outTangent = outTangent;
  50512. }
  50513. keys.push(keyData);
  50514. }
  50515. animation.setKeys(keys);
  50516. if (parsedAnimation.ranges) {
  50517. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50518. data = parsedAnimation.ranges[index];
  50519. animation.createRange(data.name, data.from, data.to);
  50520. }
  50521. }
  50522. return animation;
  50523. };
  50524. /**
  50525. * Appends the serialized animations from the source animations
  50526. * @param source Source containing the animations
  50527. * @param destination Target to store the animations
  50528. */
  50529. Animation.AppendSerializedAnimations = function (source, destination) {
  50530. if (source.animations) {
  50531. destination.animations = [];
  50532. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50533. var animation = source.animations[animationIndex];
  50534. destination.animations.push(animation.serialize());
  50535. }
  50536. }
  50537. };
  50538. /**
  50539. * Use matrix interpolation instead of using direct key value when animating matrices
  50540. */
  50541. Animation.AllowMatricesInterpolation = false;
  50542. /**
  50543. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50544. */
  50545. Animation.AllowMatrixDecomposeForInterpolation = true;
  50546. // Statics
  50547. /**
  50548. * Float animation type
  50549. */
  50550. Animation._ANIMATIONTYPE_FLOAT = 0;
  50551. /**
  50552. * Vector3 animation type
  50553. */
  50554. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50555. /**
  50556. * Quaternion animation type
  50557. */
  50558. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50559. /**
  50560. * Matrix animation type
  50561. */
  50562. Animation._ANIMATIONTYPE_MATRIX = 3;
  50563. /**
  50564. * Color3 animation type
  50565. */
  50566. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50567. /**
  50568. * Vector2 animation type
  50569. */
  50570. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50571. /**
  50572. * Size animation type
  50573. */
  50574. Animation._ANIMATIONTYPE_SIZE = 6;
  50575. /**
  50576. * Relative Loop Mode
  50577. */
  50578. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50579. /**
  50580. * Cycle Loop Mode
  50581. */
  50582. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50583. /**
  50584. * Constant Loop Mode
  50585. */
  50586. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50587. return Animation;
  50588. }());
  50589. BABYLON.Animation = Animation;
  50590. })(BABYLON || (BABYLON = {}));
  50591. //# sourceMappingURL=babylon.animation.js.map
  50592. var BABYLON;
  50593. (function (BABYLON) {
  50594. /**
  50595. * This class defines the direct association between an animation and a target
  50596. */
  50597. var TargetedAnimation = /** @class */ (function () {
  50598. function TargetedAnimation() {
  50599. }
  50600. return TargetedAnimation;
  50601. }());
  50602. BABYLON.TargetedAnimation = TargetedAnimation;
  50603. /**
  50604. * Use this class to create coordinated animations on multiple targets
  50605. */
  50606. var AnimationGroup = /** @class */ (function () {
  50607. function AnimationGroup(name, scene) {
  50608. if (scene === void 0) { scene = null; }
  50609. this.name = name;
  50610. this._targetedAnimations = new Array();
  50611. this._animatables = new Array();
  50612. this._from = Number.MAX_VALUE;
  50613. this._to = -Number.MAX_VALUE;
  50614. this._speedRatio = 1;
  50615. this.onAnimationEndObservable = new BABYLON.Observable();
  50616. /**
  50617. * This observable will notify when all animations have ended.
  50618. */
  50619. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50620. /**
  50621. * This observable will notify when all animations have paused.
  50622. */
  50623. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50624. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50625. this._scene.animationGroups.push(this);
  50626. }
  50627. Object.defineProperty(AnimationGroup.prototype, "from", {
  50628. /**
  50629. * Gets the first frame
  50630. */
  50631. get: function () {
  50632. return this._from;
  50633. },
  50634. enumerable: true,
  50635. configurable: true
  50636. });
  50637. Object.defineProperty(AnimationGroup.prototype, "to", {
  50638. /**
  50639. * Gets the last frame
  50640. */
  50641. get: function () {
  50642. return this._to;
  50643. },
  50644. enumerable: true,
  50645. configurable: true
  50646. });
  50647. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50648. /**
  50649. * Define if the animations are started
  50650. */
  50651. get: function () {
  50652. return this._isStarted;
  50653. },
  50654. enumerable: true,
  50655. configurable: true
  50656. });
  50657. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50658. /**
  50659. * Gets or sets the speed ratio to use for all animations
  50660. */
  50661. get: function () {
  50662. return this._speedRatio;
  50663. },
  50664. /**
  50665. * Gets or sets the speed ratio to use for all animations
  50666. */
  50667. set: function (value) {
  50668. if (this._speedRatio === value) {
  50669. return;
  50670. }
  50671. this._speedRatio = value;
  50672. for (var index = 0; index < this._animatables.length; index++) {
  50673. var animatable = this._animatables[index];
  50674. animatable.speedRatio = this._speedRatio;
  50675. }
  50676. },
  50677. enumerable: true,
  50678. configurable: true
  50679. });
  50680. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50681. /**
  50682. * Gets the targeted animations for this animation group
  50683. */
  50684. get: function () {
  50685. return this._targetedAnimations;
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50691. /**
  50692. * returning the list of animatables controlled by this animation group.
  50693. */
  50694. get: function () {
  50695. return this._animatables;
  50696. },
  50697. enumerable: true,
  50698. configurable: true
  50699. });
  50700. /**
  50701. * Add an animation (with its target) in the group
  50702. * @param animation defines the animation we want to add
  50703. * @param target defines the target of the animation
  50704. * @returns the {BABYLON.TargetedAnimation} object
  50705. */
  50706. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50707. var targetedAnimation = {
  50708. animation: animation,
  50709. target: target
  50710. };
  50711. var keys = animation.getKeys();
  50712. if (this._from > keys[0].frame) {
  50713. this._from = keys[0].frame;
  50714. }
  50715. if (this._to < keys[keys.length - 1].frame) {
  50716. this._to = keys[keys.length - 1].frame;
  50717. }
  50718. this._targetedAnimations.push(targetedAnimation);
  50719. return targetedAnimation;
  50720. };
  50721. /**
  50722. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50723. * It can add constant keys at begin or end
  50724. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50725. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50726. */
  50727. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50728. if (beginFrame === void 0) { beginFrame = null; }
  50729. if (endFrame === void 0) { endFrame = null; }
  50730. if (beginFrame == null)
  50731. beginFrame = this._from;
  50732. if (endFrame == null)
  50733. endFrame = this._to;
  50734. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50735. var targetedAnimation = this._targetedAnimations[index];
  50736. var keys = targetedAnimation.animation.getKeys();
  50737. var startKey = keys[0];
  50738. var endKey = keys[keys.length - 1];
  50739. if (startKey.frame > beginFrame) {
  50740. var newKey = {
  50741. frame: beginFrame,
  50742. value: startKey.value,
  50743. inTangent: startKey.inTangent,
  50744. outTangent: startKey.outTangent,
  50745. interpolation: startKey.interpolation
  50746. };
  50747. keys.splice(0, 0, newKey);
  50748. }
  50749. if (endKey.frame < endFrame) {
  50750. var newKey = {
  50751. frame: endFrame,
  50752. value: endKey.value,
  50753. inTangent: endKey.outTangent,
  50754. outTangent: endKey.outTangent,
  50755. interpolation: endKey.interpolation
  50756. };
  50757. keys.push(newKey);
  50758. }
  50759. }
  50760. this._from = beginFrame;
  50761. this._to = endFrame;
  50762. return this;
  50763. };
  50764. /**
  50765. * Start all animations on given targets
  50766. * @param loop defines if animations must loop
  50767. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50768. * @param from defines the from key (optional)
  50769. * @param to defines the to key (optional)
  50770. * @returns the current animation group
  50771. */
  50772. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50773. var _this = this;
  50774. if (loop === void 0) { loop = false; }
  50775. if (speedRatio === void 0) { speedRatio = 1; }
  50776. if (this._isStarted || this._targetedAnimations.length === 0) {
  50777. return this;
  50778. }
  50779. var _loop_1 = function (targetedAnimation) {
  50780. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50781. animatable.onAnimationEnd = function () {
  50782. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50783. _this._checkAnimationGroupEnded(animatable);
  50784. };
  50785. this_1._animatables.push(animatable);
  50786. };
  50787. var this_1 = this;
  50788. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50789. var targetedAnimation = _a[_i];
  50790. _loop_1(targetedAnimation);
  50791. }
  50792. this._speedRatio = speedRatio;
  50793. this._isStarted = true;
  50794. return this;
  50795. };
  50796. /**
  50797. * Pause all animations
  50798. */
  50799. AnimationGroup.prototype.pause = function () {
  50800. if (!this._isStarted) {
  50801. return this;
  50802. }
  50803. for (var index = 0; index < this._animatables.length; index++) {
  50804. var animatable = this._animatables[index];
  50805. animatable.pause();
  50806. }
  50807. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50808. return this;
  50809. };
  50810. /**
  50811. * Play all animations to initial state
  50812. * This function will start() the animations if they were not started or will restart() them if they were paused
  50813. * @param loop defines if animations must loop
  50814. */
  50815. AnimationGroup.prototype.play = function (loop) {
  50816. // only if all animatables are ready and exist
  50817. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50818. if (loop !== undefined) {
  50819. for (var index = 0; index < this._animatables.length; index++) {
  50820. var animatable = this._animatables[index];
  50821. animatable.loopAnimation = loop;
  50822. }
  50823. }
  50824. this.restart();
  50825. }
  50826. else {
  50827. this.stop();
  50828. this.start(loop, this._speedRatio);
  50829. }
  50830. return this;
  50831. };
  50832. /**
  50833. * Reset all animations to initial state
  50834. */
  50835. AnimationGroup.prototype.reset = function () {
  50836. if (!this._isStarted) {
  50837. return this;
  50838. }
  50839. for (var index = 0; index < this._animatables.length; index++) {
  50840. var animatable = this._animatables[index];
  50841. animatable.reset();
  50842. }
  50843. return this;
  50844. };
  50845. /**
  50846. * Restart animations from key 0
  50847. */
  50848. AnimationGroup.prototype.restart = function () {
  50849. if (!this._isStarted) {
  50850. return this;
  50851. }
  50852. for (var index = 0; index < this._animatables.length; index++) {
  50853. var animatable = this._animatables[index];
  50854. animatable.restart();
  50855. }
  50856. return this;
  50857. };
  50858. /**
  50859. * Stop all animations
  50860. */
  50861. AnimationGroup.prototype.stop = function () {
  50862. if (!this._isStarted) {
  50863. return this;
  50864. }
  50865. var list = this._animatables.slice();
  50866. for (var index = 0; index < list.length; index++) {
  50867. list[index].stop();
  50868. }
  50869. this._isStarted = false;
  50870. return this;
  50871. };
  50872. /**
  50873. * Set animation weight for all animatables
  50874. * @param weight defines the weight to use
  50875. * @return the animationGroup
  50876. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50877. */
  50878. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50879. for (var index = 0; index < this._animatables.length; index++) {
  50880. var animatable = this._animatables[index];
  50881. animatable.weight = weight;
  50882. }
  50883. return this;
  50884. };
  50885. /**
  50886. * Synchronize and normalize all animatables with a source animatable
  50887. * @param root defines the root animatable to synchronize with
  50888. * @return the animationGroup
  50889. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50890. */
  50891. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50892. for (var index = 0; index < this._animatables.length; index++) {
  50893. var animatable = this._animatables[index];
  50894. animatable.syncWith(root);
  50895. }
  50896. return this;
  50897. };
  50898. /**
  50899. * Goes to a specific frame in this animation group
  50900. * @param frame the frame number to go to
  50901. * @return the animationGroup
  50902. */
  50903. AnimationGroup.prototype.goToFrame = function (frame) {
  50904. if (!this._isStarted) {
  50905. return this;
  50906. }
  50907. for (var index = 0; index < this._animatables.length; index++) {
  50908. var animatable = this._animatables[index];
  50909. animatable.goToFrame(frame);
  50910. }
  50911. return this;
  50912. };
  50913. /**
  50914. * Dispose all associated resources
  50915. */
  50916. AnimationGroup.prototype.dispose = function () {
  50917. this._targetedAnimations = [];
  50918. this._animatables = [];
  50919. var index = this._scene.animationGroups.indexOf(this);
  50920. if (index > -1) {
  50921. this._scene.animationGroups.splice(index, 1);
  50922. }
  50923. };
  50924. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50925. // animatable should be taken out of the array
  50926. var idx = this._animatables.indexOf(animatable);
  50927. if (idx > -1) {
  50928. this._animatables.splice(idx, 1);
  50929. }
  50930. // all animatables were removed? animation group ended!
  50931. if (this._animatables.length === 0) {
  50932. this._isStarted = false;
  50933. this.onAnimationGroupEndObservable.notifyObservers(this);
  50934. }
  50935. };
  50936. return AnimationGroup;
  50937. }());
  50938. BABYLON.AnimationGroup = AnimationGroup;
  50939. })(BABYLON || (BABYLON = {}));
  50940. //# sourceMappingURL=babylon.animationGroup.js.map
  50941. var BABYLON;
  50942. (function (BABYLON) {
  50943. // Static values to help the garbage collector
  50944. // Quaternion
  50945. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  50946. // Vector3
  50947. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  50948. // Vector2
  50949. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  50950. // Size
  50951. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  50952. // Color3
  50953. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  50954. /**
  50955. * Defines a runtime animation
  50956. */
  50957. var RuntimeAnimation = /** @class */ (function () {
  50958. /**
  50959. * Create a new RuntimeAnimation object
  50960. * @param target defines the target of the animation
  50961. * @param animation defines the source animation object
  50962. * @param scene defines the hosting scene
  50963. * @param host defines the initiating Animatable
  50964. */
  50965. function RuntimeAnimation(target, animation, scene, host) {
  50966. var _this = this;
  50967. this._events = new Array();
  50968. /**
  50969. * The current frame of the runtime animation
  50970. */
  50971. this._currentFrame = 0;
  50972. /**
  50973. * The original value of the runtime animation
  50974. */
  50975. this._originalValue = new Array();
  50976. /**
  50977. * The offsets cache of the runtime animation
  50978. */
  50979. this._offsetsCache = {};
  50980. /**
  50981. * The high limits cache of the runtime animation
  50982. */
  50983. this._highLimitsCache = {};
  50984. /**
  50985. * Specifies if the runtime animation has been stopped
  50986. */
  50987. this._stopped = false;
  50988. /**
  50989. * The blending factor of the runtime animation
  50990. */
  50991. this._blendingFactor = 0;
  50992. /**
  50993. * The target path of the runtime animation
  50994. */
  50995. this._targetPath = "";
  50996. /**
  50997. * The weight of the runtime animation
  50998. */
  50999. this._weight = 1.0;
  51000. /**
  51001. * The ratio offset of the runtime animation
  51002. */
  51003. this._ratioOffset = 0;
  51004. /**
  51005. * The previous delay of the runtime animation
  51006. */
  51007. this._previousDelay = 0;
  51008. /**
  51009. * The previous ratio of the runtime animation
  51010. */
  51011. this._previousRatio = 0;
  51012. this._animation = animation;
  51013. this._target = target;
  51014. this._scene = scene;
  51015. this._host = host;
  51016. animation._runtimeAnimations.push(this);
  51017. // Cloning events locally
  51018. var events = animation.getEvents();
  51019. if (events && events.length > 0) {
  51020. events.forEach(function (e) {
  51021. _this._events.push(e._clone());
  51022. });
  51023. }
  51024. }
  51025. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51026. /**
  51027. * Gets the current frame of the runtime animation
  51028. */
  51029. get: function () {
  51030. return this._currentFrame;
  51031. },
  51032. enumerable: true,
  51033. configurable: true
  51034. });
  51035. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51036. /**
  51037. * Gets the weight of the runtime animation
  51038. */
  51039. get: function () {
  51040. return this._weight;
  51041. },
  51042. enumerable: true,
  51043. configurable: true
  51044. });
  51045. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51046. /**
  51047. * Gets the current value of the runtime animation
  51048. */
  51049. get: function () {
  51050. return this._currentValue;
  51051. },
  51052. enumerable: true,
  51053. configurable: true
  51054. });
  51055. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51056. /**
  51057. * Gets the target path of the runtime animation
  51058. */
  51059. get: function () {
  51060. return this._targetPath;
  51061. },
  51062. enumerable: true,
  51063. configurable: true
  51064. });
  51065. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51066. /**
  51067. * Gets the actual target of the runtime animation
  51068. */
  51069. get: function () {
  51070. return this._activeTarget;
  51071. },
  51072. enumerable: true,
  51073. configurable: true
  51074. });
  51075. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51076. /**
  51077. * Gets the animation from the runtime animation
  51078. */
  51079. get: function () {
  51080. return this._animation;
  51081. },
  51082. enumerable: true,
  51083. configurable: true
  51084. });
  51085. /**
  51086. * Resets the runtime animation to the beginning
  51087. * @param restoreOriginal defines whether to restore the target property to the original value
  51088. */
  51089. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51090. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51091. if (restoreOriginal) {
  51092. if (this._target instanceof Array) {
  51093. var index = 0;
  51094. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51095. var target = _a[_i];
  51096. if (this._originalValue[index] !== undefined) {
  51097. this._setValue(target, this._originalValue[index], -1);
  51098. }
  51099. index++;
  51100. }
  51101. }
  51102. else {
  51103. if (this._originalValue[0] !== undefined) {
  51104. this._setValue(this._target, this._originalValue[0], -1);
  51105. }
  51106. }
  51107. }
  51108. this._offsetsCache = {};
  51109. this._highLimitsCache = {};
  51110. this._currentFrame = 0;
  51111. this._blendingFactor = 0;
  51112. this._originalValue = new Array();
  51113. // Events
  51114. for (var index = 0; index < this._events.length; index++) {
  51115. this._events[index].isDone = false;
  51116. }
  51117. };
  51118. /**
  51119. * Specifies if the runtime animation is stopped
  51120. * @returns Boolean specifying if the runtime animation is stopped
  51121. */
  51122. RuntimeAnimation.prototype.isStopped = function () {
  51123. return this._stopped;
  51124. };
  51125. /**
  51126. * Disposes of the runtime animation
  51127. */
  51128. RuntimeAnimation.prototype.dispose = function () {
  51129. var index = this._animation.runtimeAnimations.indexOf(this);
  51130. if (index > -1) {
  51131. this._animation.runtimeAnimations.splice(index, 1);
  51132. }
  51133. };
  51134. /**
  51135. * Interpolates the animation from the current frame
  51136. * @param currentFrame The frame to interpolate the animation to
  51137. * @param repeatCount The number of times that the animation should loop
  51138. * @param loopMode The type of looping mode to use
  51139. * @param offsetValue Animation offset value
  51140. * @param highLimitValue The high limit value
  51141. * @returns The interpolated value
  51142. */
  51143. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51144. this._currentFrame = currentFrame;
  51145. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51146. this._workValue = BABYLON.Matrix.Zero();
  51147. }
  51148. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51149. };
  51150. /**
  51151. * Apply the interpolated value to the target
  51152. * @param currentValue defines the value computed by the animation
  51153. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51154. */
  51155. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51156. if (weight === void 0) { weight = 1.0; }
  51157. if (this._target instanceof Array) {
  51158. var index = 0;
  51159. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51160. var target = _a[_i];
  51161. this._setValue(target, currentValue, weight, index);
  51162. index++;
  51163. }
  51164. }
  51165. else {
  51166. this._setValue(this._target, currentValue, weight);
  51167. }
  51168. };
  51169. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51170. if (targetIndex === void 0) { targetIndex = 0; }
  51171. // Set value
  51172. var path;
  51173. var destination;
  51174. var targetPropertyPath = this._animation.targetPropertyPath;
  51175. if (targetPropertyPath.length > 1) {
  51176. var property = target[targetPropertyPath[0]];
  51177. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51178. property = property[targetPropertyPath[index]];
  51179. }
  51180. path = targetPropertyPath[targetPropertyPath.length - 1];
  51181. destination = property;
  51182. }
  51183. else {
  51184. path = targetPropertyPath[0];
  51185. destination = target;
  51186. }
  51187. this._targetPath = path;
  51188. this._activeTarget = destination;
  51189. this._weight = weight;
  51190. if (this._originalValue[targetIndex] === undefined) {
  51191. var originalValue = void 0;
  51192. if (destination.getRestPose && path === "_matrix") { // For bones
  51193. originalValue = destination.getRestPose();
  51194. }
  51195. else {
  51196. originalValue = destination[path];
  51197. }
  51198. if (originalValue && originalValue.clone) {
  51199. this._originalValue[targetIndex] = originalValue.clone();
  51200. }
  51201. else {
  51202. this._originalValue[targetIndex] = originalValue;
  51203. }
  51204. }
  51205. // Blending
  51206. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51207. if (enableBlending && this._blendingFactor <= 1.0) {
  51208. if (!this._originalBlendValue) {
  51209. var originalValue = destination[path];
  51210. if (originalValue.clone) {
  51211. this._originalBlendValue = originalValue.clone();
  51212. }
  51213. else {
  51214. this._originalBlendValue = originalValue;
  51215. }
  51216. }
  51217. if (this._originalBlendValue.m) { // Matrix
  51218. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51219. if (this._currentValue) {
  51220. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51221. }
  51222. else {
  51223. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51224. }
  51225. }
  51226. else {
  51227. if (this._currentValue) {
  51228. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51229. }
  51230. else {
  51231. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51232. }
  51233. }
  51234. }
  51235. else {
  51236. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51237. }
  51238. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51239. this._blendingFactor += blendingSpeed;
  51240. }
  51241. else {
  51242. this._currentValue = currentValue;
  51243. }
  51244. if (weight !== -1.0) {
  51245. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51246. }
  51247. else {
  51248. destination[path] = this._currentValue;
  51249. }
  51250. if (target.markAsDirty) {
  51251. target.markAsDirty(this._animation.targetProperty);
  51252. }
  51253. };
  51254. /**
  51255. * Gets the loop pmode of the runtime animation
  51256. * @returns Loop Mode
  51257. */
  51258. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51259. if (this._target && this._target.animationPropertiesOverride) {
  51260. return this._target.animationPropertiesOverride.loopMode;
  51261. }
  51262. return this._animation.loopMode;
  51263. };
  51264. /**
  51265. * Move the current animation to a given frame
  51266. * @param frame defines the frame to move to
  51267. */
  51268. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51269. var keys = this._animation.getKeys();
  51270. if (frame < keys[0].frame) {
  51271. frame = keys[0].frame;
  51272. }
  51273. else if (frame > keys[keys.length - 1].frame) {
  51274. frame = keys[keys.length - 1].frame;
  51275. }
  51276. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51277. this.setValue(currentValue, -1);
  51278. };
  51279. /**
  51280. * @hidden Internal use only
  51281. */
  51282. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51283. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51284. this._ratioOffset = this._previousRatio - newRatio;
  51285. };
  51286. /**
  51287. * Execute the current animation
  51288. * @param delay defines the delay to add to the current frame
  51289. * @param from defines the lower bound of the animation range
  51290. * @param to defines the upper bound of the animation range
  51291. * @param loop defines if the current animation must loop
  51292. * @param speedRatio defines the current speed ratio
  51293. * @param weight defines the weight of the animation (default is -1 so no weight)
  51294. * @returns a boolean indicating if the animation is running
  51295. */
  51296. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51297. if (weight === void 0) { weight = -1.0; }
  51298. var targetPropertyPath = this._animation.targetPropertyPath;
  51299. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51300. this._stopped = true;
  51301. return false;
  51302. }
  51303. var returnValue = true;
  51304. var keys = this._animation.getKeys();
  51305. // Adding a start key at frame 0 if missing
  51306. if (keys[0].frame !== 0) {
  51307. var newKey = { frame: 0, value: keys[0].value };
  51308. keys.splice(0, 0, newKey);
  51309. }
  51310. // Adding a duplicate key when there is only one key at frame zero
  51311. else if (keys.length === 1) {
  51312. var newKey = { frame: 0.001, value: keys[0].value };
  51313. keys.push(newKey);
  51314. }
  51315. // Check limits
  51316. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51317. from = keys[0].frame;
  51318. }
  51319. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51320. to = keys[keys.length - 1].frame;
  51321. }
  51322. //to and from cannot be the same key
  51323. if (from === to) {
  51324. if (from > keys[0].frame) {
  51325. from--;
  51326. }
  51327. else if (to < keys[keys.length - 1].frame) {
  51328. to++;
  51329. }
  51330. }
  51331. // Compute ratio
  51332. var range = to - from;
  51333. var offsetValue;
  51334. // ratio represents the frame delta between from and to
  51335. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51336. var highLimitValue = 0;
  51337. this._previousDelay = delay;
  51338. this._previousRatio = ratio;
  51339. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51340. returnValue = false;
  51341. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51342. }
  51343. else {
  51344. // Get max value if required
  51345. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51346. var keyOffset = to.toString() + from.toString();
  51347. if (!this._offsetsCache[keyOffset]) {
  51348. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51349. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51350. switch (this._animation.dataType) {
  51351. // Float
  51352. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51353. this._offsetsCache[keyOffset] = toValue - fromValue;
  51354. break;
  51355. // Quaternion
  51356. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51357. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51358. break;
  51359. // Vector3
  51360. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51361. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51362. // Vector2
  51363. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51364. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51365. // Size
  51366. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51367. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51368. // Color3
  51369. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51370. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51371. default:
  51372. break;
  51373. }
  51374. this._highLimitsCache[keyOffset] = toValue;
  51375. }
  51376. highLimitValue = this._highLimitsCache[keyOffset];
  51377. offsetValue = this._offsetsCache[keyOffset];
  51378. }
  51379. }
  51380. if (offsetValue === undefined) {
  51381. switch (this._animation.dataType) {
  51382. // Float
  51383. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51384. offsetValue = 0;
  51385. break;
  51386. // Quaternion
  51387. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51388. offsetValue = _staticOffsetValueQuaternion;
  51389. break;
  51390. // Vector3
  51391. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51392. offsetValue = _staticOffsetValueVector3;
  51393. break;
  51394. // Vector2
  51395. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51396. offsetValue = _staticOffsetValueVector2;
  51397. break;
  51398. // Size
  51399. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51400. offsetValue = _staticOffsetValueSize;
  51401. break;
  51402. // Color3
  51403. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51404. offsetValue = _staticOffsetValueColor3;
  51405. }
  51406. }
  51407. // Compute value
  51408. var repeatCount = (ratio / range) >> 0;
  51409. var currentFrame = returnValue ? from + ratio % range : to;
  51410. // Need to normalize?
  51411. if (this._host && this._host.syncRoot) {
  51412. var syncRoot = this._host.syncRoot;
  51413. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51414. currentFrame = from + (to - from) * hostNormalizedFrame;
  51415. }
  51416. // Reset events if looping
  51417. var events = this._events;
  51418. if (range > 0 && this.currentFrame > currentFrame ||
  51419. range < 0 && this.currentFrame < currentFrame) {
  51420. // Need to reset animation events
  51421. for (var index = 0; index < events.length; index++) {
  51422. if (!events[index].onlyOnce) {
  51423. // reset event, the animation is looping
  51424. events[index].isDone = false;
  51425. }
  51426. }
  51427. }
  51428. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51429. // Set value
  51430. this.setValue(currentValue, weight);
  51431. // Check events
  51432. for (var index = 0; index < events.length; index++) {
  51433. // Make sure current frame has passed event frame and that event frame is within the current range
  51434. // Also, handle both forward and reverse animations
  51435. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51436. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51437. var event = events[index];
  51438. if (!event.isDone) {
  51439. // If event should be done only once, remove it.
  51440. if (event.onlyOnce) {
  51441. events.splice(index, 1);
  51442. index--;
  51443. }
  51444. event.isDone = true;
  51445. event.action(currentFrame);
  51446. } // Don't do anything if the event has already be done.
  51447. }
  51448. }
  51449. if (!returnValue) {
  51450. this._stopped = true;
  51451. }
  51452. return returnValue;
  51453. };
  51454. return RuntimeAnimation;
  51455. }());
  51456. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51457. })(BABYLON || (BABYLON = {}));
  51458. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51459. var BABYLON;
  51460. (function (BABYLON) {
  51461. /**
  51462. * Class used to store an actual running animation
  51463. */
  51464. var Animatable = /** @class */ (function () {
  51465. /**
  51466. * Creates a new Animatable
  51467. * @param scene defines the hosting scene
  51468. * @param target defines the target object
  51469. * @param fromFrame defines the starting frame number (default is 0)
  51470. * @param toFrame defines the ending frame number (default is 100)
  51471. * @param loopAnimation defines if the animation must loop (default is false)
  51472. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51473. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51474. * @param animations defines a group of animation to add to the new Animatable
  51475. */
  51476. function Animatable(scene,
  51477. /** defines the target object */
  51478. target,
  51479. /** defines the starting frame number (default is 0) */
  51480. fromFrame,
  51481. /** defines the ending frame number (default is 100) */
  51482. toFrame,
  51483. /** defines if the animation must loop (default is false) */
  51484. loopAnimation, speedRatio,
  51485. /** defines a callback to call when animation ends if it is not looping */
  51486. onAnimationEnd, animations) {
  51487. if (fromFrame === void 0) { fromFrame = 0; }
  51488. if (toFrame === void 0) { toFrame = 100; }
  51489. if (loopAnimation === void 0) { loopAnimation = false; }
  51490. if (speedRatio === void 0) { speedRatio = 1.0; }
  51491. this.target = target;
  51492. this.fromFrame = fromFrame;
  51493. this.toFrame = toFrame;
  51494. this.loopAnimation = loopAnimation;
  51495. this.onAnimationEnd = onAnimationEnd;
  51496. this._localDelayOffset = null;
  51497. this._pausedDelay = null;
  51498. this._runtimeAnimations = new Array();
  51499. this._paused = false;
  51500. this._speedRatio = 1;
  51501. this._weight = -1.0;
  51502. /**
  51503. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51504. * This will only apply for non looping animation (default is true)
  51505. */
  51506. this.disposeOnEnd = true;
  51507. /**
  51508. * Gets a boolean indicating if the animation has started
  51509. */
  51510. this.animationStarted = false;
  51511. /**
  51512. * Observer raised when the animation ends
  51513. */
  51514. this.onAnimationEndObservable = new BABYLON.Observable();
  51515. this._scene = scene;
  51516. if (animations) {
  51517. this.appendAnimations(target, animations);
  51518. }
  51519. this._speedRatio = speedRatio;
  51520. scene._activeAnimatables.push(this);
  51521. }
  51522. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51523. /**
  51524. * Gets the root Animatable used to synchronize and normalize animations
  51525. */
  51526. get: function () {
  51527. return this._syncRoot;
  51528. },
  51529. enumerable: true,
  51530. configurable: true
  51531. });
  51532. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51533. /**
  51534. * Gets the current frame of the first RuntimeAnimation
  51535. * Used to synchronize Animatables
  51536. */
  51537. get: function () {
  51538. if (this._runtimeAnimations.length === 0) {
  51539. return 0;
  51540. }
  51541. return this._runtimeAnimations[0].currentFrame;
  51542. },
  51543. enumerable: true,
  51544. configurable: true
  51545. });
  51546. Object.defineProperty(Animatable.prototype, "weight", {
  51547. /**
  51548. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51549. */
  51550. get: function () {
  51551. return this._weight;
  51552. },
  51553. set: function (value) {
  51554. if (value === -1) { // -1 is ok and means no weight
  51555. this._weight = -1;
  51556. return;
  51557. }
  51558. // Else weight must be in [0, 1] range
  51559. this._weight = Math.min(Math.max(value, 0), 1.0);
  51560. },
  51561. enumerable: true,
  51562. configurable: true
  51563. });
  51564. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51565. /**
  51566. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51567. */
  51568. get: function () {
  51569. return this._speedRatio;
  51570. },
  51571. set: function (value) {
  51572. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51573. var animation = this._runtimeAnimations[index];
  51574. animation._prepareForSpeedRatioChange(value);
  51575. }
  51576. this._speedRatio = value;
  51577. },
  51578. enumerable: true,
  51579. configurable: true
  51580. });
  51581. // Methods
  51582. /**
  51583. * Synchronize and normalize current Animatable with a source Animatable
  51584. * This is useful when using animation weights and when animations are not of the same length
  51585. * @param root defines the root Animatable to synchronize with
  51586. * @returns the current Animatable
  51587. */
  51588. Animatable.prototype.syncWith = function (root) {
  51589. this._syncRoot = root;
  51590. if (root) {
  51591. // Make sure this animatable will animate after the root
  51592. var index = this._scene._activeAnimatables.indexOf(this);
  51593. if (index > -1) {
  51594. this._scene._activeAnimatables.splice(index, 1);
  51595. this._scene._activeAnimatables.push(this);
  51596. }
  51597. }
  51598. return this;
  51599. };
  51600. /**
  51601. * Gets the list of runtime animations
  51602. * @returns an array of RuntimeAnimation
  51603. */
  51604. Animatable.prototype.getAnimations = function () {
  51605. return this._runtimeAnimations;
  51606. };
  51607. /**
  51608. * Adds more animations to the current animatable
  51609. * @param target defines the target of the animations
  51610. * @param animations defines the new animations to add
  51611. */
  51612. Animatable.prototype.appendAnimations = function (target, animations) {
  51613. for (var index = 0; index < animations.length; index++) {
  51614. var animation = animations[index];
  51615. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51616. }
  51617. };
  51618. /**
  51619. * Gets the source animation for a specific property
  51620. * @param property defines the propertyu to look for
  51621. * @returns null or the source animation for the given property
  51622. */
  51623. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51624. var runtimeAnimations = this._runtimeAnimations;
  51625. for (var index = 0; index < runtimeAnimations.length; index++) {
  51626. if (runtimeAnimations[index].animation.targetProperty === property) {
  51627. return runtimeAnimations[index].animation;
  51628. }
  51629. }
  51630. return null;
  51631. };
  51632. /**
  51633. * Gets the runtime animation for a specific property
  51634. * @param property defines the propertyu to look for
  51635. * @returns null or the runtime animation for the given property
  51636. */
  51637. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51638. var runtimeAnimations = this._runtimeAnimations;
  51639. for (var index = 0; index < runtimeAnimations.length; index++) {
  51640. if (runtimeAnimations[index].animation.targetProperty === property) {
  51641. return runtimeAnimations[index];
  51642. }
  51643. }
  51644. return null;
  51645. };
  51646. /**
  51647. * Resets the animatable to its original state
  51648. */
  51649. Animatable.prototype.reset = function () {
  51650. var runtimeAnimations = this._runtimeAnimations;
  51651. for (var index = 0; index < runtimeAnimations.length; index++) {
  51652. runtimeAnimations[index].reset(true);
  51653. }
  51654. this._localDelayOffset = null;
  51655. this._pausedDelay = null;
  51656. };
  51657. /**
  51658. * Allows the animatable to blend with current running animations
  51659. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51660. * @param blendingSpeed defines the blending speed to use
  51661. */
  51662. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51663. var runtimeAnimations = this._runtimeAnimations;
  51664. for (var index = 0; index < runtimeAnimations.length; index++) {
  51665. runtimeAnimations[index].animation.enableBlending = true;
  51666. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51667. }
  51668. };
  51669. /**
  51670. * Disable animation blending
  51671. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51672. */
  51673. Animatable.prototype.disableBlending = function () {
  51674. var runtimeAnimations = this._runtimeAnimations;
  51675. for (var index = 0; index < runtimeAnimations.length; index++) {
  51676. runtimeAnimations[index].animation.enableBlending = false;
  51677. }
  51678. };
  51679. /**
  51680. * Jump directly to a given frame
  51681. * @param frame defines the frame to jump to
  51682. */
  51683. Animatable.prototype.goToFrame = function (frame) {
  51684. var runtimeAnimations = this._runtimeAnimations;
  51685. if (runtimeAnimations[0]) {
  51686. var fps = runtimeAnimations[0].animation.framePerSecond;
  51687. var currentFrame = runtimeAnimations[0].currentFrame;
  51688. var adjustTime = frame - currentFrame;
  51689. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51690. if (this._localDelayOffset === null) {
  51691. this._localDelayOffset = 0;
  51692. }
  51693. this._localDelayOffset -= delay;
  51694. }
  51695. for (var index = 0; index < runtimeAnimations.length; index++) {
  51696. runtimeAnimations[index].goToFrame(frame);
  51697. }
  51698. };
  51699. /**
  51700. * Pause the animation
  51701. */
  51702. Animatable.prototype.pause = function () {
  51703. if (this._paused) {
  51704. return;
  51705. }
  51706. this._paused = true;
  51707. };
  51708. /**
  51709. * Restart the animation
  51710. */
  51711. Animatable.prototype.restart = function () {
  51712. this._paused = false;
  51713. };
  51714. Animatable.prototype._raiseOnAnimationEnd = function () {
  51715. if (this.onAnimationEnd) {
  51716. this.onAnimationEnd();
  51717. }
  51718. this.onAnimationEndObservable.notifyObservers(this);
  51719. };
  51720. /**
  51721. * Stop and delete the current animation
  51722. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51723. * @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)
  51724. */
  51725. Animatable.prototype.stop = function (animationName, targetMask) {
  51726. if (animationName || targetMask) {
  51727. var idx = this._scene._activeAnimatables.indexOf(this);
  51728. if (idx > -1) {
  51729. var runtimeAnimations = this._runtimeAnimations;
  51730. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51731. var runtimeAnimation = runtimeAnimations[index];
  51732. if (animationName && runtimeAnimation.animation.name != animationName) {
  51733. continue;
  51734. }
  51735. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51736. continue;
  51737. }
  51738. runtimeAnimation.dispose();
  51739. runtimeAnimations.splice(index, 1);
  51740. }
  51741. if (runtimeAnimations.length == 0) {
  51742. this._scene._activeAnimatables.splice(idx, 1);
  51743. this._raiseOnAnimationEnd();
  51744. }
  51745. }
  51746. }
  51747. else {
  51748. var index = this._scene._activeAnimatables.indexOf(this);
  51749. if (index > -1) {
  51750. this._scene._activeAnimatables.splice(index, 1);
  51751. var runtimeAnimations = this._runtimeAnimations;
  51752. for (var index = 0; index < runtimeAnimations.length; index++) {
  51753. runtimeAnimations[index].dispose();
  51754. }
  51755. this._raiseOnAnimationEnd();
  51756. }
  51757. }
  51758. };
  51759. /**
  51760. * Wait asynchronously for the animation to end
  51761. * @returns a promise which will be fullfilled when the animation ends
  51762. */
  51763. Animatable.prototype.waitAsync = function () {
  51764. var _this = this;
  51765. return new Promise(function (resolve, reject) {
  51766. _this.onAnimationEndObservable.add(function () {
  51767. resolve(_this);
  51768. }, undefined, undefined, _this, true);
  51769. });
  51770. };
  51771. /** @hidden */
  51772. Animatable.prototype._animate = function (delay) {
  51773. if (this._paused) {
  51774. this.animationStarted = false;
  51775. if (this._pausedDelay === null) {
  51776. this._pausedDelay = delay;
  51777. }
  51778. return true;
  51779. }
  51780. if (this._localDelayOffset === null) {
  51781. this._localDelayOffset = delay;
  51782. this._pausedDelay = null;
  51783. }
  51784. else if (this._pausedDelay !== null) {
  51785. this._localDelayOffset += delay - this._pausedDelay;
  51786. this._pausedDelay = null;
  51787. }
  51788. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51789. return true;
  51790. }
  51791. // Animating
  51792. var running = false;
  51793. var runtimeAnimations = this._runtimeAnimations;
  51794. var index;
  51795. for (index = 0; index < runtimeAnimations.length; index++) {
  51796. var animation = runtimeAnimations[index];
  51797. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51798. running = running || isRunning;
  51799. }
  51800. this.animationStarted = running;
  51801. if (!running) {
  51802. if (this.disposeOnEnd) {
  51803. // Remove from active animatables
  51804. index = this._scene._activeAnimatables.indexOf(this);
  51805. this._scene._activeAnimatables.splice(index, 1);
  51806. // Dispose all runtime animations
  51807. for (index = 0; index < runtimeAnimations.length; index++) {
  51808. runtimeAnimations[index].dispose();
  51809. }
  51810. }
  51811. this._raiseOnAnimationEnd();
  51812. if (this.disposeOnEnd) {
  51813. this.onAnimationEnd = null;
  51814. this.onAnimationEndObservable.clear();
  51815. }
  51816. }
  51817. return running;
  51818. };
  51819. return Animatable;
  51820. }());
  51821. BABYLON.Animatable = Animatable;
  51822. })(BABYLON || (BABYLON = {}));
  51823. //# sourceMappingURL=babylon.animatable.js.map
  51824. var BABYLON;
  51825. (function (BABYLON) {
  51826. var EasingFunction = /** @class */ (function () {
  51827. function EasingFunction() {
  51828. // Properties
  51829. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51830. }
  51831. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51832. get: function () {
  51833. return EasingFunction._EASINGMODE_EASEIN;
  51834. },
  51835. enumerable: true,
  51836. configurable: true
  51837. });
  51838. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51839. get: function () {
  51840. return EasingFunction._EASINGMODE_EASEOUT;
  51841. },
  51842. enumerable: true,
  51843. configurable: true
  51844. });
  51845. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51846. get: function () {
  51847. return EasingFunction._EASINGMODE_EASEINOUT;
  51848. },
  51849. enumerable: true,
  51850. configurable: true
  51851. });
  51852. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51853. var n = Math.min(Math.max(easingMode, 0), 2);
  51854. this._easingMode = n;
  51855. };
  51856. EasingFunction.prototype.getEasingMode = function () {
  51857. return this._easingMode;
  51858. };
  51859. EasingFunction.prototype.easeInCore = function (gradient) {
  51860. throw new Error('You must implement this method');
  51861. };
  51862. EasingFunction.prototype.ease = function (gradient) {
  51863. switch (this._easingMode) {
  51864. case EasingFunction.EASINGMODE_EASEIN:
  51865. return this.easeInCore(gradient);
  51866. case EasingFunction.EASINGMODE_EASEOUT:
  51867. return (1 - this.easeInCore(1 - gradient));
  51868. }
  51869. if (gradient >= 0.5) {
  51870. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51871. }
  51872. return (this.easeInCore(gradient * 2) * 0.5);
  51873. };
  51874. //Statics
  51875. EasingFunction._EASINGMODE_EASEIN = 0;
  51876. EasingFunction._EASINGMODE_EASEOUT = 1;
  51877. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51878. return EasingFunction;
  51879. }());
  51880. BABYLON.EasingFunction = EasingFunction;
  51881. var CircleEase = /** @class */ (function (_super) {
  51882. __extends(CircleEase, _super);
  51883. function CircleEase() {
  51884. return _super !== null && _super.apply(this, arguments) || this;
  51885. }
  51886. CircleEase.prototype.easeInCore = function (gradient) {
  51887. gradient = Math.max(0, Math.min(1, gradient));
  51888. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51889. };
  51890. return CircleEase;
  51891. }(EasingFunction));
  51892. BABYLON.CircleEase = CircleEase;
  51893. var BackEase = /** @class */ (function (_super) {
  51894. __extends(BackEase, _super);
  51895. function BackEase(amplitude) {
  51896. if (amplitude === void 0) { amplitude = 1; }
  51897. var _this = _super.call(this) || this;
  51898. _this.amplitude = amplitude;
  51899. return _this;
  51900. }
  51901. BackEase.prototype.easeInCore = function (gradient) {
  51902. var num = Math.max(0, this.amplitude);
  51903. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51904. };
  51905. return BackEase;
  51906. }(EasingFunction));
  51907. BABYLON.BackEase = BackEase;
  51908. var BounceEase = /** @class */ (function (_super) {
  51909. __extends(BounceEase, _super);
  51910. function BounceEase(bounces, bounciness) {
  51911. if (bounces === void 0) { bounces = 3; }
  51912. if (bounciness === void 0) { bounciness = 2; }
  51913. var _this = _super.call(this) || this;
  51914. _this.bounces = bounces;
  51915. _this.bounciness = bounciness;
  51916. return _this;
  51917. }
  51918. BounceEase.prototype.easeInCore = function (gradient) {
  51919. var y = Math.max(0.0, this.bounces);
  51920. var bounciness = this.bounciness;
  51921. if (bounciness <= 1.0) {
  51922. bounciness = 1.001;
  51923. }
  51924. var num9 = Math.pow(bounciness, y);
  51925. var num5 = 1.0 - bounciness;
  51926. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51927. var num15 = gradient * num4;
  51928. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51929. var num3 = Math.floor(num65);
  51930. var num13 = num3 + 1.0;
  51931. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51932. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51933. var num7 = (num8 + num12) * 0.5;
  51934. var num6 = gradient - num7;
  51935. var num2 = num7 - num8;
  51936. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51937. };
  51938. return BounceEase;
  51939. }(EasingFunction));
  51940. BABYLON.BounceEase = BounceEase;
  51941. var CubicEase = /** @class */ (function (_super) {
  51942. __extends(CubicEase, _super);
  51943. function CubicEase() {
  51944. return _super !== null && _super.apply(this, arguments) || this;
  51945. }
  51946. CubicEase.prototype.easeInCore = function (gradient) {
  51947. return (gradient * gradient * gradient);
  51948. };
  51949. return CubicEase;
  51950. }(EasingFunction));
  51951. BABYLON.CubicEase = CubicEase;
  51952. var ElasticEase = /** @class */ (function (_super) {
  51953. __extends(ElasticEase, _super);
  51954. function ElasticEase(oscillations, springiness) {
  51955. if (oscillations === void 0) { oscillations = 3; }
  51956. if (springiness === void 0) { springiness = 3; }
  51957. var _this = _super.call(this) || this;
  51958. _this.oscillations = oscillations;
  51959. _this.springiness = springiness;
  51960. return _this;
  51961. }
  51962. ElasticEase.prototype.easeInCore = function (gradient) {
  51963. var num2;
  51964. var num3 = Math.max(0.0, this.oscillations);
  51965. var num = Math.max(0.0, this.springiness);
  51966. if (num == 0) {
  51967. num2 = gradient;
  51968. }
  51969. else {
  51970. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51971. }
  51972. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51973. };
  51974. return ElasticEase;
  51975. }(EasingFunction));
  51976. BABYLON.ElasticEase = ElasticEase;
  51977. var ExponentialEase = /** @class */ (function (_super) {
  51978. __extends(ExponentialEase, _super);
  51979. function ExponentialEase(exponent) {
  51980. if (exponent === void 0) { exponent = 2; }
  51981. var _this = _super.call(this) || this;
  51982. _this.exponent = exponent;
  51983. return _this;
  51984. }
  51985. ExponentialEase.prototype.easeInCore = function (gradient) {
  51986. if (this.exponent <= 0) {
  51987. return gradient;
  51988. }
  51989. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51990. };
  51991. return ExponentialEase;
  51992. }(EasingFunction));
  51993. BABYLON.ExponentialEase = ExponentialEase;
  51994. var PowerEase = /** @class */ (function (_super) {
  51995. __extends(PowerEase, _super);
  51996. function PowerEase(power) {
  51997. if (power === void 0) { power = 2; }
  51998. var _this = _super.call(this) || this;
  51999. _this.power = power;
  52000. return _this;
  52001. }
  52002. PowerEase.prototype.easeInCore = function (gradient) {
  52003. var y = Math.max(0.0, this.power);
  52004. return Math.pow(gradient, y);
  52005. };
  52006. return PowerEase;
  52007. }(EasingFunction));
  52008. BABYLON.PowerEase = PowerEase;
  52009. var QuadraticEase = /** @class */ (function (_super) {
  52010. __extends(QuadraticEase, _super);
  52011. function QuadraticEase() {
  52012. return _super !== null && _super.apply(this, arguments) || this;
  52013. }
  52014. QuadraticEase.prototype.easeInCore = function (gradient) {
  52015. return (gradient * gradient);
  52016. };
  52017. return QuadraticEase;
  52018. }(EasingFunction));
  52019. BABYLON.QuadraticEase = QuadraticEase;
  52020. var QuarticEase = /** @class */ (function (_super) {
  52021. __extends(QuarticEase, _super);
  52022. function QuarticEase() {
  52023. return _super !== null && _super.apply(this, arguments) || this;
  52024. }
  52025. QuarticEase.prototype.easeInCore = function (gradient) {
  52026. return (gradient * gradient * gradient * gradient);
  52027. };
  52028. return QuarticEase;
  52029. }(EasingFunction));
  52030. BABYLON.QuarticEase = QuarticEase;
  52031. var QuinticEase = /** @class */ (function (_super) {
  52032. __extends(QuinticEase, _super);
  52033. function QuinticEase() {
  52034. return _super !== null && _super.apply(this, arguments) || this;
  52035. }
  52036. QuinticEase.prototype.easeInCore = function (gradient) {
  52037. return (gradient * gradient * gradient * gradient * gradient);
  52038. };
  52039. return QuinticEase;
  52040. }(EasingFunction));
  52041. BABYLON.QuinticEase = QuinticEase;
  52042. var SineEase = /** @class */ (function (_super) {
  52043. __extends(SineEase, _super);
  52044. function SineEase() {
  52045. return _super !== null && _super.apply(this, arguments) || this;
  52046. }
  52047. SineEase.prototype.easeInCore = function (gradient) {
  52048. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52049. };
  52050. return SineEase;
  52051. }(EasingFunction));
  52052. BABYLON.SineEase = SineEase;
  52053. var BezierCurveEase = /** @class */ (function (_super) {
  52054. __extends(BezierCurveEase, _super);
  52055. function BezierCurveEase(x1, y1, x2, y2) {
  52056. if (x1 === void 0) { x1 = 0; }
  52057. if (y1 === void 0) { y1 = 0; }
  52058. if (x2 === void 0) { x2 = 1; }
  52059. if (y2 === void 0) { y2 = 1; }
  52060. var _this = _super.call(this) || this;
  52061. _this.x1 = x1;
  52062. _this.y1 = y1;
  52063. _this.x2 = x2;
  52064. _this.y2 = y2;
  52065. return _this;
  52066. }
  52067. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52068. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52069. };
  52070. return BezierCurveEase;
  52071. }(EasingFunction));
  52072. BABYLON.BezierCurveEase = BezierCurveEase;
  52073. })(BABYLON || (BABYLON = {}));
  52074. //# sourceMappingURL=babylon.easing.js.map
  52075. var BABYLON;
  52076. (function (BABYLON) {
  52077. /**
  52078. * A Condition applied to an Action
  52079. */
  52080. var Condition = /** @class */ (function () {
  52081. /**
  52082. * Creates a new Condition
  52083. * @param actionManager the manager of the action the condition is applied to
  52084. */
  52085. function Condition(actionManager) {
  52086. this._actionManager = actionManager;
  52087. }
  52088. /**
  52089. * Check if the current condition is valid
  52090. * @returns a boolean
  52091. */
  52092. Condition.prototype.isValid = function () {
  52093. return true;
  52094. };
  52095. /**
  52096. * Internal only
  52097. * @hidden
  52098. */
  52099. Condition.prototype._getProperty = function (propertyPath) {
  52100. return this._actionManager._getProperty(propertyPath);
  52101. };
  52102. /**
  52103. * Internal only
  52104. * @hidden
  52105. */
  52106. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52107. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52108. };
  52109. /**
  52110. * Serialize placeholder for child classes
  52111. * @returns the serialized object
  52112. */
  52113. Condition.prototype.serialize = function () {
  52114. };
  52115. /**
  52116. * Internal only
  52117. * @hidden
  52118. */
  52119. Condition.prototype._serialize = function (serializedCondition) {
  52120. return {
  52121. type: 2,
  52122. children: [],
  52123. name: serializedCondition.name,
  52124. properties: serializedCondition.properties
  52125. };
  52126. };
  52127. return Condition;
  52128. }());
  52129. BABYLON.Condition = Condition;
  52130. /**
  52131. * Defines specific conditional operators as extensions of Condition
  52132. */
  52133. var ValueCondition = /** @class */ (function (_super) {
  52134. __extends(ValueCondition, _super);
  52135. /**
  52136. * Creates a new ValueCondition
  52137. * @param actionManager manager for the action the condition applies to
  52138. * @param target for the action
  52139. * @param propertyPath path to specify the property of the target the conditional operator uses
  52140. * @param value the value compared by the conditional operator against the current value of the property
  52141. * @param operator the conditional operator, default ValueCondition.IsEqual
  52142. */
  52143. function ValueCondition(actionManager, target,
  52144. /** path to specify the property of the target the conditional operator uses */
  52145. propertyPath,
  52146. /** the value compared by the conditional operator against the current value of the property */
  52147. value,
  52148. /** the conditional operator, default ValueCondition.IsEqual */
  52149. operator) {
  52150. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52151. var _this = _super.call(this, actionManager) || this;
  52152. _this.propertyPath = propertyPath;
  52153. _this.value = value;
  52154. _this.operator = operator;
  52155. _this._target = target;
  52156. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52157. _this._property = _this._getProperty(_this.propertyPath);
  52158. return _this;
  52159. }
  52160. Object.defineProperty(ValueCondition, "IsEqual", {
  52161. /**
  52162. * returns the number for IsEqual
  52163. */
  52164. get: function () {
  52165. return ValueCondition._IsEqual;
  52166. },
  52167. enumerable: true,
  52168. configurable: true
  52169. });
  52170. Object.defineProperty(ValueCondition, "IsDifferent", {
  52171. /**
  52172. * Returns the number for IsDifferent
  52173. */
  52174. get: function () {
  52175. return ValueCondition._IsDifferent;
  52176. },
  52177. enumerable: true,
  52178. configurable: true
  52179. });
  52180. Object.defineProperty(ValueCondition, "IsGreater", {
  52181. /**
  52182. * Returns the number for IsGreater
  52183. */
  52184. get: function () {
  52185. return ValueCondition._IsGreater;
  52186. },
  52187. enumerable: true,
  52188. configurable: true
  52189. });
  52190. Object.defineProperty(ValueCondition, "IsLesser", {
  52191. /**
  52192. * Returns the number for IsLesser
  52193. */
  52194. get: function () {
  52195. return ValueCondition._IsLesser;
  52196. },
  52197. enumerable: true,
  52198. configurable: true
  52199. });
  52200. /**
  52201. * Compares the given value with the property value for the specified conditional operator
  52202. * @returns the result of the comparison
  52203. */
  52204. ValueCondition.prototype.isValid = function () {
  52205. switch (this.operator) {
  52206. case ValueCondition.IsGreater:
  52207. return this._effectiveTarget[this._property] > this.value;
  52208. case ValueCondition.IsLesser:
  52209. return this._effectiveTarget[this._property] < this.value;
  52210. case ValueCondition.IsEqual:
  52211. case ValueCondition.IsDifferent:
  52212. var check;
  52213. if (this.value.equals) {
  52214. check = this.value.equals(this._effectiveTarget[this._property]);
  52215. }
  52216. else {
  52217. check = this.value === this._effectiveTarget[this._property];
  52218. }
  52219. return this.operator === ValueCondition.IsEqual ? check : !check;
  52220. }
  52221. return false;
  52222. };
  52223. /**
  52224. * Serialize the ValueCondition into a JSON compatible object
  52225. * @returns serialization object
  52226. */
  52227. ValueCondition.prototype.serialize = function () {
  52228. return this._serialize({
  52229. name: "ValueCondition",
  52230. properties: [
  52231. BABYLON.Action._GetTargetProperty(this._target),
  52232. { name: "propertyPath", value: this.propertyPath },
  52233. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52234. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52235. ]
  52236. });
  52237. };
  52238. /**
  52239. * Gets the name of the conditional operator for the ValueCondition
  52240. * @param operator the conditional operator
  52241. * @returns the name
  52242. */
  52243. ValueCondition.GetOperatorName = function (operator) {
  52244. switch (operator) {
  52245. case ValueCondition._IsEqual: return "IsEqual";
  52246. case ValueCondition._IsDifferent: return "IsDifferent";
  52247. case ValueCondition._IsGreater: return "IsGreater";
  52248. case ValueCondition._IsLesser: return "IsLesser";
  52249. default: return "";
  52250. }
  52251. };
  52252. /**
  52253. * Internal only
  52254. * @hidden
  52255. */
  52256. ValueCondition._IsEqual = 0;
  52257. /**
  52258. * Internal only
  52259. * @hidden
  52260. */
  52261. ValueCondition._IsDifferent = 1;
  52262. /**
  52263. * Internal only
  52264. * @hidden
  52265. */
  52266. ValueCondition._IsGreater = 2;
  52267. /**
  52268. * Internal only
  52269. * @hidden
  52270. */
  52271. ValueCondition._IsLesser = 3;
  52272. return ValueCondition;
  52273. }(Condition));
  52274. BABYLON.ValueCondition = ValueCondition;
  52275. /**
  52276. * Defines a predicate condition as an extension of Condition
  52277. */
  52278. var PredicateCondition = /** @class */ (function (_super) {
  52279. __extends(PredicateCondition, _super);
  52280. /**
  52281. * Creates a new PredicateCondition
  52282. * @param actionManager manager for the action the condition applies to
  52283. * @param predicate defines the predicate function used to validate the condition
  52284. */
  52285. function PredicateCondition(actionManager,
  52286. /** defines the predicate function used to validate the condition */
  52287. predicate) {
  52288. var _this = _super.call(this, actionManager) || this;
  52289. _this.predicate = predicate;
  52290. return _this;
  52291. }
  52292. /**
  52293. * @returns the validity of the predicate condition
  52294. */
  52295. PredicateCondition.prototype.isValid = function () {
  52296. return this.predicate();
  52297. };
  52298. return PredicateCondition;
  52299. }(Condition));
  52300. BABYLON.PredicateCondition = PredicateCondition;
  52301. /**
  52302. * Defines a state condition as an extension of Condition
  52303. */
  52304. var StateCondition = /** @class */ (function (_super) {
  52305. __extends(StateCondition, _super);
  52306. /**
  52307. * Creates a new StateCondition
  52308. * @param actionManager manager for the action the condition applies to
  52309. * @param target of the condition
  52310. * @param value to compare with target state
  52311. */
  52312. function StateCondition(actionManager, target, value) {
  52313. var _this = _super.call(this, actionManager) || this;
  52314. _this.value = value;
  52315. _this._target = target;
  52316. return _this;
  52317. }
  52318. /**
  52319. * @returns the validity of the state
  52320. */
  52321. StateCondition.prototype.isValid = function () {
  52322. return this._target.state === this.value;
  52323. };
  52324. /**
  52325. * Serialize the StateCondition into a JSON compatible object
  52326. * @returns serialization object
  52327. */
  52328. StateCondition.prototype.serialize = function () {
  52329. return this._serialize({
  52330. name: "StateCondition",
  52331. properties: [
  52332. BABYLON.Action._GetTargetProperty(this._target),
  52333. { name: "value", value: this.value }
  52334. ]
  52335. });
  52336. };
  52337. return StateCondition;
  52338. }(Condition));
  52339. BABYLON.StateCondition = StateCondition;
  52340. })(BABYLON || (BABYLON = {}));
  52341. //# sourceMappingURL=babylon.condition.js.map
  52342. var BABYLON;
  52343. (function (BABYLON) {
  52344. /**
  52345. * The action to be carried out following a trigger
  52346. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52347. */
  52348. var Action = /** @class */ (function () {
  52349. /**
  52350. * Creates a new Action
  52351. * @param triggerOptions the trigger, with or without parameters, for the action
  52352. * @param condition an optional determinant of action
  52353. */
  52354. function Action(
  52355. /** the trigger, with or without parameters, for the action */
  52356. triggerOptions, condition) {
  52357. this.triggerOptions = triggerOptions;
  52358. /**
  52359. * An event triggered prior to action being executed.
  52360. */
  52361. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52362. if (triggerOptions.parameter) {
  52363. this.trigger = triggerOptions.trigger;
  52364. this._triggerParameter = triggerOptions.parameter;
  52365. }
  52366. else if (triggerOptions.trigger) {
  52367. this.trigger = triggerOptions.trigger;
  52368. }
  52369. else {
  52370. this.trigger = triggerOptions;
  52371. }
  52372. this._nextActiveAction = this;
  52373. this._condition = condition;
  52374. }
  52375. /**
  52376. * Internal only
  52377. * @hidden
  52378. */
  52379. Action.prototype._prepare = function () {
  52380. };
  52381. /**
  52382. * Gets the trigger parameters
  52383. * @returns the trigger parameters
  52384. */
  52385. Action.prototype.getTriggerParameter = function () {
  52386. return this._triggerParameter;
  52387. };
  52388. /**
  52389. * Internal only - executes current action event
  52390. * @hidden
  52391. */
  52392. Action.prototype._executeCurrent = function (evt) {
  52393. if (this._nextActiveAction._condition) {
  52394. var condition = this._nextActiveAction._condition;
  52395. var currentRenderId = this._actionManager.getScene().getRenderId();
  52396. // We cache the current evaluation for the current frame
  52397. if (condition._evaluationId === currentRenderId) {
  52398. if (!condition._currentResult) {
  52399. return;
  52400. }
  52401. }
  52402. else {
  52403. condition._evaluationId = currentRenderId;
  52404. if (!condition.isValid()) {
  52405. condition._currentResult = false;
  52406. return;
  52407. }
  52408. condition._currentResult = true;
  52409. }
  52410. }
  52411. this.onBeforeExecuteObservable.notifyObservers(this);
  52412. this._nextActiveAction.execute(evt);
  52413. this.skipToNextActiveAction();
  52414. };
  52415. /**
  52416. * Execute placeholder for child classes
  52417. * @param evt optional action event
  52418. */
  52419. Action.prototype.execute = function (evt) {
  52420. };
  52421. /**
  52422. * Skips to next active action
  52423. */
  52424. Action.prototype.skipToNextActiveAction = function () {
  52425. if (this._nextActiveAction._child) {
  52426. if (!this._nextActiveAction._child._actionManager) {
  52427. this._nextActiveAction._child._actionManager = this._actionManager;
  52428. }
  52429. this._nextActiveAction = this._nextActiveAction._child;
  52430. }
  52431. else {
  52432. this._nextActiveAction = this;
  52433. }
  52434. };
  52435. /**
  52436. * Adds action to chain of actions, may be a DoNothingAction
  52437. * @param action defines the next action to execute
  52438. * @returns The action passed in
  52439. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52440. */
  52441. Action.prototype.then = function (action) {
  52442. this._child = action;
  52443. action._actionManager = this._actionManager;
  52444. action._prepare();
  52445. return action;
  52446. };
  52447. /**
  52448. * Internal only
  52449. * @hidden
  52450. */
  52451. Action.prototype._getProperty = function (propertyPath) {
  52452. return this._actionManager._getProperty(propertyPath);
  52453. };
  52454. /**
  52455. * Internal only
  52456. * @hidden
  52457. */
  52458. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52459. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52460. };
  52461. /**
  52462. * Serialize placeholder for child classes
  52463. * @param parent of child
  52464. * @returns the serialized object
  52465. */
  52466. Action.prototype.serialize = function (parent) {
  52467. };
  52468. /**
  52469. * Internal only called by serialize
  52470. * @hidden
  52471. */
  52472. Action.prototype._serialize = function (serializedAction, parent) {
  52473. var serializationObject = {
  52474. type: 1,
  52475. children: [],
  52476. name: serializedAction.name,
  52477. properties: serializedAction.properties || []
  52478. };
  52479. // Serialize child
  52480. if (this._child) {
  52481. this._child.serialize(serializationObject);
  52482. }
  52483. // Check if "this" has a condition
  52484. if (this._condition) {
  52485. var serializedCondition = this._condition.serialize();
  52486. serializedCondition.children.push(serializationObject);
  52487. if (parent) {
  52488. parent.children.push(serializedCondition);
  52489. }
  52490. return serializedCondition;
  52491. }
  52492. if (parent) {
  52493. parent.children.push(serializationObject);
  52494. }
  52495. return serializationObject;
  52496. };
  52497. /**
  52498. * Internal only
  52499. * @hidden
  52500. */
  52501. Action._SerializeValueAsString = function (value) {
  52502. if (typeof value === "number") {
  52503. return value.toString();
  52504. }
  52505. if (typeof value === "boolean") {
  52506. return value ? "true" : "false";
  52507. }
  52508. if (value instanceof BABYLON.Vector2) {
  52509. return value.x + ", " + value.y;
  52510. }
  52511. if (value instanceof BABYLON.Vector3) {
  52512. return value.x + ", " + value.y + ", " + value.z;
  52513. }
  52514. if (value instanceof BABYLON.Color3) {
  52515. return value.r + ", " + value.g + ", " + value.b;
  52516. }
  52517. if (value instanceof BABYLON.Color4) {
  52518. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52519. }
  52520. return value; // string
  52521. };
  52522. /**
  52523. * Internal only
  52524. * @hidden
  52525. */
  52526. Action._GetTargetProperty = function (target) {
  52527. return {
  52528. name: "target",
  52529. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52530. : target instanceof BABYLON.Light ? "LightProperties"
  52531. : target instanceof BABYLON.Camera ? "CameraProperties"
  52532. : "SceneProperties",
  52533. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52534. };
  52535. };
  52536. return Action;
  52537. }());
  52538. BABYLON.Action = Action;
  52539. })(BABYLON || (BABYLON = {}));
  52540. //# sourceMappingURL=babylon.action.js.map
  52541. var BABYLON;
  52542. (function (BABYLON) {
  52543. /**
  52544. * ActionEvent is the event being sent when an action is triggered.
  52545. */
  52546. var ActionEvent = /** @class */ (function () {
  52547. /**
  52548. * Creates a new ActionEvent
  52549. * @param source The mesh or sprite that triggered the action
  52550. * @param pointerX The X mouse cursor position at the time of the event
  52551. * @param pointerY The Y mouse cursor position at the time of the event
  52552. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52553. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52554. * @param additionalData additional data for the event
  52555. */
  52556. function ActionEvent(
  52557. /** The mesh or sprite that triggered the action */
  52558. source,
  52559. /** The X mouse cursor position at the time of the event */
  52560. pointerX,
  52561. /** The Y mouse cursor position at the time of the event */
  52562. pointerY,
  52563. /** The mesh that is currently pointed at (can be null) */
  52564. meshUnderPointer,
  52565. /** the original (browser) event that triggered the ActionEvent */
  52566. sourceEvent,
  52567. /** additional data for the event */
  52568. additionalData) {
  52569. this.source = source;
  52570. this.pointerX = pointerX;
  52571. this.pointerY = pointerY;
  52572. this.meshUnderPointer = meshUnderPointer;
  52573. this.sourceEvent = sourceEvent;
  52574. this.additionalData = additionalData;
  52575. }
  52576. /**
  52577. * Helper function to auto-create an ActionEvent from a source mesh.
  52578. * @param source The source mesh that triggered the event
  52579. * @param evt The original (browser) event
  52580. * @param additionalData additional data for the event
  52581. * @returns the new ActionEvent
  52582. */
  52583. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52584. var scene = source.getScene();
  52585. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52586. };
  52587. /**
  52588. * Helper function to auto-create an ActionEvent from a source sprite
  52589. * @param source The source sprite that triggered the event
  52590. * @param scene Scene associated with the sprite
  52591. * @param evt The original (browser) event
  52592. * @param additionalData additional data for the event
  52593. * @returns the new ActionEvent
  52594. */
  52595. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52596. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52597. };
  52598. /**
  52599. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52600. * @param scene the scene where the event occurred
  52601. * @param evt The original (browser) event
  52602. * @returns the new ActionEvent
  52603. */
  52604. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52605. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52606. };
  52607. /**
  52608. * Helper function to auto-create an ActionEvent from a primitive
  52609. * @param prim defines the target primitive
  52610. * @param pointerPos defines the pointer position
  52611. * @param evt The original (browser) event
  52612. * @param additionalData additional data for the event
  52613. * @returns the new ActionEvent
  52614. */
  52615. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52616. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52617. };
  52618. return ActionEvent;
  52619. }());
  52620. BABYLON.ActionEvent = ActionEvent;
  52621. /**
  52622. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52623. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52624. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52625. */
  52626. var ActionManager = /** @class */ (function () {
  52627. /**
  52628. * Creates a new action manager
  52629. * @param scene defines the hosting scene
  52630. */
  52631. function ActionManager(scene) {
  52632. // Members
  52633. /** Gets the list of actions */
  52634. this.actions = new Array();
  52635. /** Gets the cursor to use when hovering items */
  52636. this.hoverCursor = '';
  52637. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52638. scene.actionManagers.push(this);
  52639. }
  52640. Object.defineProperty(ActionManager, "NothingTrigger", {
  52641. /**
  52642. * Nothing
  52643. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52644. */
  52645. get: function () {
  52646. return ActionManager._NothingTrigger;
  52647. },
  52648. enumerable: true,
  52649. configurable: true
  52650. });
  52651. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52652. /**
  52653. * On pick
  52654. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52655. */
  52656. get: function () {
  52657. return ActionManager._OnPickTrigger;
  52658. },
  52659. enumerable: true,
  52660. configurable: true
  52661. });
  52662. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52663. /**
  52664. * On left pick
  52665. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52666. */
  52667. get: function () {
  52668. return ActionManager._OnLeftPickTrigger;
  52669. },
  52670. enumerable: true,
  52671. configurable: true
  52672. });
  52673. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52674. /**
  52675. * On right pick
  52676. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52677. */
  52678. get: function () {
  52679. return ActionManager._OnRightPickTrigger;
  52680. },
  52681. enumerable: true,
  52682. configurable: true
  52683. });
  52684. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52685. /**
  52686. * On center pick
  52687. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52688. */
  52689. get: function () {
  52690. return ActionManager._OnCenterPickTrigger;
  52691. },
  52692. enumerable: true,
  52693. configurable: true
  52694. });
  52695. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52696. /**
  52697. * On pick down
  52698. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52699. */
  52700. get: function () {
  52701. return ActionManager._OnPickDownTrigger;
  52702. },
  52703. enumerable: true,
  52704. configurable: true
  52705. });
  52706. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52707. /**
  52708. * On double pick
  52709. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52710. */
  52711. get: function () {
  52712. return ActionManager._OnDoublePickTrigger;
  52713. },
  52714. enumerable: true,
  52715. configurable: true
  52716. });
  52717. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52718. /**
  52719. * On pick up
  52720. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52721. */
  52722. get: function () {
  52723. return ActionManager._OnPickUpTrigger;
  52724. },
  52725. enumerable: true,
  52726. configurable: true
  52727. });
  52728. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52729. /**
  52730. * On pick out.
  52731. * This trigger will only be raised if you also declared a OnPickDown
  52732. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52733. */
  52734. get: function () {
  52735. return ActionManager._OnPickOutTrigger;
  52736. },
  52737. enumerable: true,
  52738. configurable: true
  52739. });
  52740. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52741. /**
  52742. * On long press
  52743. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52744. */
  52745. get: function () {
  52746. return ActionManager._OnLongPressTrigger;
  52747. },
  52748. enumerable: true,
  52749. configurable: true
  52750. });
  52751. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52752. /**
  52753. * On pointer over
  52754. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52755. */
  52756. get: function () {
  52757. return ActionManager._OnPointerOverTrigger;
  52758. },
  52759. enumerable: true,
  52760. configurable: true
  52761. });
  52762. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52763. /**
  52764. * On pointer out
  52765. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52766. */
  52767. get: function () {
  52768. return ActionManager._OnPointerOutTrigger;
  52769. },
  52770. enumerable: true,
  52771. configurable: true
  52772. });
  52773. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52774. /**
  52775. * On every frame
  52776. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52777. */
  52778. get: function () {
  52779. return ActionManager._OnEveryFrameTrigger;
  52780. },
  52781. enumerable: true,
  52782. configurable: true
  52783. });
  52784. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52785. /**
  52786. * On intersection enter
  52787. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52788. */
  52789. get: function () {
  52790. return ActionManager._OnIntersectionEnterTrigger;
  52791. },
  52792. enumerable: true,
  52793. configurable: true
  52794. });
  52795. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52796. /**
  52797. * On intersection exit
  52798. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52799. */
  52800. get: function () {
  52801. return ActionManager._OnIntersectionExitTrigger;
  52802. },
  52803. enumerable: true,
  52804. configurable: true
  52805. });
  52806. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52807. /**
  52808. * On key down
  52809. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52810. */
  52811. get: function () {
  52812. return ActionManager._OnKeyDownTrigger;
  52813. },
  52814. enumerable: true,
  52815. configurable: true
  52816. });
  52817. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52818. /**
  52819. * On key up
  52820. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52821. */
  52822. get: function () {
  52823. return ActionManager._OnKeyUpTrigger;
  52824. },
  52825. enumerable: true,
  52826. configurable: true
  52827. });
  52828. // Methods
  52829. /**
  52830. * Releases all associated resources
  52831. */
  52832. ActionManager.prototype.dispose = function () {
  52833. var index = this._scene.actionManagers.indexOf(this);
  52834. for (var i = 0; i < this.actions.length; i++) {
  52835. var action = this.actions[i];
  52836. ActionManager.Triggers[action.trigger]--;
  52837. if (ActionManager.Triggers[action.trigger] === 0) {
  52838. delete ActionManager.Triggers[action.trigger];
  52839. }
  52840. }
  52841. if (index > -1) {
  52842. this._scene.actionManagers.splice(index, 1);
  52843. }
  52844. };
  52845. /**
  52846. * Gets hosting scene
  52847. * @returns the hosting scene
  52848. */
  52849. ActionManager.prototype.getScene = function () {
  52850. return this._scene;
  52851. };
  52852. /**
  52853. * Does this action manager handles actions of any of the given triggers
  52854. * @param triggers defines the triggers to be tested
  52855. * @return a boolean indicating whether one (or more) of the triggers is handled
  52856. */
  52857. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52858. for (var index = 0; index < this.actions.length; index++) {
  52859. var action = this.actions[index];
  52860. if (triggers.indexOf(action.trigger) > -1) {
  52861. return true;
  52862. }
  52863. }
  52864. return false;
  52865. };
  52866. /**
  52867. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52868. * speed.
  52869. * @param triggerA defines the trigger to be tested
  52870. * @param triggerB defines the trigger to be tested
  52871. * @return a boolean indicating whether one (or more) of the triggers is handled
  52872. */
  52873. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  52874. for (var index = 0; index < this.actions.length; index++) {
  52875. var action = this.actions[index];
  52876. if (triggerA == action.trigger || triggerB == action.trigger) {
  52877. return true;
  52878. }
  52879. }
  52880. return false;
  52881. };
  52882. /**
  52883. * Does this action manager handles actions of a given trigger
  52884. * @param trigger defines the trigger to be tested
  52885. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52886. * @return whether the trigger is handled
  52887. */
  52888. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52889. for (var index = 0; index < this.actions.length; index++) {
  52890. var action = this.actions[index];
  52891. if (action.trigger === trigger) {
  52892. if (parameterPredicate) {
  52893. if (parameterPredicate(action.getTriggerParameter())) {
  52894. return true;
  52895. }
  52896. }
  52897. else {
  52898. return true;
  52899. }
  52900. }
  52901. }
  52902. return false;
  52903. };
  52904. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52905. /**
  52906. * Does this action manager has pointer triggers
  52907. */
  52908. get: function () {
  52909. for (var index = 0; index < this.actions.length; index++) {
  52910. var action = this.actions[index];
  52911. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52912. return true;
  52913. }
  52914. }
  52915. return false;
  52916. },
  52917. enumerable: true,
  52918. configurable: true
  52919. });
  52920. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52921. /**
  52922. * Does this action manager has pick triggers
  52923. */
  52924. get: function () {
  52925. for (var index = 0; index < this.actions.length; index++) {
  52926. var action = this.actions[index];
  52927. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52928. return true;
  52929. }
  52930. }
  52931. return false;
  52932. },
  52933. enumerable: true,
  52934. configurable: true
  52935. });
  52936. Object.defineProperty(ActionManager, "HasTriggers", {
  52937. /**
  52938. * Does exist one action manager with at least one trigger
  52939. **/
  52940. get: function () {
  52941. for (var t in ActionManager.Triggers) {
  52942. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52943. return true;
  52944. }
  52945. }
  52946. return false;
  52947. },
  52948. enumerable: true,
  52949. configurable: true
  52950. });
  52951. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52952. /**
  52953. * Does exist one action manager with at least one pick trigger
  52954. **/
  52955. get: function () {
  52956. for (var t in ActionManager.Triggers) {
  52957. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52958. var t_int = parseInt(t);
  52959. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52960. return true;
  52961. }
  52962. }
  52963. }
  52964. return false;
  52965. },
  52966. enumerable: true,
  52967. configurable: true
  52968. });
  52969. /**
  52970. * Does exist one action manager that handles actions of a given trigger
  52971. * @param trigger defines the trigger to be tested
  52972. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52973. **/
  52974. ActionManager.HasSpecificTrigger = function (trigger) {
  52975. for (var t in ActionManager.Triggers) {
  52976. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52977. var t_int = parseInt(t);
  52978. if (t_int === trigger) {
  52979. return true;
  52980. }
  52981. }
  52982. }
  52983. return false;
  52984. };
  52985. /**
  52986. * Registers an action to this action manager
  52987. * @param action defines the action to be registered
  52988. * @return the action amended (prepared) after registration
  52989. */
  52990. ActionManager.prototype.registerAction = function (action) {
  52991. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52992. if (this.getScene().actionManager !== this) {
  52993. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52994. return null;
  52995. }
  52996. }
  52997. this.actions.push(action);
  52998. if (ActionManager.Triggers[action.trigger]) {
  52999. ActionManager.Triggers[action.trigger]++;
  53000. }
  53001. else {
  53002. ActionManager.Triggers[action.trigger] = 1;
  53003. }
  53004. action._actionManager = this;
  53005. action._prepare();
  53006. return action;
  53007. };
  53008. /**
  53009. * Unregisters an action to this action manager
  53010. * @param action defines the action to be unregistered
  53011. * @return a boolean indicating whether the action has been unregistered
  53012. */
  53013. ActionManager.prototype.unregisterAction = function (action) {
  53014. var index = this.actions.indexOf(action);
  53015. if (index !== -1) {
  53016. this.actions.splice(index, 1);
  53017. ActionManager.Triggers[action.trigger] -= 1;
  53018. if (ActionManager.Triggers[action.trigger] === 0) {
  53019. delete ActionManager.Triggers[action.trigger];
  53020. }
  53021. delete action._actionManager;
  53022. return true;
  53023. }
  53024. return false;
  53025. };
  53026. /**
  53027. * Process a specific trigger
  53028. * @param trigger defines the trigger to process
  53029. * @param evt defines the event details to be processed
  53030. */
  53031. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53032. for (var index = 0; index < this.actions.length; index++) {
  53033. var action = this.actions[index];
  53034. if (action.trigger === trigger) {
  53035. if (evt) {
  53036. if (trigger === ActionManager.OnKeyUpTrigger
  53037. || trigger === ActionManager.OnKeyDownTrigger) {
  53038. var parameter = action.getTriggerParameter();
  53039. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53040. if (!parameter.toLowerCase) {
  53041. continue;
  53042. }
  53043. var lowerCase = parameter.toLowerCase();
  53044. if (lowerCase !== evt.sourceEvent.key) {
  53045. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53046. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53047. if (actualkey !== lowerCase) {
  53048. continue;
  53049. }
  53050. }
  53051. }
  53052. }
  53053. }
  53054. action._executeCurrent(evt);
  53055. }
  53056. }
  53057. };
  53058. /** @hidden */
  53059. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53060. var properties = propertyPath.split(".");
  53061. for (var index = 0; index < properties.length - 1; index++) {
  53062. target = target[properties[index]];
  53063. }
  53064. return target;
  53065. };
  53066. /** @hidden */
  53067. ActionManager.prototype._getProperty = function (propertyPath) {
  53068. var properties = propertyPath.split(".");
  53069. return properties[properties.length - 1];
  53070. };
  53071. /**
  53072. * Serialize this manager to a JSON object
  53073. * @param name defines the property name to store this manager
  53074. * @returns a JSON representation of this manager
  53075. */
  53076. ActionManager.prototype.serialize = function (name) {
  53077. var root = {
  53078. children: new Array(),
  53079. name: name,
  53080. type: 3,
  53081. properties: new Array() // Empty for root but required
  53082. };
  53083. for (var i = 0; i < this.actions.length; i++) {
  53084. var triggerObject = {
  53085. type: 0,
  53086. children: new Array(),
  53087. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53088. properties: new Array()
  53089. };
  53090. var triggerOptions = this.actions[i].triggerOptions;
  53091. if (triggerOptions && typeof triggerOptions !== "number") {
  53092. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53093. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53094. }
  53095. else {
  53096. var parameter = {};
  53097. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53098. if (triggerOptions.parameter.mesh) {
  53099. parameter._meshId = triggerOptions.parameter.mesh.id;
  53100. }
  53101. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53102. }
  53103. }
  53104. // Serialize child action, recursively
  53105. this.actions[i].serialize(triggerObject);
  53106. // Add serialized trigger
  53107. root.children.push(triggerObject);
  53108. }
  53109. return root;
  53110. };
  53111. /**
  53112. * Creates a new ActionManager from a JSON data
  53113. * @param parsedActions defines the JSON data to read from
  53114. * @param object defines the hosting mesh
  53115. * @param scene defines the hosting scene
  53116. */
  53117. ActionManager.Parse = function (parsedActions, object, scene) {
  53118. var actionManager = new ActionManager(scene);
  53119. if (object === null)
  53120. scene.actionManager = actionManager;
  53121. else
  53122. object.actionManager = actionManager;
  53123. // instanciate a new object
  53124. var instanciate = function (name, params) {
  53125. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53126. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53127. newInstance.constructor.apply(newInstance, params);
  53128. return newInstance;
  53129. };
  53130. var parseParameter = function (name, value, target, propertyPath) {
  53131. if (propertyPath === null) {
  53132. // String, boolean or float
  53133. var floatValue = parseFloat(value);
  53134. if (value === "true" || value === "false")
  53135. return value === "true";
  53136. else
  53137. return isNaN(floatValue) ? value : floatValue;
  53138. }
  53139. var effectiveTarget = propertyPath.split(".");
  53140. var values = value.split(",");
  53141. // Get effective Target
  53142. for (var i = 0; i < effectiveTarget.length; i++) {
  53143. target = target[effectiveTarget[i]];
  53144. }
  53145. // Return appropriate value with its type
  53146. if (typeof (target) === "boolean")
  53147. return values[0] === "true";
  53148. if (typeof (target) === "string")
  53149. return values[0];
  53150. // Parameters with multiple values such as Vector3 etc.
  53151. var split = new Array();
  53152. for (var i = 0; i < values.length; i++)
  53153. split.push(parseFloat(values[i]));
  53154. if (target instanceof BABYLON.Vector3)
  53155. return BABYLON.Vector3.FromArray(split);
  53156. if (target instanceof BABYLON.Vector4)
  53157. return BABYLON.Vector4.FromArray(split);
  53158. if (target instanceof BABYLON.Color3)
  53159. return BABYLON.Color3.FromArray(split);
  53160. if (target instanceof BABYLON.Color4)
  53161. return BABYLON.Color4.FromArray(split);
  53162. return parseFloat(values[0]);
  53163. };
  53164. // traverse graph per trigger
  53165. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53166. if (combineArray === void 0) { combineArray = null; }
  53167. if (parsedAction.detached)
  53168. return;
  53169. var parameters = new Array();
  53170. var target = null;
  53171. var propertyPath = null;
  53172. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53173. // Parameters
  53174. if (parsedAction.type === 2)
  53175. parameters.push(actionManager);
  53176. else
  53177. parameters.push(trigger);
  53178. if (combine) {
  53179. var actions = new Array();
  53180. for (var j = 0; j < parsedAction.combine.length; j++) {
  53181. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53182. }
  53183. parameters.push(actions);
  53184. }
  53185. else {
  53186. for (var i = 0; i < parsedAction.properties.length; i++) {
  53187. var value = parsedAction.properties[i].value;
  53188. var name = parsedAction.properties[i].name;
  53189. var targetType = parsedAction.properties[i].targetType;
  53190. if (name === "target")
  53191. if (targetType !== null && targetType === "SceneProperties")
  53192. value = target = scene;
  53193. else
  53194. value = target = scene.getNodeByName(value);
  53195. else if (name === "parent")
  53196. value = scene.getNodeByName(value);
  53197. else if (name === "sound")
  53198. value = scene.getSoundByName(value);
  53199. else if (name !== "propertyPath") {
  53200. if (parsedAction.type === 2 && name === "operator")
  53201. value = BABYLON.ValueCondition[value];
  53202. else
  53203. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53204. }
  53205. else {
  53206. propertyPath = value;
  53207. }
  53208. parameters.push(value);
  53209. }
  53210. }
  53211. if (combineArray === null) {
  53212. parameters.push(condition);
  53213. }
  53214. else {
  53215. parameters.push(null);
  53216. }
  53217. // If interpolate value action
  53218. if (parsedAction.name === "InterpolateValueAction") {
  53219. var param = parameters[parameters.length - 2];
  53220. parameters[parameters.length - 1] = param;
  53221. parameters[parameters.length - 2] = condition;
  53222. }
  53223. // Action or condition(s) and not CombineAction
  53224. var newAction = instanciate(parsedAction.name, parameters);
  53225. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53226. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53227. if (action)
  53228. action.then(nothing);
  53229. else
  53230. actionManager.registerAction(nothing);
  53231. action = nothing;
  53232. }
  53233. if (combineArray === null) {
  53234. if (newAction instanceof BABYLON.Condition) {
  53235. condition = newAction;
  53236. newAction = action;
  53237. }
  53238. else {
  53239. condition = null;
  53240. if (action)
  53241. action.then(newAction);
  53242. else
  53243. actionManager.registerAction(newAction);
  53244. }
  53245. }
  53246. else {
  53247. combineArray.push(newAction);
  53248. }
  53249. for (var i = 0; i < parsedAction.children.length; i++)
  53250. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53251. };
  53252. // triggers
  53253. for (var i = 0; i < parsedActions.children.length; i++) {
  53254. var triggerParams;
  53255. var trigger = parsedActions.children[i];
  53256. if (trigger.properties.length > 0) {
  53257. var param = trigger.properties[0].value;
  53258. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53259. if (value._meshId) {
  53260. value.mesh = scene.getMeshByID(value._meshId);
  53261. }
  53262. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53263. }
  53264. else
  53265. triggerParams = ActionManager[trigger.name];
  53266. for (var j = 0; j < trigger.children.length; j++) {
  53267. if (!trigger.detached)
  53268. traverse(trigger.children[j], triggerParams, null, null);
  53269. }
  53270. }
  53271. };
  53272. /**
  53273. * Get a trigger name by index
  53274. * @param trigger defines the trigger index
  53275. * @returns a trigger name
  53276. */
  53277. ActionManager.GetTriggerName = function (trigger) {
  53278. switch (trigger) {
  53279. case 0: return "NothingTrigger";
  53280. case 1: return "OnPickTrigger";
  53281. case 2: return "OnLeftPickTrigger";
  53282. case 3: return "OnRightPickTrigger";
  53283. case 4: return "OnCenterPickTrigger";
  53284. case 5: return "OnPickDownTrigger";
  53285. case 6: return "OnPickUpTrigger";
  53286. case 7: return "OnLongPressTrigger";
  53287. case 8: return "OnPointerOverTrigger";
  53288. case 9: return "OnPointerOutTrigger";
  53289. case 10: return "OnEveryFrameTrigger";
  53290. case 11: return "OnIntersectionEnterTrigger";
  53291. case 12: return "OnIntersectionExitTrigger";
  53292. case 13: return "OnKeyDownTrigger";
  53293. case 14: return "OnKeyUpTrigger";
  53294. case 15: return "OnPickOutTrigger";
  53295. default: return "";
  53296. }
  53297. };
  53298. // Statics
  53299. ActionManager._NothingTrigger = 0;
  53300. ActionManager._OnPickTrigger = 1;
  53301. ActionManager._OnLeftPickTrigger = 2;
  53302. ActionManager._OnRightPickTrigger = 3;
  53303. ActionManager._OnCenterPickTrigger = 4;
  53304. ActionManager._OnPickDownTrigger = 5;
  53305. ActionManager._OnDoublePickTrigger = 6;
  53306. ActionManager._OnPickUpTrigger = 7;
  53307. ActionManager._OnLongPressTrigger = 8;
  53308. ActionManager._OnPointerOverTrigger = 9;
  53309. ActionManager._OnPointerOutTrigger = 10;
  53310. ActionManager._OnEveryFrameTrigger = 11;
  53311. ActionManager._OnIntersectionEnterTrigger = 12;
  53312. ActionManager._OnIntersectionExitTrigger = 13;
  53313. ActionManager._OnKeyDownTrigger = 14;
  53314. ActionManager._OnKeyUpTrigger = 15;
  53315. ActionManager._OnPickOutTrigger = 16;
  53316. /** Gets the list of active triggers */
  53317. ActionManager.Triggers = {};
  53318. return ActionManager;
  53319. }());
  53320. BABYLON.ActionManager = ActionManager;
  53321. })(BABYLON || (BABYLON = {}));
  53322. //# sourceMappingURL=babylon.actionManager.js.map
  53323. var BABYLON;
  53324. (function (BABYLON) {
  53325. var InterpolateValueAction = /** @class */ (function (_super) {
  53326. __extends(InterpolateValueAction, _super);
  53327. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53328. if (duration === void 0) { duration = 1000; }
  53329. var _this = _super.call(this, triggerOptions, condition) || this;
  53330. _this.propertyPath = propertyPath;
  53331. _this.value = value;
  53332. _this.duration = duration;
  53333. _this.stopOtherAnimations = stopOtherAnimations;
  53334. _this.onInterpolationDone = onInterpolationDone;
  53335. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53336. _this._target = _this._effectiveTarget = target;
  53337. return _this;
  53338. }
  53339. /** @hidden */
  53340. InterpolateValueAction.prototype._prepare = function () {
  53341. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53342. this._property = this._getProperty(this.propertyPath);
  53343. };
  53344. InterpolateValueAction.prototype.execute = function () {
  53345. var _this = this;
  53346. var scene = this._actionManager.getScene();
  53347. var keys = [
  53348. {
  53349. frame: 0,
  53350. value: this._effectiveTarget[this._property]
  53351. }, {
  53352. frame: 100,
  53353. value: this.value
  53354. }
  53355. ];
  53356. var dataType;
  53357. if (typeof this.value === "number") {
  53358. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53359. }
  53360. else if (this.value instanceof BABYLON.Color3) {
  53361. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53362. }
  53363. else if (this.value instanceof BABYLON.Vector3) {
  53364. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53365. }
  53366. else if (this.value instanceof BABYLON.Matrix) {
  53367. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53368. }
  53369. else if (this.value instanceof BABYLON.Quaternion) {
  53370. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53371. }
  53372. else {
  53373. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53374. return;
  53375. }
  53376. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53377. animation.setKeys(keys);
  53378. if (this.stopOtherAnimations) {
  53379. scene.stopAnimation(this._effectiveTarget);
  53380. }
  53381. var wrapper = function () {
  53382. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53383. if (_this.onInterpolationDone) {
  53384. _this.onInterpolationDone();
  53385. }
  53386. };
  53387. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53388. };
  53389. InterpolateValueAction.prototype.serialize = function (parent) {
  53390. return _super.prototype._serialize.call(this, {
  53391. name: "InterpolateValueAction",
  53392. properties: [
  53393. BABYLON.Action._GetTargetProperty(this._target),
  53394. { name: "propertyPath", value: this.propertyPath },
  53395. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53396. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53397. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53398. ]
  53399. }, parent);
  53400. };
  53401. return InterpolateValueAction;
  53402. }(BABYLON.Action));
  53403. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53404. })(BABYLON || (BABYLON = {}));
  53405. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53406. var BABYLON;
  53407. (function (BABYLON) {
  53408. var SwitchBooleanAction = /** @class */ (function (_super) {
  53409. __extends(SwitchBooleanAction, _super);
  53410. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53411. var _this = _super.call(this, triggerOptions, condition) || this;
  53412. _this.propertyPath = propertyPath;
  53413. _this._target = _this._effectiveTarget = target;
  53414. return _this;
  53415. }
  53416. /** @hidden */
  53417. SwitchBooleanAction.prototype._prepare = function () {
  53418. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53419. this._property = this._getProperty(this.propertyPath);
  53420. };
  53421. SwitchBooleanAction.prototype.execute = function () {
  53422. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53423. };
  53424. SwitchBooleanAction.prototype.serialize = function (parent) {
  53425. return _super.prototype._serialize.call(this, {
  53426. name: "SwitchBooleanAction",
  53427. properties: [
  53428. BABYLON.Action._GetTargetProperty(this._target),
  53429. { name: "propertyPath", value: this.propertyPath }
  53430. ]
  53431. }, parent);
  53432. };
  53433. return SwitchBooleanAction;
  53434. }(BABYLON.Action));
  53435. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53436. var SetStateAction = /** @class */ (function (_super) {
  53437. __extends(SetStateAction, _super);
  53438. function SetStateAction(triggerOptions, target, value, condition) {
  53439. var _this = _super.call(this, triggerOptions, condition) || this;
  53440. _this.value = value;
  53441. _this._target = target;
  53442. return _this;
  53443. }
  53444. SetStateAction.prototype.execute = function () {
  53445. this._target.state = this.value;
  53446. };
  53447. SetStateAction.prototype.serialize = function (parent) {
  53448. return _super.prototype._serialize.call(this, {
  53449. name: "SetStateAction",
  53450. properties: [
  53451. BABYLON.Action._GetTargetProperty(this._target),
  53452. { name: "value", value: this.value }
  53453. ]
  53454. }, parent);
  53455. };
  53456. return SetStateAction;
  53457. }(BABYLON.Action));
  53458. BABYLON.SetStateAction = SetStateAction;
  53459. var SetValueAction = /** @class */ (function (_super) {
  53460. __extends(SetValueAction, _super);
  53461. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53462. var _this = _super.call(this, triggerOptions, condition) || this;
  53463. _this.propertyPath = propertyPath;
  53464. _this.value = value;
  53465. _this._target = _this._effectiveTarget = target;
  53466. return _this;
  53467. }
  53468. /** @hidden */
  53469. SetValueAction.prototype._prepare = function () {
  53470. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53471. this._property = this._getProperty(this.propertyPath);
  53472. };
  53473. SetValueAction.prototype.execute = function () {
  53474. this._effectiveTarget[this._property] = this.value;
  53475. if (this._target.markAsDirty) {
  53476. this._target.markAsDirty(this._property);
  53477. }
  53478. };
  53479. SetValueAction.prototype.serialize = function (parent) {
  53480. return _super.prototype._serialize.call(this, {
  53481. name: "SetValueAction",
  53482. properties: [
  53483. BABYLON.Action._GetTargetProperty(this._target),
  53484. { name: "propertyPath", value: this.propertyPath },
  53485. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53486. ]
  53487. }, parent);
  53488. };
  53489. return SetValueAction;
  53490. }(BABYLON.Action));
  53491. BABYLON.SetValueAction = SetValueAction;
  53492. var IncrementValueAction = /** @class */ (function (_super) {
  53493. __extends(IncrementValueAction, _super);
  53494. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53495. var _this = _super.call(this, triggerOptions, condition) || this;
  53496. _this.propertyPath = propertyPath;
  53497. _this.value = value;
  53498. _this._target = _this._effectiveTarget = target;
  53499. return _this;
  53500. }
  53501. /** @hidden */
  53502. IncrementValueAction.prototype._prepare = function () {
  53503. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53504. this._property = this._getProperty(this.propertyPath);
  53505. if (typeof this._effectiveTarget[this._property] !== "number") {
  53506. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53507. }
  53508. };
  53509. IncrementValueAction.prototype.execute = function () {
  53510. this._effectiveTarget[this._property] += this.value;
  53511. if (this._target.markAsDirty) {
  53512. this._target.markAsDirty(this._property);
  53513. }
  53514. };
  53515. IncrementValueAction.prototype.serialize = function (parent) {
  53516. return _super.prototype._serialize.call(this, {
  53517. name: "IncrementValueAction",
  53518. properties: [
  53519. BABYLON.Action._GetTargetProperty(this._target),
  53520. { name: "propertyPath", value: this.propertyPath },
  53521. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53522. ]
  53523. }, parent);
  53524. };
  53525. return IncrementValueAction;
  53526. }(BABYLON.Action));
  53527. BABYLON.IncrementValueAction = IncrementValueAction;
  53528. var PlayAnimationAction = /** @class */ (function (_super) {
  53529. __extends(PlayAnimationAction, _super);
  53530. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53531. var _this = _super.call(this, triggerOptions, condition) || this;
  53532. _this.from = from;
  53533. _this.to = to;
  53534. _this.loop = loop;
  53535. _this._target = target;
  53536. return _this;
  53537. }
  53538. /** @hidden */
  53539. PlayAnimationAction.prototype._prepare = function () {
  53540. };
  53541. PlayAnimationAction.prototype.execute = function () {
  53542. var scene = this._actionManager.getScene();
  53543. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53544. };
  53545. PlayAnimationAction.prototype.serialize = function (parent) {
  53546. return _super.prototype._serialize.call(this, {
  53547. name: "PlayAnimationAction",
  53548. properties: [
  53549. BABYLON.Action._GetTargetProperty(this._target),
  53550. { name: "from", value: String(this.from) },
  53551. { name: "to", value: String(this.to) },
  53552. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53553. ]
  53554. }, parent);
  53555. };
  53556. return PlayAnimationAction;
  53557. }(BABYLON.Action));
  53558. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53559. var StopAnimationAction = /** @class */ (function (_super) {
  53560. __extends(StopAnimationAction, _super);
  53561. function StopAnimationAction(triggerOptions, target, condition) {
  53562. var _this = _super.call(this, triggerOptions, condition) || this;
  53563. _this._target = target;
  53564. return _this;
  53565. }
  53566. /** @hidden */
  53567. StopAnimationAction.prototype._prepare = function () {
  53568. };
  53569. StopAnimationAction.prototype.execute = function () {
  53570. var scene = this._actionManager.getScene();
  53571. scene.stopAnimation(this._target);
  53572. };
  53573. StopAnimationAction.prototype.serialize = function (parent) {
  53574. return _super.prototype._serialize.call(this, {
  53575. name: "StopAnimationAction",
  53576. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53577. }, parent);
  53578. };
  53579. return StopAnimationAction;
  53580. }(BABYLON.Action));
  53581. BABYLON.StopAnimationAction = StopAnimationAction;
  53582. var DoNothingAction = /** @class */ (function (_super) {
  53583. __extends(DoNothingAction, _super);
  53584. function DoNothingAction(triggerOptions, condition) {
  53585. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53586. return _super.call(this, triggerOptions, condition) || this;
  53587. }
  53588. DoNothingAction.prototype.execute = function () {
  53589. };
  53590. DoNothingAction.prototype.serialize = function (parent) {
  53591. return _super.prototype._serialize.call(this, {
  53592. name: "DoNothingAction",
  53593. properties: []
  53594. }, parent);
  53595. };
  53596. return DoNothingAction;
  53597. }(BABYLON.Action));
  53598. BABYLON.DoNothingAction = DoNothingAction;
  53599. var CombineAction = /** @class */ (function (_super) {
  53600. __extends(CombineAction, _super);
  53601. function CombineAction(triggerOptions, children, condition) {
  53602. var _this = _super.call(this, triggerOptions, condition) || this;
  53603. _this.children = children;
  53604. return _this;
  53605. }
  53606. /** @hidden */
  53607. CombineAction.prototype._prepare = function () {
  53608. for (var index = 0; index < this.children.length; index++) {
  53609. this.children[index]._actionManager = this._actionManager;
  53610. this.children[index]._prepare();
  53611. }
  53612. };
  53613. CombineAction.prototype.execute = function (evt) {
  53614. for (var index = 0; index < this.children.length; index++) {
  53615. this.children[index].execute(evt);
  53616. }
  53617. };
  53618. CombineAction.prototype.serialize = function (parent) {
  53619. var serializationObject = _super.prototype._serialize.call(this, {
  53620. name: "CombineAction",
  53621. properties: [],
  53622. combine: []
  53623. }, parent);
  53624. for (var i = 0; i < this.children.length; i++) {
  53625. serializationObject.combine.push(this.children[i].serialize(null));
  53626. }
  53627. return serializationObject;
  53628. };
  53629. return CombineAction;
  53630. }(BABYLON.Action));
  53631. BABYLON.CombineAction = CombineAction;
  53632. var ExecuteCodeAction = /** @class */ (function (_super) {
  53633. __extends(ExecuteCodeAction, _super);
  53634. function ExecuteCodeAction(triggerOptions, func, condition) {
  53635. var _this = _super.call(this, triggerOptions, condition) || this;
  53636. _this.func = func;
  53637. return _this;
  53638. }
  53639. ExecuteCodeAction.prototype.execute = function (evt) {
  53640. this.func(evt);
  53641. };
  53642. return ExecuteCodeAction;
  53643. }(BABYLON.Action));
  53644. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53645. var SetParentAction = /** @class */ (function (_super) {
  53646. __extends(SetParentAction, _super);
  53647. function SetParentAction(triggerOptions, target, parent, condition) {
  53648. var _this = _super.call(this, triggerOptions, condition) || this;
  53649. _this._target = target;
  53650. _this._parent = parent;
  53651. return _this;
  53652. }
  53653. /** @hidden */
  53654. SetParentAction.prototype._prepare = function () {
  53655. };
  53656. SetParentAction.prototype.execute = function () {
  53657. if (this._target.parent === this._parent) {
  53658. return;
  53659. }
  53660. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53661. invertParentWorldMatrix.invert();
  53662. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53663. this._target.parent = this._parent;
  53664. };
  53665. SetParentAction.prototype.serialize = function (parent) {
  53666. return _super.prototype._serialize.call(this, {
  53667. name: "SetParentAction",
  53668. properties: [
  53669. BABYLON.Action._GetTargetProperty(this._target),
  53670. BABYLON.Action._GetTargetProperty(this._parent),
  53671. ]
  53672. }, parent);
  53673. };
  53674. return SetParentAction;
  53675. }(BABYLON.Action));
  53676. BABYLON.SetParentAction = SetParentAction;
  53677. var PlaySoundAction = /** @class */ (function (_super) {
  53678. __extends(PlaySoundAction, _super);
  53679. function PlaySoundAction(triggerOptions, sound, condition) {
  53680. var _this = _super.call(this, triggerOptions, condition) || this;
  53681. _this._sound = sound;
  53682. return _this;
  53683. }
  53684. /** @hidden */
  53685. PlaySoundAction.prototype._prepare = function () {
  53686. };
  53687. PlaySoundAction.prototype.execute = function () {
  53688. if (this._sound !== undefined)
  53689. this._sound.play();
  53690. };
  53691. PlaySoundAction.prototype.serialize = function (parent) {
  53692. return _super.prototype._serialize.call(this, {
  53693. name: "PlaySoundAction",
  53694. properties: [{ name: "sound", value: this._sound.name }]
  53695. }, parent);
  53696. };
  53697. return PlaySoundAction;
  53698. }(BABYLON.Action));
  53699. BABYLON.PlaySoundAction = PlaySoundAction;
  53700. var StopSoundAction = /** @class */ (function (_super) {
  53701. __extends(StopSoundAction, _super);
  53702. function StopSoundAction(triggerOptions, sound, condition) {
  53703. var _this = _super.call(this, triggerOptions, condition) || this;
  53704. _this._sound = sound;
  53705. return _this;
  53706. }
  53707. /** @hidden */
  53708. StopSoundAction.prototype._prepare = function () {
  53709. };
  53710. StopSoundAction.prototype.execute = function () {
  53711. if (this._sound !== undefined)
  53712. this._sound.stop();
  53713. };
  53714. StopSoundAction.prototype.serialize = function (parent) {
  53715. return _super.prototype._serialize.call(this, {
  53716. name: "StopSoundAction",
  53717. properties: [{ name: "sound", value: this._sound.name }]
  53718. }, parent);
  53719. };
  53720. return StopSoundAction;
  53721. }(BABYLON.Action));
  53722. BABYLON.StopSoundAction = StopSoundAction;
  53723. })(BABYLON || (BABYLON = {}));
  53724. //# sourceMappingURL=babylon.directActions.js.map
  53725. var BABYLON;
  53726. (function (BABYLON) {
  53727. var SpriteManager = /** @class */ (function () {
  53728. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53729. if (epsilon === void 0) { epsilon = 0.01; }
  53730. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53731. this.name = name;
  53732. this.sprites = new Array();
  53733. this.renderingGroupId = 0;
  53734. this.layerMask = 0x0FFFFFFF;
  53735. this.fogEnabled = true;
  53736. this.isPickable = false;
  53737. /**
  53738. * An event triggered when the manager is disposed.
  53739. */
  53740. this.onDisposeObservable = new BABYLON.Observable();
  53741. this._vertexBuffers = {};
  53742. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53743. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53744. }
  53745. this._capacity = capacity;
  53746. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53747. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53748. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53749. if (cellSize.width && cellSize.height) {
  53750. this.cellWidth = cellSize.width;
  53751. this.cellHeight = cellSize.height;
  53752. }
  53753. else if (cellSize !== undefined) {
  53754. this.cellWidth = cellSize;
  53755. this.cellHeight = cellSize;
  53756. }
  53757. else {
  53758. return;
  53759. }
  53760. this._epsilon = epsilon;
  53761. this._scene = scene;
  53762. this._scene.spriteManagers.push(this);
  53763. var indices = [];
  53764. var index = 0;
  53765. for (var count = 0; count < capacity; count++) {
  53766. indices.push(index);
  53767. indices.push(index + 1);
  53768. indices.push(index + 2);
  53769. indices.push(index);
  53770. indices.push(index + 2);
  53771. indices.push(index + 3);
  53772. index += 4;
  53773. }
  53774. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53775. // VBO
  53776. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53777. this._vertexData = new Float32Array(capacity * 16 * 4);
  53778. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53779. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53780. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53781. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53782. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53783. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53784. this._vertexBuffers["options"] = options;
  53785. this._vertexBuffers["cellInfo"] = cellInfo;
  53786. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53787. // Effects
  53788. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53789. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53790. }
  53791. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53792. set: function (callback) {
  53793. if (this._onDisposeObserver) {
  53794. this.onDisposeObservable.remove(this._onDisposeObserver);
  53795. }
  53796. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53797. },
  53798. enumerable: true,
  53799. configurable: true
  53800. });
  53801. Object.defineProperty(SpriteManager.prototype, "texture", {
  53802. get: function () {
  53803. return this._spriteTexture;
  53804. },
  53805. set: function (value) {
  53806. this._spriteTexture = value;
  53807. },
  53808. enumerable: true,
  53809. configurable: true
  53810. });
  53811. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53812. var arrayOffset = index * 16;
  53813. if (offsetX === 0)
  53814. offsetX = this._epsilon;
  53815. else if (offsetX === 1)
  53816. offsetX = 1 - this._epsilon;
  53817. if (offsetY === 0)
  53818. offsetY = this._epsilon;
  53819. else if (offsetY === 1)
  53820. offsetY = 1 - this._epsilon;
  53821. this._vertexData[arrayOffset] = sprite.position.x;
  53822. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53823. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53824. this._vertexData[arrayOffset + 3] = sprite.angle;
  53825. this._vertexData[arrayOffset + 4] = sprite.width;
  53826. this._vertexData[arrayOffset + 5] = sprite.height;
  53827. this._vertexData[arrayOffset + 6] = offsetX;
  53828. this._vertexData[arrayOffset + 7] = offsetY;
  53829. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53830. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53831. var offset = (sprite.cellIndex / rowSize) >> 0;
  53832. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53833. this._vertexData[arrayOffset + 11] = offset;
  53834. // Color
  53835. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53836. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53837. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53838. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53839. };
  53840. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53841. var count = Math.min(this._capacity, this.sprites.length);
  53842. var min = BABYLON.Vector3.Zero();
  53843. var max = BABYLON.Vector3.Zero();
  53844. var distance = Number.MAX_VALUE;
  53845. var currentSprite = null;
  53846. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53847. var cameraView = camera.getViewMatrix();
  53848. for (var index = 0; index < count; index++) {
  53849. var sprite = this.sprites[index];
  53850. if (!sprite) {
  53851. continue;
  53852. }
  53853. if (predicate) {
  53854. if (!predicate(sprite)) {
  53855. continue;
  53856. }
  53857. }
  53858. else if (!sprite.isPickable) {
  53859. continue;
  53860. }
  53861. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53862. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53863. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53864. if (ray.intersectsBoxMinMax(min, max)) {
  53865. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53866. if (distance > currentDistance) {
  53867. distance = currentDistance;
  53868. currentSprite = sprite;
  53869. if (fastCheck) {
  53870. break;
  53871. }
  53872. }
  53873. }
  53874. }
  53875. if (currentSprite) {
  53876. var result = new BABYLON.PickingInfo();
  53877. result.hit = true;
  53878. result.pickedSprite = currentSprite;
  53879. result.distance = distance;
  53880. return result;
  53881. }
  53882. return null;
  53883. };
  53884. SpriteManager.prototype.render = function () {
  53885. // Check
  53886. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53887. return;
  53888. var engine = this._scene.getEngine();
  53889. var baseSize = this._spriteTexture.getBaseSize();
  53890. // Sprites
  53891. var deltaTime = engine.getDeltaTime();
  53892. var max = Math.min(this._capacity, this.sprites.length);
  53893. var rowSize = baseSize.width / this.cellWidth;
  53894. var offset = 0;
  53895. for (var index = 0; index < max; index++) {
  53896. var sprite = this.sprites[index];
  53897. if (!sprite || !sprite.isVisible) {
  53898. continue;
  53899. }
  53900. sprite._animate(deltaTime);
  53901. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53902. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53903. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53904. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53905. }
  53906. this._buffer.update(this._vertexData);
  53907. // Render
  53908. var effect = this._effectBase;
  53909. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53910. effect = this._effectFog;
  53911. }
  53912. engine.enableEffect(effect);
  53913. var viewMatrix = this._scene.getViewMatrix();
  53914. effect.setTexture("diffuseSampler", this._spriteTexture);
  53915. effect.setMatrix("view", viewMatrix);
  53916. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53917. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53918. // Fog
  53919. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53920. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53921. effect.setColor3("vFogColor", this._scene.fogColor);
  53922. }
  53923. // VBOs
  53924. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53925. // Draw order
  53926. engine.setDepthFunctionToLessOrEqual();
  53927. effect.setBool("alphaTest", true);
  53928. engine.setColorWrite(false);
  53929. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53930. engine.setColorWrite(true);
  53931. effect.setBool("alphaTest", false);
  53932. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53933. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53934. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53935. };
  53936. SpriteManager.prototype.dispose = function () {
  53937. if (this._buffer) {
  53938. this._buffer.dispose();
  53939. this._buffer = null;
  53940. }
  53941. if (this._indexBuffer) {
  53942. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53943. this._indexBuffer = null;
  53944. }
  53945. if (this._spriteTexture) {
  53946. this._spriteTexture.dispose();
  53947. this._spriteTexture = null;
  53948. }
  53949. // Remove from scene
  53950. var index = this._scene.spriteManagers.indexOf(this);
  53951. this._scene.spriteManagers.splice(index, 1);
  53952. // Callback
  53953. this.onDisposeObservable.notifyObservers(this);
  53954. this.onDisposeObservable.clear();
  53955. };
  53956. return SpriteManager;
  53957. }());
  53958. BABYLON.SpriteManager = SpriteManager;
  53959. })(BABYLON || (BABYLON = {}));
  53960. //# sourceMappingURL=babylon.spriteManager.js.map
  53961. var BABYLON;
  53962. (function (BABYLON) {
  53963. var Sprite = /** @class */ (function () {
  53964. function Sprite(name, manager) {
  53965. this.name = name;
  53966. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53967. this.width = 1.0;
  53968. this.height = 1.0;
  53969. this.angle = 0;
  53970. this.cellIndex = 0;
  53971. this.invertU = 0;
  53972. this.invertV = 0;
  53973. this.animations = new Array();
  53974. this.isPickable = false;
  53975. this._animationStarted = false;
  53976. this._loopAnimation = false;
  53977. this._fromIndex = 0;
  53978. this._toIndex = 0;
  53979. this._delay = 0;
  53980. this._direction = 1;
  53981. this._time = 0;
  53982. /**
  53983. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53984. */
  53985. this.isVisible = true;
  53986. this._manager = manager;
  53987. this._manager.sprites.push(this);
  53988. this.position = BABYLON.Vector3.Zero();
  53989. }
  53990. Object.defineProperty(Sprite.prototype, "size", {
  53991. get: function () {
  53992. return this.width;
  53993. },
  53994. set: function (value) {
  53995. this.width = value;
  53996. this.height = value;
  53997. },
  53998. enumerable: true,
  53999. configurable: true
  54000. });
  54001. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54002. this._fromIndex = from;
  54003. this._toIndex = to;
  54004. this._loopAnimation = loop;
  54005. this._delay = delay;
  54006. this._animationStarted = true;
  54007. this._direction = from < to ? 1 : -1;
  54008. this.cellIndex = from;
  54009. this._time = 0;
  54010. this._onAnimationEnd = onAnimationEnd;
  54011. };
  54012. Sprite.prototype.stopAnimation = function () {
  54013. this._animationStarted = false;
  54014. };
  54015. /** @hidden */
  54016. Sprite.prototype._animate = function (deltaTime) {
  54017. if (!this._animationStarted)
  54018. return;
  54019. this._time += deltaTime;
  54020. if (this._time > this._delay) {
  54021. this._time = this._time % this._delay;
  54022. this.cellIndex += this._direction;
  54023. if (this.cellIndex > this._toIndex) {
  54024. if (this._loopAnimation) {
  54025. this.cellIndex = this._fromIndex;
  54026. }
  54027. else {
  54028. this.cellIndex = this._toIndex;
  54029. this._animationStarted = false;
  54030. if (this._onAnimationEnd) {
  54031. this._onAnimationEnd();
  54032. }
  54033. if (this.disposeWhenFinishedAnimating) {
  54034. this.dispose();
  54035. }
  54036. }
  54037. }
  54038. }
  54039. };
  54040. Sprite.prototype.dispose = function () {
  54041. for (var i = 0; i < this._manager.sprites.length; i++) {
  54042. if (this._manager.sprites[i] == this) {
  54043. this._manager.sprites.splice(i, 1);
  54044. }
  54045. }
  54046. };
  54047. return Sprite;
  54048. }());
  54049. BABYLON.Sprite = Sprite;
  54050. })(BABYLON || (BABYLON = {}));
  54051. //# sourceMappingURL=babylon.sprite.js.map
  54052. var BABYLON;
  54053. (function (BABYLON) {
  54054. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54055. if (!BABYLON.PickingInfo) {
  54056. return null;
  54057. }
  54058. var pickingInfo = null;
  54059. if (!camera) {
  54060. if (!this.activeCamera) {
  54061. return null;
  54062. }
  54063. camera = this.activeCamera;
  54064. }
  54065. if (this.spriteManagers.length > 0) {
  54066. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  54067. var spriteManager = this.spriteManagers[spriteIndex];
  54068. if (!spriteManager.isPickable) {
  54069. continue;
  54070. }
  54071. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  54072. if (!result || !result.hit)
  54073. continue;
  54074. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  54075. continue;
  54076. pickingInfo = result;
  54077. if (fastCheck) {
  54078. break;
  54079. }
  54080. }
  54081. }
  54082. return pickingInfo || new BABYLON.PickingInfo();
  54083. };
  54084. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  54085. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  54086. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54087. };
  54088. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  54089. if (!this._tempSpritePickingRay) {
  54090. return null;
  54091. }
  54092. if (!camera) {
  54093. if (!this.activeCamera) {
  54094. return null;
  54095. }
  54096. camera = this.activeCamera;
  54097. }
  54098. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  54099. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54100. };
  54101. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  54102. if (this._pointerOverSprite === sprite) {
  54103. return;
  54104. }
  54105. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54106. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54107. }
  54108. this._pointerOverSprite = sprite;
  54109. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54110. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54111. }
  54112. };
  54113. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  54114. return this._pointerOverSprite;
  54115. };
  54116. /**
  54117. * Defines the sprite scene component responsible to manage sprites
  54118. * in a given scene.
  54119. */
  54120. var SpriteSceneComponent = /** @class */ (function () {
  54121. /**
  54122. * Creates a new instance of the component for the given scene
  54123. * @param scene Defines the scene to register the component in
  54124. */
  54125. function SpriteSceneComponent(scene) {
  54126. /**
  54127. * The component name helpfull to identify the component in the list of scene components.
  54128. */
  54129. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  54130. this.scene = scene;
  54131. this.scene.spriteManagers = new Array();
  54132. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  54133. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  54134. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  54135. this._spritePredicate = function (sprite) {
  54136. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  54137. };
  54138. }
  54139. /**
  54140. * Registers the component in a given scene
  54141. */
  54142. SpriteSceneComponent.prototype.register = function () {
  54143. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  54144. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  54145. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  54146. };
  54147. /**
  54148. * Rebuilds the elements related to this component in case of
  54149. * context lost for instance.
  54150. */
  54151. SpriteSceneComponent.prototype.rebuild = function () {
  54152. /** Nothing to do for sprites */
  54153. };
  54154. /**
  54155. * Disposes the component and the associated ressources.
  54156. */
  54157. SpriteSceneComponent.prototype.dispose = function () {
  54158. this.scene.onBeforeSpritesRenderingObservable.clear();
  54159. this.scene.onAfterSpritesRenderingObservable.clear();
  54160. var spriteManagers = this.scene.spriteManagers;
  54161. while (spriteManagers.length) {
  54162. spriteManagers[0].dispose();
  54163. }
  54164. };
  54165. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  54166. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  54167. if (result) {
  54168. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  54169. }
  54170. return result;
  54171. };
  54172. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  54173. var scene = this.scene;
  54174. if (isMeshPicked) {
  54175. scene.setPointerOverSprite(null);
  54176. }
  54177. else {
  54178. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  54179. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54180. scene.setPointerOverSprite(pickResult.pickedSprite);
  54181. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  54182. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  54183. }
  54184. else {
  54185. canvas.style.cursor = scene.hoverCursor;
  54186. }
  54187. }
  54188. else {
  54189. scene.setPointerOverSprite(null);
  54190. }
  54191. }
  54192. return pickResult;
  54193. };
  54194. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54195. var scene = this.scene;
  54196. scene._pickedDownSprite = null;
  54197. if (scene.spriteManagers.length > 0) {
  54198. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54199. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54200. if (pickResult.pickedSprite.actionManager) {
  54201. scene._pickedDownSprite = pickResult.pickedSprite;
  54202. switch (evt.button) {
  54203. case 0:
  54204. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54205. break;
  54206. case 1:
  54207. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54208. break;
  54209. case 2:
  54210. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54211. break;
  54212. }
  54213. if (pickResult.pickedSprite.actionManager) {
  54214. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54215. }
  54216. }
  54217. }
  54218. }
  54219. return pickResult;
  54220. };
  54221. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54222. var scene = this.scene;
  54223. if (scene.spriteManagers.length > 0) {
  54224. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54225. if (spritePickResult) {
  54226. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  54227. if (spritePickResult.pickedSprite.actionManager) {
  54228. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54229. if (spritePickResult.pickedSprite.actionManager) {
  54230. if (!this.scene._isPointerSwiping()) {
  54231. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54232. }
  54233. }
  54234. }
  54235. }
  54236. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54237. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54238. }
  54239. }
  54240. }
  54241. return pickResult;
  54242. };
  54243. return SpriteSceneComponent;
  54244. }());
  54245. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54246. })(BABYLON || (BABYLON = {}));
  54247. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54248. var BABYLON;
  54249. (function (BABYLON) {
  54250. var IntersectionInfo = /** @class */ (function () {
  54251. function IntersectionInfo(bu, bv, distance) {
  54252. this.bu = bu;
  54253. this.bv = bv;
  54254. this.distance = distance;
  54255. this.faceId = 0;
  54256. this.subMeshId = 0;
  54257. }
  54258. return IntersectionInfo;
  54259. }());
  54260. BABYLON.IntersectionInfo = IntersectionInfo;
  54261. /**
  54262. * Information about the result of picking within a scene
  54263. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54264. */
  54265. var PickingInfo = /** @class */ (function () {
  54266. function PickingInfo() {
  54267. /**
  54268. * If the pick collided with an object
  54269. */
  54270. this.hit = false;
  54271. /**
  54272. * Distance away where the pick collided
  54273. */
  54274. this.distance = 0;
  54275. /**
  54276. * The location of pick collision
  54277. */
  54278. this.pickedPoint = null;
  54279. /**
  54280. * The mesh corresponding the the pick collision
  54281. */
  54282. this.pickedMesh = null;
  54283. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54284. this.bu = 0;
  54285. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54286. this.bv = 0;
  54287. /** The id of the face on the mesh that was picked */
  54288. this.faceId = -1;
  54289. /** Id of the the submesh that was picked */
  54290. this.subMeshId = 0;
  54291. /** If a sprite was picked, this will be the sprite the pick collided with */
  54292. this.pickedSprite = null;
  54293. /**
  54294. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54295. */
  54296. this.originMesh = null;
  54297. /**
  54298. * The ray that was used to perform the picking.
  54299. */
  54300. this.ray = null;
  54301. }
  54302. /**
  54303. * Gets the normal correspodning to the face the pick collided with
  54304. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54305. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54306. * @returns The normal correspodning to the face the pick collided with
  54307. */
  54308. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54309. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54310. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54311. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54312. return null;
  54313. }
  54314. var indices = this.pickedMesh.getIndices();
  54315. if (!indices) {
  54316. return null;
  54317. }
  54318. var result;
  54319. if (useVerticesNormals) {
  54320. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54321. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54322. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54323. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54324. normal0 = normal0.scale(this.bu);
  54325. normal1 = normal1.scale(this.bv);
  54326. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54327. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54328. }
  54329. else {
  54330. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54331. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54332. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54333. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54334. var p1p2 = vertex1.subtract(vertex2);
  54335. var p3p2 = vertex3.subtract(vertex2);
  54336. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54337. }
  54338. if (useWorldCoordinates) {
  54339. var wm = this.pickedMesh.getWorldMatrix();
  54340. if (this.pickedMesh.nonUniformScaling) {
  54341. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54342. wm = BABYLON.Tmp.Matrix[0];
  54343. wm.setTranslationFromFloats(0, 0, 0);
  54344. wm.invert();
  54345. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54346. wm = BABYLON.Tmp.Matrix[1];
  54347. }
  54348. result = BABYLON.Vector3.TransformNormal(result, wm);
  54349. }
  54350. result.normalize();
  54351. return result;
  54352. };
  54353. /**
  54354. * Gets the texture coordinates of where the pick occured
  54355. * @returns the vector containing the coordnates of the texture
  54356. */
  54357. PickingInfo.prototype.getTextureCoordinates = function () {
  54358. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54359. return null;
  54360. }
  54361. var indices = this.pickedMesh.getIndices();
  54362. if (!indices) {
  54363. return null;
  54364. }
  54365. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54366. if (!uvs) {
  54367. return null;
  54368. }
  54369. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54370. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54371. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54372. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54373. uv1 = uv1.scale(this.bu);
  54374. uv2 = uv2.scale(this.bv);
  54375. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54376. };
  54377. return PickingInfo;
  54378. }());
  54379. BABYLON.PickingInfo = PickingInfo;
  54380. })(BABYLON || (BABYLON = {}));
  54381. //# sourceMappingURL=babylon.pickingInfo.js.map
  54382. var BABYLON;
  54383. (function (BABYLON) {
  54384. var Ray = /** @class */ (function () {
  54385. function Ray(origin, direction, length) {
  54386. if (length === void 0) { length = Number.MAX_VALUE; }
  54387. this.origin = origin;
  54388. this.direction = direction;
  54389. this.length = length;
  54390. }
  54391. // Methods
  54392. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54393. var d = 0.0;
  54394. var maxValue = Number.MAX_VALUE;
  54395. var inv;
  54396. var min;
  54397. var max;
  54398. var temp;
  54399. if (Math.abs(this.direction.x) < 0.0000001) {
  54400. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54401. return false;
  54402. }
  54403. }
  54404. else {
  54405. inv = 1.0 / this.direction.x;
  54406. min = (minimum.x - this.origin.x) * inv;
  54407. max = (maximum.x - this.origin.x) * inv;
  54408. if (max === -Infinity) {
  54409. max = Infinity;
  54410. }
  54411. if (min > max) {
  54412. temp = min;
  54413. min = max;
  54414. max = temp;
  54415. }
  54416. d = Math.max(min, d);
  54417. maxValue = Math.min(max, maxValue);
  54418. if (d > maxValue) {
  54419. return false;
  54420. }
  54421. }
  54422. if (Math.abs(this.direction.y) < 0.0000001) {
  54423. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54424. return false;
  54425. }
  54426. }
  54427. else {
  54428. inv = 1.0 / this.direction.y;
  54429. min = (minimum.y - this.origin.y) * inv;
  54430. max = (maximum.y - this.origin.y) * inv;
  54431. if (max === -Infinity) {
  54432. max = Infinity;
  54433. }
  54434. if (min > max) {
  54435. temp = min;
  54436. min = max;
  54437. max = temp;
  54438. }
  54439. d = Math.max(min, d);
  54440. maxValue = Math.min(max, maxValue);
  54441. if (d > maxValue) {
  54442. return false;
  54443. }
  54444. }
  54445. if (Math.abs(this.direction.z) < 0.0000001) {
  54446. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54447. return false;
  54448. }
  54449. }
  54450. else {
  54451. inv = 1.0 / this.direction.z;
  54452. min = (minimum.z - this.origin.z) * inv;
  54453. max = (maximum.z - this.origin.z) * inv;
  54454. if (max === -Infinity) {
  54455. max = Infinity;
  54456. }
  54457. if (min > max) {
  54458. temp = min;
  54459. min = max;
  54460. max = temp;
  54461. }
  54462. d = Math.max(min, d);
  54463. maxValue = Math.min(max, maxValue);
  54464. if (d > maxValue) {
  54465. return false;
  54466. }
  54467. }
  54468. return true;
  54469. };
  54470. Ray.prototype.intersectsBox = function (box) {
  54471. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54472. };
  54473. Ray.prototype.intersectsSphere = function (sphere) {
  54474. var x = sphere.center.x - this.origin.x;
  54475. var y = sphere.center.y - this.origin.y;
  54476. var z = sphere.center.z - this.origin.z;
  54477. var pyth = (x * x) + (y * y) + (z * z);
  54478. var rr = sphere.radius * sphere.radius;
  54479. if (pyth <= rr) {
  54480. return true;
  54481. }
  54482. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54483. if (dot < 0.0) {
  54484. return false;
  54485. }
  54486. var temp = pyth - (dot * dot);
  54487. return temp <= rr;
  54488. };
  54489. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54490. if (!this._edge1) {
  54491. this._edge1 = BABYLON.Vector3.Zero();
  54492. this._edge2 = BABYLON.Vector3.Zero();
  54493. this._pvec = BABYLON.Vector3.Zero();
  54494. this._tvec = BABYLON.Vector3.Zero();
  54495. this._qvec = BABYLON.Vector3.Zero();
  54496. }
  54497. vertex1.subtractToRef(vertex0, this._edge1);
  54498. vertex2.subtractToRef(vertex0, this._edge2);
  54499. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54500. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54501. if (det === 0) {
  54502. return null;
  54503. }
  54504. var invdet = 1 / det;
  54505. this.origin.subtractToRef(vertex0, this._tvec);
  54506. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54507. if (bu < 0 || bu > 1.0) {
  54508. return null;
  54509. }
  54510. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54511. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54512. if (bv < 0 || bu + bv > 1.0) {
  54513. return null;
  54514. }
  54515. //check if the distance is longer than the predefined length.
  54516. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54517. if (distance > this.length) {
  54518. return null;
  54519. }
  54520. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54521. };
  54522. Ray.prototype.intersectsPlane = function (plane) {
  54523. var distance;
  54524. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54525. if (Math.abs(result1) < 9.99999997475243E-07) {
  54526. return null;
  54527. }
  54528. else {
  54529. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54530. distance = (-plane.d - result2) / result1;
  54531. if (distance < 0.0) {
  54532. if (distance < -9.99999997475243E-07) {
  54533. return null;
  54534. }
  54535. else {
  54536. return 0;
  54537. }
  54538. }
  54539. return distance;
  54540. }
  54541. };
  54542. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54543. var tm = BABYLON.Tmp.Matrix[0];
  54544. mesh.getWorldMatrix().invertToRef(tm);
  54545. if (this._tmpRay) {
  54546. Ray.TransformToRef(this, tm, this._tmpRay);
  54547. }
  54548. else {
  54549. this._tmpRay = Ray.Transform(this, tm);
  54550. }
  54551. return mesh.intersects(this._tmpRay, fastCheck);
  54552. };
  54553. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54554. if (results) {
  54555. results.length = 0;
  54556. }
  54557. else {
  54558. results = [];
  54559. }
  54560. for (var i = 0; i < meshes.length; i++) {
  54561. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54562. if (pickInfo.hit) {
  54563. results.push(pickInfo);
  54564. }
  54565. }
  54566. results.sort(this._comparePickingInfo);
  54567. return results;
  54568. };
  54569. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54570. if (pickingInfoA.distance < pickingInfoB.distance) {
  54571. return -1;
  54572. }
  54573. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54574. return 1;
  54575. }
  54576. else {
  54577. return 0;
  54578. }
  54579. };
  54580. /**
  54581. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54582. * @param sega the first point of the segment to test the intersection against
  54583. * @param segb the second point of the segment to test the intersection against
  54584. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54585. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54586. */
  54587. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54588. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54589. var u = segb.subtract(sega);
  54590. var v = rsegb.subtract(this.origin);
  54591. var w = sega.subtract(this.origin);
  54592. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54593. var b = BABYLON.Vector3.Dot(u, v);
  54594. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54595. var d = BABYLON.Vector3.Dot(u, w);
  54596. var e = BABYLON.Vector3.Dot(v, w);
  54597. var D = a * c - b * b; // always >= 0
  54598. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54599. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54600. // compute the line parameters of the two closest points
  54601. if (D < Ray.smallnum) { // the lines are almost parallel
  54602. sN = 0.0; // force using point P0 on segment S1
  54603. sD = 1.0; // to prevent possible division by 0.0 later
  54604. tN = e;
  54605. tD = c;
  54606. }
  54607. else { // get the closest points on the infinite lines
  54608. sN = (b * e - c * d);
  54609. tN = (a * e - b * d);
  54610. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54611. sN = 0.0;
  54612. tN = e;
  54613. tD = c;
  54614. }
  54615. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54616. sN = sD;
  54617. tN = e + b;
  54618. tD = c;
  54619. }
  54620. }
  54621. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54622. tN = 0.0;
  54623. // recompute sc for this edge
  54624. if (-d < 0.0) {
  54625. sN = 0.0;
  54626. }
  54627. else if (-d > a)
  54628. sN = sD;
  54629. else {
  54630. sN = -d;
  54631. sD = a;
  54632. }
  54633. }
  54634. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54635. tN = tD;
  54636. // recompute sc for this edge
  54637. if ((-d + b) < 0.0) {
  54638. sN = 0;
  54639. }
  54640. else if ((-d + b) > a) {
  54641. sN = sD;
  54642. }
  54643. else {
  54644. sN = (-d + b);
  54645. sD = a;
  54646. }
  54647. }
  54648. // finally do the division to get sc and tc
  54649. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54650. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54651. // get the difference of the two closest points
  54652. var qtc = v.multiplyByFloats(tc, tc, tc);
  54653. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54654. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54655. if (isIntersected) {
  54656. return qtc.length();
  54657. }
  54658. return -1;
  54659. };
  54660. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54661. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54662. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54663. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54664. this.direction.normalize();
  54665. return this;
  54666. };
  54667. // Statics
  54668. Ray.Zero = function () {
  54669. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54670. };
  54671. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54672. var result = Ray.Zero();
  54673. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54674. };
  54675. /**
  54676. * 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
  54677. * transformed to the given world matrix.
  54678. * @param origin The origin point
  54679. * @param end The end point
  54680. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54681. */
  54682. Ray.CreateNewFromTo = function (origin, end, world) {
  54683. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54684. var direction = end.subtract(origin);
  54685. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54686. direction.normalize();
  54687. return Ray.Transform(new Ray(origin, direction, length), world);
  54688. };
  54689. Ray.Transform = function (ray, matrix) {
  54690. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54691. Ray.TransformToRef(ray, matrix, result);
  54692. return result;
  54693. };
  54694. Ray.TransformToRef = function (ray, matrix, result) {
  54695. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54696. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54697. result.length = ray.length;
  54698. var dir = result.direction;
  54699. var len = dir.length();
  54700. if (!(len === 0 || len === 1)) {
  54701. var num = 1.0 / len;
  54702. dir.x *= num;
  54703. dir.y *= num;
  54704. dir.z *= num;
  54705. result.length *= len;
  54706. }
  54707. };
  54708. Ray.smallnum = 0.00000001;
  54709. Ray.rayl = 10e8;
  54710. return Ray;
  54711. }());
  54712. BABYLON.Ray = Ray;
  54713. })(BABYLON || (BABYLON = {}));
  54714. //# sourceMappingURL=babylon.ray.js.map
  54715. var BABYLON;
  54716. (function (BABYLON) {
  54717. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54718. if (boxMin.x > sphereCenter.x + sphereRadius)
  54719. return false;
  54720. if (sphereCenter.x - sphereRadius > boxMax.x)
  54721. return false;
  54722. if (boxMin.y > sphereCenter.y + sphereRadius)
  54723. return false;
  54724. if (sphereCenter.y - sphereRadius > boxMax.y)
  54725. return false;
  54726. if (boxMin.z > sphereCenter.z + sphereRadius)
  54727. return false;
  54728. if (sphereCenter.z - sphereRadius > boxMax.z)
  54729. return false;
  54730. return true;
  54731. };
  54732. var getLowestRoot = (function () {
  54733. var result = { root: 0, found: false };
  54734. return function (a, b, c, maxR) {
  54735. result.root = 0;
  54736. result.found = false;
  54737. var determinant = b * b - 4.0 * a * c;
  54738. if (determinant < 0)
  54739. return result;
  54740. var sqrtD = Math.sqrt(determinant);
  54741. var r1 = (-b - sqrtD) / (2.0 * a);
  54742. var r2 = (-b + sqrtD) / (2.0 * a);
  54743. if (r1 > r2) {
  54744. var temp = r2;
  54745. r2 = r1;
  54746. r1 = temp;
  54747. }
  54748. if (r1 > 0 && r1 < maxR) {
  54749. result.root = r1;
  54750. result.found = true;
  54751. return result;
  54752. }
  54753. if (r2 > 0 && r2 < maxR) {
  54754. result.root = r2;
  54755. result.found = true;
  54756. return result;
  54757. }
  54758. return result;
  54759. };
  54760. })();
  54761. var Collider = /** @class */ (function () {
  54762. function Collider() {
  54763. this._collisionPoint = BABYLON.Vector3.Zero();
  54764. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54765. this._tempVector = BABYLON.Vector3.Zero();
  54766. this._tempVector2 = BABYLON.Vector3.Zero();
  54767. this._tempVector3 = BABYLON.Vector3.Zero();
  54768. this._tempVector4 = BABYLON.Vector3.Zero();
  54769. this._edge = BABYLON.Vector3.Zero();
  54770. this._baseToVertex = BABYLON.Vector3.Zero();
  54771. this._destinationPoint = BABYLON.Vector3.Zero();
  54772. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54773. this._displacementVector = BABYLON.Vector3.Zero();
  54774. /** @hidden */
  54775. this._radius = BABYLON.Vector3.One();
  54776. /** @hidden */
  54777. this._retry = 0;
  54778. /** @hidden */
  54779. this._basePointWorld = BABYLON.Vector3.Zero();
  54780. this._velocityWorld = BABYLON.Vector3.Zero();
  54781. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54782. this._collisionMask = -1;
  54783. }
  54784. Object.defineProperty(Collider.prototype, "collisionMask", {
  54785. get: function () {
  54786. return this._collisionMask;
  54787. },
  54788. set: function (mask) {
  54789. this._collisionMask = !isNaN(mask) ? mask : -1;
  54790. },
  54791. enumerable: true,
  54792. configurable: true
  54793. });
  54794. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54795. /**
  54796. * Gets the plane normal used to compute the sliding response (in local space)
  54797. */
  54798. get: function () {
  54799. return this._slidePlaneNormal;
  54800. },
  54801. enumerable: true,
  54802. configurable: true
  54803. });
  54804. // Methods
  54805. /** @hidden */
  54806. Collider.prototype._initialize = function (source, dir, e) {
  54807. this._velocity = dir;
  54808. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54809. this._basePoint = source;
  54810. source.multiplyToRef(this._radius, this._basePointWorld);
  54811. dir.multiplyToRef(this._radius, this._velocityWorld);
  54812. this._velocityWorldLength = this._velocityWorld.length();
  54813. this._epsilon = e;
  54814. this.collisionFound = false;
  54815. };
  54816. /** @hidden */
  54817. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54818. pa.subtractToRef(point, this._tempVector);
  54819. pb.subtractToRef(point, this._tempVector2);
  54820. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54821. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54822. if (d < 0)
  54823. return false;
  54824. pc.subtractToRef(point, this._tempVector3);
  54825. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54826. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54827. if (d < 0)
  54828. return false;
  54829. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54830. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54831. return d >= 0;
  54832. };
  54833. /** @hidden */
  54834. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54835. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54836. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54837. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54838. return false;
  54839. }
  54840. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54841. return false;
  54842. return true;
  54843. };
  54844. /** @hidden */
  54845. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54846. var t0;
  54847. var embeddedInPlane = false;
  54848. //defensive programming, actually not needed.
  54849. if (!trianglePlaneArray) {
  54850. trianglePlaneArray = [];
  54851. }
  54852. if (!trianglePlaneArray[faceIndex]) {
  54853. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54854. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54855. }
  54856. var trianglePlane = trianglePlaneArray[faceIndex];
  54857. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54858. return;
  54859. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54860. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54861. if (normalDotVelocity == 0) {
  54862. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54863. return;
  54864. embeddedInPlane = true;
  54865. t0 = 0;
  54866. }
  54867. else {
  54868. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54869. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54870. if (t0 > t1) {
  54871. var temp = t1;
  54872. t1 = t0;
  54873. t0 = temp;
  54874. }
  54875. if (t0 > 1.0 || t1 < 0.0)
  54876. return;
  54877. if (t0 < 0)
  54878. t0 = 0;
  54879. if (t0 > 1.0)
  54880. t0 = 1.0;
  54881. }
  54882. this._collisionPoint.copyFromFloats(0, 0, 0);
  54883. var found = false;
  54884. var t = 1.0;
  54885. if (!embeddedInPlane) {
  54886. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54887. this._velocity.scaleToRef(t0, this._tempVector);
  54888. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54889. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54890. found = true;
  54891. t = t0;
  54892. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54893. }
  54894. }
  54895. if (!found) {
  54896. var velocitySquaredLength = this._velocity.lengthSquared();
  54897. var a = velocitySquaredLength;
  54898. this._basePoint.subtractToRef(p1, this._tempVector);
  54899. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54900. var c = this._tempVector.lengthSquared() - 1.0;
  54901. var lowestRoot = getLowestRoot(a, b, c, t);
  54902. if (lowestRoot.found) {
  54903. t = lowestRoot.root;
  54904. found = true;
  54905. this._collisionPoint.copyFrom(p1);
  54906. }
  54907. this._basePoint.subtractToRef(p2, this._tempVector);
  54908. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54909. c = this._tempVector.lengthSquared() - 1.0;
  54910. lowestRoot = getLowestRoot(a, b, c, t);
  54911. if (lowestRoot.found) {
  54912. t = lowestRoot.root;
  54913. found = true;
  54914. this._collisionPoint.copyFrom(p2);
  54915. }
  54916. this._basePoint.subtractToRef(p3, this._tempVector);
  54917. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54918. c = this._tempVector.lengthSquared() - 1.0;
  54919. lowestRoot = getLowestRoot(a, b, c, t);
  54920. if (lowestRoot.found) {
  54921. t = lowestRoot.root;
  54922. found = true;
  54923. this._collisionPoint.copyFrom(p3);
  54924. }
  54925. p2.subtractToRef(p1, this._edge);
  54926. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54927. var edgeSquaredLength = this._edge.lengthSquared();
  54928. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54929. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54930. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54931. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54932. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54933. lowestRoot = getLowestRoot(a, b, c, t);
  54934. if (lowestRoot.found) {
  54935. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54936. if (f >= 0.0 && f <= 1.0) {
  54937. t = lowestRoot.root;
  54938. found = true;
  54939. this._edge.scaleInPlace(f);
  54940. p1.addToRef(this._edge, this._collisionPoint);
  54941. }
  54942. }
  54943. p3.subtractToRef(p2, this._edge);
  54944. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54945. edgeSquaredLength = this._edge.lengthSquared();
  54946. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54947. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54948. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54949. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54950. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54951. lowestRoot = getLowestRoot(a, b, c, t);
  54952. if (lowestRoot.found) {
  54953. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54954. if (f >= 0.0 && f <= 1.0) {
  54955. t = lowestRoot.root;
  54956. found = true;
  54957. this._edge.scaleInPlace(f);
  54958. p2.addToRef(this._edge, this._collisionPoint);
  54959. }
  54960. }
  54961. p1.subtractToRef(p3, this._edge);
  54962. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54963. edgeSquaredLength = this._edge.lengthSquared();
  54964. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54965. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54966. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54967. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54968. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54969. lowestRoot = getLowestRoot(a, b, c, t);
  54970. if (lowestRoot.found) {
  54971. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54972. if (f >= 0.0 && f <= 1.0) {
  54973. t = lowestRoot.root;
  54974. found = true;
  54975. this._edge.scaleInPlace(f);
  54976. p3.addToRef(this._edge, this._collisionPoint);
  54977. }
  54978. }
  54979. }
  54980. if (found) {
  54981. var distToCollision = t * this._velocity.length();
  54982. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54983. if (!this.intersectionPoint) {
  54984. this.intersectionPoint = this._collisionPoint.clone();
  54985. }
  54986. else {
  54987. this.intersectionPoint.copyFrom(this._collisionPoint);
  54988. }
  54989. this._nearestDistance = distToCollision;
  54990. this.collisionFound = true;
  54991. }
  54992. }
  54993. };
  54994. /** @hidden */
  54995. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54996. for (var i = indexStart; i < indexEnd; i += 3) {
  54997. var p1 = pts[indices[i] - decal];
  54998. var p2 = pts[indices[i + 1] - decal];
  54999. var p3 = pts[indices[i + 2] - decal];
  55000. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55001. }
  55002. };
  55003. /** @hidden */
  55004. Collider.prototype._getResponse = function (pos, vel) {
  55005. pos.addToRef(vel, this._destinationPoint);
  55006. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55007. this._basePoint.addToRef(vel, pos);
  55008. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55009. this._slidePlaneNormal.normalize();
  55010. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55011. pos.addInPlace(this._displacementVector);
  55012. this.intersectionPoint.addInPlace(this._displacementVector);
  55013. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55014. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55015. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55016. };
  55017. return Collider;
  55018. }());
  55019. BABYLON.Collider = Collider;
  55020. })(BABYLON || (BABYLON = {}));
  55021. //# sourceMappingURL=babylon.collider.js.map
  55022. var BABYLON;
  55023. (function (BABYLON) {
  55024. //WebWorker code will be inserted to this variable.
  55025. BABYLON.CollisionWorker = "";
  55026. /** Defines supported task for worker process */
  55027. var WorkerTaskType;
  55028. (function (WorkerTaskType) {
  55029. /** Initialization */
  55030. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55031. /** Update of geometry */
  55032. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55033. /** Evaluate collision */
  55034. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55035. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55036. /** Defines kind of replies returned by worker */
  55037. var WorkerReplyType;
  55038. (function (WorkerReplyType) {
  55039. /** Success */
  55040. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55041. /** Unkown error */
  55042. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55043. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55044. var CollisionCoordinatorWorker = /** @class */ (function () {
  55045. function CollisionCoordinatorWorker() {
  55046. var _this = this;
  55047. this._scaledPosition = BABYLON.Vector3.Zero();
  55048. this._scaledVelocity = BABYLON.Vector3.Zero();
  55049. this.onMeshUpdated = function (transformNode) {
  55050. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55051. };
  55052. this.onGeometryUpdated = function (geometry) {
  55053. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55054. };
  55055. this._afterRender = function () {
  55056. if (!_this._init)
  55057. return;
  55058. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55059. return;
  55060. }
  55061. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55062. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55063. if (_this._runningUpdated > 4) {
  55064. return;
  55065. }
  55066. ++_this._runningUpdated;
  55067. var payload = {
  55068. updatedMeshes: _this._addUpdateMeshesList,
  55069. updatedGeometries: _this._addUpdateGeometriesList,
  55070. removedGeometries: _this._toRemoveGeometryArray,
  55071. removedMeshes: _this._toRemoveMeshesArray
  55072. };
  55073. var message = {
  55074. payload: payload,
  55075. taskType: WorkerTaskType.UPDATE
  55076. };
  55077. var serializable = [];
  55078. for (var id in payload.updatedGeometries) {
  55079. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55080. //prepare transferables
  55081. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55082. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55083. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55084. }
  55085. }
  55086. _this._worker.postMessage(message, serializable);
  55087. _this._addUpdateMeshesList = {};
  55088. _this._addUpdateGeometriesList = {};
  55089. _this._toRemoveGeometryArray = [];
  55090. _this._toRemoveMeshesArray = [];
  55091. };
  55092. this._onMessageFromWorker = function (e) {
  55093. var returnData = e.data;
  55094. if (returnData.error != WorkerReplyType.SUCCESS) {
  55095. //TODO what errors can be returned from the worker?
  55096. BABYLON.Tools.Warn("error returned from worker!");
  55097. return;
  55098. }
  55099. switch (returnData.taskType) {
  55100. case WorkerTaskType.INIT:
  55101. _this._init = true;
  55102. //Update the worked with ALL of the scene's current state
  55103. _this._scene.meshes.forEach(function (mesh) {
  55104. _this.onMeshAdded(mesh);
  55105. });
  55106. _this._scene.getGeometries().forEach(function (geometry) {
  55107. _this.onGeometryAdded(geometry);
  55108. });
  55109. break;
  55110. case WorkerTaskType.UPDATE:
  55111. _this._runningUpdated--;
  55112. break;
  55113. case WorkerTaskType.COLLIDE:
  55114. var returnPayload = returnData.payload;
  55115. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55116. return;
  55117. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55118. if (callback) {
  55119. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55120. if (mesh) {
  55121. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55122. }
  55123. }
  55124. //cleanup
  55125. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55126. break;
  55127. }
  55128. };
  55129. this._collisionsCallbackArray = [];
  55130. this._init = false;
  55131. this._runningUpdated = 0;
  55132. this._addUpdateMeshesList = {};
  55133. this._addUpdateGeometriesList = {};
  55134. this._toRemoveGeometryArray = [];
  55135. this._toRemoveMeshesArray = [];
  55136. }
  55137. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55138. if (!this._init)
  55139. return;
  55140. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55141. return;
  55142. position.divideToRef(collider._radius, this._scaledPosition);
  55143. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55144. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55145. var payload = {
  55146. collider: {
  55147. position: this._scaledPosition.asArray(),
  55148. velocity: this._scaledVelocity.asArray(),
  55149. radius: collider._radius.asArray()
  55150. },
  55151. collisionId: collisionIndex,
  55152. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55153. maximumRetry: maximumRetry
  55154. };
  55155. var message = {
  55156. payload: payload,
  55157. taskType: WorkerTaskType.COLLIDE
  55158. };
  55159. this._worker.postMessage(message);
  55160. };
  55161. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55162. this._scene = scene;
  55163. this._scene.registerAfterRender(this._afterRender);
  55164. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55165. this._worker = new Worker(workerUrl);
  55166. this._worker.onmessage = this._onMessageFromWorker;
  55167. var message = {
  55168. payload: {},
  55169. taskType: WorkerTaskType.INIT
  55170. };
  55171. this._worker.postMessage(message);
  55172. };
  55173. CollisionCoordinatorWorker.prototype.destroy = function () {
  55174. this._scene.unregisterAfterRender(this._afterRender);
  55175. this._worker.terminate();
  55176. };
  55177. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55178. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55179. this.onMeshUpdated(mesh);
  55180. };
  55181. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55182. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55183. };
  55184. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55185. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55186. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55187. this.onGeometryUpdated(geometry);
  55188. };
  55189. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55190. this._toRemoveGeometryArray.push(geometry.id);
  55191. };
  55192. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55193. var submeshes = [];
  55194. if (mesh.subMeshes) {
  55195. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55196. var boundingInfo = sm.getBoundingInfo();
  55197. return {
  55198. position: idx,
  55199. verticesStart: sm.verticesStart,
  55200. verticesCount: sm.verticesCount,
  55201. indexStart: sm.indexStart,
  55202. indexCount: sm.indexCount,
  55203. hasMaterial: !!sm.getMaterial(),
  55204. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55205. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55206. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55207. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55208. };
  55209. });
  55210. }
  55211. var geometryId = null;
  55212. if (mesh instanceof BABYLON.Mesh) {
  55213. var geometry = mesh.geometry;
  55214. geometryId = geometry ? geometry.id : null;
  55215. }
  55216. else if (mesh instanceof BABYLON.InstancedMesh) {
  55217. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55218. geometryId = geometry ? geometry.id : null;
  55219. }
  55220. var boundingInfo = mesh.getBoundingInfo();
  55221. return {
  55222. uniqueId: mesh.uniqueId,
  55223. id: mesh.id,
  55224. name: mesh.name,
  55225. geometryId: geometryId,
  55226. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55227. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55228. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55229. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55230. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55231. subMeshes: submeshes,
  55232. checkCollisions: mesh.checkCollisions
  55233. };
  55234. };
  55235. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55236. return {
  55237. id: geometry.id,
  55238. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55239. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55240. indices: new Uint32Array(geometry.getIndices() || []),
  55241. };
  55242. };
  55243. return CollisionCoordinatorWorker;
  55244. }());
  55245. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55246. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55247. function CollisionCoordinatorLegacy() {
  55248. this._scaledPosition = BABYLON.Vector3.Zero();
  55249. this._scaledVelocity = BABYLON.Vector3.Zero();
  55250. this._finalPosition = BABYLON.Vector3.Zero();
  55251. }
  55252. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55253. position.divideToRef(collider._radius, this._scaledPosition);
  55254. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55255. collider.collidedMesh = null;
  55256. collider._retry = 0;
  55257. collider._initialVelocity = this._scaledVelocity;
  55258. collider._initialPosition = this._scaledPosition;
  55259. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55260. this._finalPosition.multiplyInPlace(collider._radius);
  55261. //run the callback
  55262. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55263. };
  55264. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55265. this._scene = scene;
  55266. };
  55267. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55268. //Legacy need no destruction method.
  55269. };
  55270. //No update in legacy mode
  55271. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55272. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55273. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55274. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55275. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55276. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55277. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55278. if (excludedMesh === void 0) { excludedMesh = null; }
  55279. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55280. if (collider._retry >= maximumRetry) {
  55281. finalPosition.copyFrom(position);
  55282. return;
  55283. }
  55284. // Check if this is a mesh else camera or -1
  55285. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55286. collider._initialize(position, velocity, closeDistance);
  55287. // Check all meshes
  55288. for (var index = 0; index < this._scene.meshes.length; index++) {
  55289. var mesh = this._scene.meshes[index];
  55290. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55291. mesh._checkCollision(collider);
  55292. }
  55293. }
  55294. if (!collider.collisionFound) {
  55295. position.addToRef(velocity, finalPosition);
  55296. return;
  55297. }
  55298. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55299. collider._getResponse(position, velocity);
  55300. }
  55301. if (velocity.length() <= closeDistance) {
  55302. finalPosition.copyFrom(position);
  55303. return;
  55304. }
  55305. collider._retry++;
  55306. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55307. };
  55308. return CollisionCoordinatorLegacy;
  55309. }());
  55310. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55311. })(BABYLON || (BABYLON = {}));
  55312. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55313. var BABYLON;
  55314. (function (BABYLON) {
  55315. /**
  55316. * A particle represents one of the element emitted by a particle system.
  55317. * This is mainly define by its coordinates, direction, velocity and age.
  55318. */
  55319. var Particle = /** @class */ (function () {
  55320. /**
  55321. * Creates a new instance Particle
  55322. * @param particleSystem the particle system the particle belongs to
  55323. */
  55324. function Particle(
  55325. /**
  55326. * The particle system the particle belongs to.
  55327. */
  55328. particleSystem) {
  55329. this.particleSystem = particleSystem;
  55330. /**
  55331. * The world position of the particle in the scene.
  55332. */
  55333. this.position = BABYLON.Vector3.Zero();
  55334. /**
  55335. * The world direction of the particle in the scene.
  55336. */
  55337. this.direction = BABYLON.Vector3.Zero();
  55338. /**
  55339. * The color of the particle.
  55340. */
  55341. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55342. /**
  55343. * The color change of the particle per step.
  55344. */
  55345. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55346. /**
  55347. * Defines how long will the life of the particle be.
  55348. */
  55349. this.lifeTime = 1.0;
  55350. /**
  55351. * The current age of the particle.
  55352. */
  55353. this.age = 0;
  55354. /**
  55355. * The current size of the particle.
  55356. */
  55357. this.size = 0;
  55358. /**
  55359. * The current scale of the particle.
  55360. */
  55361. this.scale = new BABYLON.Vector2(1, 1);
  55362. /**
  55363. * The current angle of the particle.
  55364. */
  55365. this.angle = 0;
  55366. /**
  55367. * Defines how fast is the angle changing.
  55368. */
  55369. this.angularSpeed = 0;
  55370. /**
  55371. * Defines the cell index used by the particle to be rendered from a sprite.
  55372. */
  55373. this.cellIndex = 0;
  55374. /** @hidden */
  55375. this._attachedSubEmitters = null;
  55376. /** @hidden */
  55377. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55378. /** @hidden */
  55379. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55380. /** @hidden */
  55381. this._currentSize1 = 0;
  55382. /** @hidden */
  55383. this._currentSize2 = 0;
  55384. /** @hidden */
  55385. this._currentAngularSpeed1 = 0;
  55386. /** @hidden */
  55387. this._currentAngularSpeed2 = 0;
  55388. /** @hidden */
  55389. this._currentVelocity1 = 0;
  55390. /** @hidden */
  55391. this._currentVelocity2 = 0;
  55392. /** @hidden */
  55393. this._currentLimitVelocity1 = 0;
  55394. /** @hidden */
  55395. this._currentLimitVelocity2 = 0;
  55396. /** @hidden */
  55397. this._currentDrag1 = 0;
  55398. /** @hidden */
  55399. this._currentDrag2 = 0;
  55400. this.id = Particle._Count++;
  55401. if (!this.particleSystem.isAnimationSheetEnabled) {
  55402. return;
  55403. }
  55404. this.updateCellInfoFromSystem();
  55405. }
  55406. Particle.prototype.updateCellInfoFromSystem = function () {
  55407. this.cellIndex = this.particleSystem.startSpriteCellID;
  55408. };
  55409. /**
  55410. * Defines how the sprite cell index is updated for the particle
  55411. */
  55412. Particle.prototype.updateCellIndex = function () {
  55413. var offsetAge = this.age;
  55414. if (this.particleSystem.spriteRandomStartCell) {
  55415. if (this._randomCellOffset === undefined) {
  55416. this._randomCellOffset = Math.random() * this.lifeTime;
  55417. }
  55418. offsetAge += this._randomCellOffset;
  55419. }
  55420. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55421. var ratio = BABYLON.Scalar.Clamp(((offsetAge * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55422. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55423. };
  55424. /** @hidden */
  55425. Particle.prototype._reset = function () {
  55426. this.age = 0;
  55427. this._currentColorGradient = null;
  55428. this._currentSizeGradient = null;
  55429. this._currentAngularSpeedGradient = null;
  55430. this._currentVelocityGradient = null;
  55431. this._currentLimitVelocityGradient = null;
  55432. this._currentDragGradient = null;
  55433. this.cellIndex = this.particleSystem.startSpriteCellID;
  55434. this._randomCellOffset = undefined;
  55435. };
  55436. /**
  55437. * Copy the properties of particle to another one.
  55438. * @param other the particle to copy the information to.
  55439. */
  55440. Particle.prototype.copyTo = function (other) {
  55441. other.position.copyFrom(this.position);
  55442. if (this._initialDirection) {
  55443. if (other._initialDirection) {
  55444. other._initialDirection.copyFrom(this._initialDirection);
  55445. }
  55446. else {
  55447. other._initialDirection = this._initialDirection.clone();
  55448. }
  55449. }
  55450. else {
  55451. other._initialDirection = null;
  55452. }
  55453. other.direction.copyFrom(this.direction);
  55454. other.color.copyFrom(this.color);
  55455. other.colorStep.copyFrom(this.colorStep);
  55456. other.lifeTime = this.lifeTime;
  55457. other.age = this.age;
  55458. other._randomCellOffset = undefined;
  55459. other.size = this.size;
  55460. other.scale.copyFrom(this.scale);
  55461. other.angle = this.angle;
  55462. other.angularSpeed = this.angularSpeed;
  55463. other.particleSystem = this.particleSystem;
  55464. other.cellIndex = this.cellIndex;
  55465. other.id = this.id;
  55466. other._attachedSubEmitters = this._attachedSubEmitters;
  55467. if (this._currentColorGradient) {
  55468. other._currentColorGradient = this._currentColorGradient;
  55469. other._currentColor1.copyFrom(this._currentColor1);
  55470. other._currentColor2.copyFrom(this._currentColor2);
  55471. }
  55472. if (this._currentSizeGradient) {
  55473. other._currentSizeGradient = this._currentSizeGradient;
  55474. other._currentSize1 = this._currentSize1;
  55475. other._currentSize2 = this._currentSize2;
  55476. }
  55477. if (this._currentAngularSpeedGradient) {
  55478. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55479. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55480. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55481. }
  55482. if (this._currentVelocityGradient) {
  55483. other._currentVelocityGradient = this._currentVelocityGradient;
  55484. other._currentVelocity1 = this._currentVelocity1;
  55485. other._currentVelocity2 = this._currentVelocity2;
  55486. }
  55487. if (this._currentLimitVelocityGradient) {
  55488. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55489. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55490. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55491. }
  55492. if (this._currentDragGradient) {
  55493. other._currentDragGradient = this._currentDragGradient;
  55494. other._currentDrag1 = this._currentDrag1;
  55495. other._currentDrag2 = this._currentDrag2;
  55496. }
  55497. if (this.particleSystem.isAnimationSheetEnabled) {
  55498. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55499. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55500. }
  55501. if (this.particleSystem.useRampGradients) {
  55502. other.remapData.copyFrom(this.remapData);
  55503. }
  55504. };
  55505. Particle._Count = 0;
  55506. return Particle;
  55507. }());
  55508. BABYLON.Particle = Particle;
  55509. })(BABYLON || (BABYLON = {}));
  55510. //# sourceMappingURL=babylon.particle.js.map
  55511. var BABYLON;
  55512. (function (BABYLON) {
  55513. /**
  55514. * This represents the base class for particle system in Babylon.
  55515. * 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.
  55516. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55517. * @example https://doc.babylonjs.com/babylon101/particles
  55518. */
  55519. var BaseParticleSystem = /** @class */ (function () {
  55520. /**
  55521. * Instantiates a particle system.
  55522. * 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.
  55523. * @param name The name of the particle system
  55524. */
  55525. function BaseParticleSystem(name) {
  55526. /**
  55527. * List of animations used by the particle system.
  55528. */
  55529. this.animations = [];
  55530. /**
  55531. * The rendering group used by the Particle system to chose when to render.
  55532. */
  55533. this.renderingGroupId = 0;
  55534. /**
  55535. * The emitter represents the Mesh or position we are attaching the particle system to.
  55536. */
  55537. this.emitter = null;
  55538. /**
  55539. * The maximum number of particles to emit per frame
  55540. */
  55541. this.emitRate = 10;
  55542. /**
  55543. * If you want to launch only a few particles at once, that can be done, as well.
  55544. */
  55545. this.manualEmitCount = -1;
  55546. /**
  55547. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55548. */
  55549. this.updateSpeed = 0.01;
  55550. /**
  55551. * The amount of time the particle system is running (depends of the overall update speed).
  55552. */
  55553. this.targetStopDuration = 0;
  55554. /**
  55555. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55556. */
  55557. this.disposeOnStop = false;
  55558. /**
  55559. * Minimum power of emitting particles.
  55560. */
  55561. this.minEmitPower = 1;
  55562. /**
  55563. * Maximum power of emitting particles.
  55564. */
  55565. this.maxEmitPower = 1;
  55566. /**
  55567. * Minimum life time of emitting particles.
  55568. */
  55569. this.minLifeTime = 1;
  55570. /**
  55571. * Maximum life time of emitting particles.
  55572. */
  55573. this.maxLifeTime = 1;
  55574. /**
  55575. * Minimum Size of emitting particles.
  55576. */
  55577. this.minSize = 1;
  55578. /**
  55579. * Maximum Size of emitting particles.
  55580. */
  55581. this.maxSize = 1;
  55582. /**
  55583. * Minimum scale of emitting particles on X axis.
  55584. */
  55585. this.minScaleX = 1;
  55586. /**
  55587. * Maximum scale of emitting particles on X axis.
  55588. */
  55589. this.maxScaleX = 1;
  55590. /**
  55591. * Minimum scale of emitting particles on Y axis.
  55592. */
  55593. this.minScaleY = 1;
  55594. /**
  55595. * Maximum scale of emitting particles on Y axis.
  55596. */
  55597. this.maxScaleY = 1;
  55598. /**
  55599. * Gets or sets the minimal initial rotation in radians.
  55600. */
  55601. this.minInitialRotation = 0;
  55602. /**
  55603. * Gets or sets the maximal initial rotation in radians.
  55604. */
  55605. this.maxInitialRotation = 0;
  55606. /**
  55607. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55608. */
  55609. this.minAngularSpeed = 0;
  55610. /**
  55611. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55612. */
  55613. this.maxAngularSpeed = 0;
  55614. /**
  55615. * The layer mask we are rendering the particles through.
  55616. */
  55617. this.layerMask = 0x0FFFFFFF;
  55618. /**
  55619. * This can help using your own shader to render the particle system.
  55620. * The according effect will be created
  55621. */
  55622. this.customShader = null;
  55623. /**
  55624. * By default particle system starts as soon as they are created. This prevents the
  55625. * automatic start to happen and let you decide when to start emitting particles.
  55626. */
  55627. this.preventAutoStart = false;
  55628. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55629. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55630. /**
  55631. * Callback triggered when the particle animation is ending.
  55632. */
  55633. this.onAnimationEnd = null;
  55634. /**
  55635. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55636. */
  55637. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55638. /**
  55639. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55640. * to override the particles.
  55641. */
  55642. this.forceDepthWrite = false;
  55643. /** 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 */
  55644. this.preWarmCycles = 0;
  55645. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55646. this.preWarmStepOffset = 1;
  55647. /**
  55648. * 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)
  55649. */
  55650. this.spriteCellChangeSpeed = 1;
  55651. /**
  55652. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55653. */
  55654. this.startSpriteCellID = 0;
  55655. /**
  55656. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55657. */
  55658. this.endSpriteCellID = 0;
  55659. /**
  55660. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55661. */
  55662. this.spriteCellWidth = 0;
  55663. /**
  55664. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55665. */
  55666. this.spriteCellHeight = 0;
  55667. /**
  55668. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55669. */
  55670. this.spriteRandomStartCell = false;
  55671. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55672. this.translationPivot = new BABYLON.Vector2(0, 0);
  55673. /**
  55674. * You can use gravity if you want to give an orientation to your particles.
  55675. */
  55676. this.gravity = BABYLON.Vector3.Zero();
  55677. this._colorGradients = null;
  55678. this._sizeGradients = null;
  55679. this._lifeTimeGradients = null;
  55680. this._angularSpeedGradients = null;
  55681. this._velocityGradients = null;
  55682. this._limitVelocityGradients = null;
  55683. this._dragGradients = null;
  55684. this._emitRateGradients = null;
  55685. this._startSizeGradients = null;
  55686. this._rampGradients = null;
  55687. this._colorRemapGradients = null;
  55688. this._alphaRemapGradients = null;
  55689. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55690. this.limitVelocityDamping = 0.4;
  55691. /**
  55692. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55693. */
  55694. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55695. /**
  55696. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55697. */
  55698. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55699. /**
  55700. * Color the particle will have at the end of its lifetime
  55701. */
  55702. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55703. /**
  55704. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55705. */
  55706. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55707. /**
  55708. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55709. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55710. */
  55711. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55712. this._isBillboardBased = true;
  55713. /**
  55714. * Local cache of defines for image processing.
  55715. */
  55716. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55717. this.id = name;
  55718. this.name = name;
  55719. }
  55720. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55721. /**
  55722. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55723. */
  55724. get: function () {
  55725. return this._isAnimationSheetEnabled;
  55726. },
  55727. set: function (value) {
  55728. if (this._isAnimationSheetEnabled == value) {
  55729. return;
  55730. }
  55731. this._isAnimationSheetEnabled = value;
  55732. this._reset();
  55733. },
  55734. enumerable: true,
  55735. configurable: true
  55736. });
  55737. /**
  55738. * Get hosting scene
  55739. * @returns the scene
  55740. */
  55741. BaseParticleSystem.prototype.getScene = function () {
  55742. return this._scene;
  55743. };
  55744. /**
  55745. * Gets the current list of drag gradients.
  55746. * You must use addDragGradient and removeDragGradient to udpate this list
  55747. * @returns the list of drag gradients
  55748. */
  55749. BaseParticleSystem.prototype.getDragGradients = function () {
  55750. return this._dragGradients;
  55751. };
  55752. /**
  55753. * Gets the current list of limit velocity gradients.
  55754. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55755. * @returns the list of limit velocity gradients
  55756. */
  55757. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55758. return this._limitVelocityGradients;
  55759. };
  55760. /**
  55761. * Gets the current list of color gradients.
  55762. * You must use addColorGradient and removeColorGradient to udpate this list
  55763. * @returns the list of color gradients
  55764. */
  55765. BaseParticleSystem.prototype.getColorGradients = function () {
  55766. return this._colorGradients;
  55767. };
  55768. /**
  55769. * Gets the current list of size gradients.
  55770. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55771. * @returns the list of size gradients
  55772. */
  55773. BaseParticleSystem.prototype.getSizeGradients = function () {
  55774. return this._sizeGradients;
  55775. };
  55776. /**
  55777. * Gets the current list of color remap gradients.
  55778. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  55779. * @returns the list of color remap gradients
  55780. */
  55781. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  55782. return this._colorRemapGradients;
  55783. };
  55784. /**
  55785. * Gets the current list of alpha remap gradients.
  55786. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  55787. * @returns the list of alpha remap gradients
  55788. */
  55789. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  55790. return this._alphaRemapGradients;
  55791. };
  55792. /**
  55793. * Gets the current list of life time gradients.
  55794. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55795. * @returns the list of life time gradients
  55796. */
  55797. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55798. return this._lifeTimeGradients;
  55799. };
  55800. /**
  55801. * Gets the current list of angular speed gradients.
  55802. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55803. * @returns the list of angular speed gradients
  55804. */
  55805. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55806. return this._angularSpeedGradients;
  55807. };
  55808. /**
  55809. * Gets the current list of velocity gradients.
  55810. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55811. * @returns the list of velocity gradients
  55812. */
  55813. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55814. return this._velocityGradients;
  55815. };
  55816. /**
  55817. * Gets the current list of start size gradients.
  55818. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55819. * @returns the list of start size gradients
  55820. */
  55821. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55822. return this._startSizeGradients;
  55823. };
  55824. /**
  55825. * Gets the current list of emit rate gradients.
  55826. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55827. * @returns the list of emit rate gradients
  55828. */
  55829. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55830. return this._emitRateGradients;
  55831. };
  55832. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55833. /**
  55834. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55835. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55836. */
  55837. get: function () {
  55838. if (this.particleEmitterType.direction1) {
  55839. return this.particleEmitterType.direction1;
  55840. }
  55841. return BABYLON.Vector3.Zero();
  55842. },
  55843. set: function (value) {
  55844. if (this.particleEmitterType.direction1) {
  55845. this.particleEmitterType.direction1 = value;
  55846. }
  55847. },
  55848. enumerable: true,
  55849. configurable: true
  55850. });
  55851. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55852. /**
  55853. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55854. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55855. */
  55856. get: function () {
  55857. if (this.particleEmitterType.direction2) {
  55858. return this.particleEmitterType.direction2;
  55859. }
  55860. return BABYLON.Vector3.Zero();
  55861. },
  55862. set: function (value) {
  55863. if (this.particleEmitterType.direction2) {
  55864. this.particleEmitterType.direction2 = value;
  55865. }
  55866. },
  55867. enumerable: true,
  55868. configurable: true
  55869. });
  55870. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55871. /**
  55872. * 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.
  55873. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55874. */
  55875. get: function () {
  55876. if (this.particleEmitterType.minEmitBox) {
  55877. return this.particleEmitterType.minEmitBox;
  55878. }
  55879. return BABYLON.Vector3.Zero();
  55880. },
  55881. set: function (value) {
  55882. if (this.particleEmitterType.minEmitBox) {
  55883. this.particleEmitterType.minEmitBox = value;
  55884. }
  55885. },
  55886. enumerable: true,
  55887. configurable: true
  55888. });
  55889. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55890. /**
  55891. * 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.
  55892. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55893. */
  55894. get: function () {
  55895. if (this.particleEmitterType.maxEmitBox) {
  55896. return this.particleEmitterType.maxEmitBox;
  55897. }
  55898. return BABYLON.Vector3.Zero();
  55899. },
  55900. set: function (value) {
  55901. if (this.particleEmitterType.maxEmitBox) {
  55902. this.particleEmitterType.maxEmitBox = value;
  55903. }
  55904. },
  55905. enumerable: true,
  55906. configurable: true
  55907. });
  55908. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55909. /**
  55910. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55911. */
  55912. get: function () {
  55913. return this._isBillboardBased;
  55914. },
  55915. set: function (value) {
  55916. if (this._isBillboardBased === value) {
  55917. return;
  55918. }
  55919. this._isBillboardBased = value;
  55920. this._reset();
  55921. },
  55922. enumerable: true,
  55923. configurable: true
  55924. });
  55925. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55926. /**
  55927. * Gets the image processing configuration used either in this material.
  55928. */
  55929. get: function () {
  55930. return this._imageProcessingConfiguration;
  55931. },
  55932. /**
  55933. * Sets the Default image processing configuration used either in the this material.
  55934. *
  55935. * If sets to null, the scene one is in use.
  55936. */
  55937. set: function (value) {
  55938. this._attachImageProcessingConfiguration(value);
  55939. },
  55940. enumerable: true,
  55941. configurable: true
  55942. });
  55943. /**
  55944. * Attaches a new image processing configuration to the Standard Material.
  55945. * @param configuration
  55946. */
  55947. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55948. if (configuration === this._imageProcessingConfiguration) {
  55949. return;
  55950. }
  55951. // Pick the scene configuration if needed.
  55952. if (!configuration) {
  55953. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55954. }
  55955. else {
  55956. this._imageProcessingConfiguration = configuration;
  55957. }
  55958. };
  55959. /** @hidden */
  55960. BaseParticleSystem.prototype._reset = function () {
  55961. };
  55962. /** @hidden */
  55963. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  55964. if (!gradients) {
  55965. return this;
  55966. }
  55967. var index = 0;
  55968. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  55969. var valueGradient = gradients_1[_i];
  55970. if (valueGradient.gradient === gradient) {
  55971. gradients.splice(index, 1);
  55972. break;
  55973. }
  55974. index++;
  55975. }
  55976. if (texture) {
  55977. texture.dispose();
  55978. }
  55979. return this;
  55980. };
  55981. /**
  55982. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55983. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55984. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55985. * @returns the emitter
  55986. */
  55987. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55988. var particleEmitter = new BABYLON.PointParticleEmitter();
  55989. particleEmitter.direction1 = direction1;
  55990. particleEmitter.direction2 = direction2;
  55991. this.particleEmitterType = particleEmitter;
  55992. return particleEmitter;
  55993. };
  55994. /**
  55995. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55996. * @param radius The radius of the hemisphere to emit from
  55997. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55998. * @returns the emitter
  55999. */
  56000. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56001. if (radius === void 0) { radius = 1; }
  56002. if (radiusRange === void 0) { radiusRange = 1; }
  56003. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56004. this.particleEmitterType = particleEmitter;
  56005. return particleEmitter;
  56006. };
  56007. /**
  56008. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56009. * @param radius The radius of the sphere to emit from
  56010. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56011. * @returns the emitter
  56012. */
  56013. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56014. if (radius === void 0) { radius = 1; }
  56015. if (radiusRange === void 0) { radiusRange = 1; }
  56016. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56017. this.particleEmitterType = particleEmitter;
  56018. return particleEmitter;
  56019. };
  56020. /**
  56021. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56022. * @param radius The radius of the sphere to emit from
  56023. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56024. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56025. * @returns the emitter
  56026. */
  56027. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56028. if (radius === void 0) { radius = 1; }
  56029. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56030. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56031. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56032. this.particleEmitterType = particleEmitter;
  56033. return particleEmitter;
  56034. };
  56035. /**
  56036. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56037. * @param radius The radius of the emission cylinder
  56038. * @param height The height of the emission cylinder
  56039. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56040. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56041. * @returns the emitter
  56042. */
  56043. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56044. if (radius === void 0) { radius = 1; }
  56045. if (height === void 0) { height = 1; }
  56046. if (radiusRange === void 0) { radiusRange = 1; }
  56047. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56048. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56049. this.particleEmitterType = particleEmitter;
  56050. return particleEmitter;
  56051. };
  56052. /**
  56053. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  56054. * @param radius The radius of the cylinder to emit from
  56055. * @param height The height of the emission cylinder
  56056. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56057. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  56058. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  56059. * @returns the emitter
  56060. */
  56061. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  56062. if (radius === void 0) { radius = 1; }
  56063. if (height === void 0) { height = 1; }
  56064. if (radiusRange === void 0) { radiusRange = 1; }
  56065. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56066. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56067. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  56068. this.particleEmitterType = particleEmitter;
  56069. return particleEmitter;
  56070. };
  56071. /**
  56072. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56073. * @param radius The radius of the cone to emit from
  56074. * @param angle The base angle of the cone
  56075. * @returns the emitter
  56076. */
  56077. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56078. if (radius === void 0) { radius = 1; }
  56079. if (angle === void 0) { angle = Math.PI / 4; }
  56080. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56081. this.particleEmitterType = particleEmitter;
  56082. return particleEmitter;
  56083. };
  56084. /**
  56085. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56086. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56087. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56088. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56089. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56090. * @returns the emitter
  56091. */
  56092. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56093. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56094. this.particleEmitterType = particleEmitter;
  56095. this.direction1 = direction1;
  56096. this.direction2 = direction2;
  56097. this.minEmitBox = minEmitBox;
  56098. this.maxEmitBox = maxEmitBox;
  56099. return particleEmitter;
  56100. };
  56101. /**
  56102. * Source color is added to the destination color without alpha affecting the result.
  56103. */
  56104. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56105. /**
  56106. * Blend current color and particle color using particle’s alpha.
  56107. */
  56108. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56109. /**
  56110. * Add current color and particle color multiplied by particle’s alpha.
  56111. */
  56112. BaseParticleSystem.BLENDMODE_ADD = 2;
  56113. /**
  56114. * Multiply current color with particle color
  56115. */
  56116. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56117. return BaseParticleSystem;
  56118. }());
  56119. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56120. })(BABYLON || (BABYLON = {}));
  56121. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56122. var BABYLON;
  56123. (function (BABYLON) {
  56124. /**
  56125. * This represents a particle system in Babylon.
  56126. * 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.
  56127. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56128. * @example https://doc.babylonjs.com/babylon101/particles
  56129. */
  56130. var ParticleSystem = /** @class */ (function (_super) {
  56131. __extends(ParticleSystem, _super);
  56132. /**
  56133. * Instantiates a particle system.
  56134. * 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.
  56135. * @param name The name of the particle system
  56136. * @param capacity The max number of particles alive at the same time
  56137. * @param scene The scene the particle system belongs to
  56138. * @param customEffect a custom effect used to change the way particles are rendered by default
  56139. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56140. * @param epsilon Offset used to render the particles
  56141. */
  56142. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56143. if (customEffect === void 0) { customEffect = null; }
  56144. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56145. if (epsilon === void 0) { epsilon = 0.01; }
  56146. var _this = _super.call(this, name) || this;
  56147. /**
  56148. * @hidden
  56149. */
  56150. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  56151. /**
  56152. * An event triggered when the system is disposed
  56153. */
  56154. _this.onDisposeObservable = new BABYLON.Observable();
  56155. _this._particles = new Array();
  56156. _this._stockParticles = new Array();
  56157. _this._newPartsExcess = 0;
  56158. _this._vertexBuffers = {};
  56159. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56160. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56161. _this._scaledDirection = BABYLON.Vector3.Zero();
  56162. _this._scaledGravity = BABYLON.Vector3.Zero();
  56163. _this._currentRenderId = -1;
  56164. _this._useInstancing = false;
  56165. _this._started = false;
  56166. _this._stopped = false;
  56167. _this._actualFrame = 0;
  56168. /** @hidden */
  56169. _this._currentEmitRate1 = 0;
  56170. /** @hidden */
  56171. _this._currentEmitRate2 = 0;
  56172. /** @hidden */
  56173. _this._currentStartSize1 = 0;
  56174. /** @hidden */
  56175. _this._currentStartSize2 = 0;
  56176. _this._rawTextureWidth = 256;
  56177. _this._useRampGradients = false;
  56178. /**
  56179. * @hidden
  56180. * If the particle systems emitter should be disposed when the particle system is disposed
  56181. */
  56182. _this._disposeEmitterOnDispose = false;
  56183. // start of sub system methods
  56184. /**
  56185. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56186. * Its lifetime will start back at 0.
  56187. */
  56188. _this.recycleParticle = function (particle) {
  56189. // move particle from activeParticle list to stock particles
  56190. var lastParticle = _this._particles.pop();
  56191. if (lastParticle !== particle) {
  56192. lastParticle.copyTo(particle);
  56193. }
  56194. _this._stockParticles.push(lastParticle);
  56195. };
  56196. _this._createParticle = function () {
  56197. var particle;
  56198. if (_this._stockParticles.length !== 0) {
  56199. particle = _this._stockParticles.pop();
  56200. particle._reset();
  56201. }
  56202. else {
  56203. particle = new BABYLON.Particle(_this);
  56204. }
  56205. // Attach emitters
  56206. if (_this._subEmitters && _this._subEmitters.length > 0) {
  56207. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  56208. particle._attachedSubEmitters = [];
  56209. subEmitters.forEach(function (subEmitter) {
  56210. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  56211. var newEmitter = subEmitter.clone();
  56212. particle._attachedSubEmitters.push(newEmitter);
  56213. newEmitter.particleSystem.start();
  56214. }
  56215. });
  56216. }
  56217. return particle;
  56218. };
  56219. _this._emitFromParticle = function (particle) {
  56220. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  56221. return;
  56222. }
  56223. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  56224. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  56225. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  56226. var subSystem = subEmitter.clone();
  56227. ParticleSystem._InheritParticleInfoToSubEmitter(subSystem, particle);
  56228. subSystem.particleSystem._rootParticleSystem = _this;
  56229. _this.activeSubSystems.push(subSystem.particleSystem);
  56230. subSystem.particleSystem.start();
  56231. }
  56232. });
  56233. };
  56234. _this._capacity = capacity;
  56235. _this._epsilon = epsilon;
  56236. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56237. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56238. // Setup the default processing configuration to the scene.
  56239. _this._attachImageProcessingConfiguration(null);
  56240. _this._customEffect = customEffect;
  56241. _this._scene.particleSystems.push(_this);
  56242. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56243. _this._createIndexBuffer();
  56244. _this._createVertexBuffers();
  56245. // Default emitter type
  56246. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56247. _this.updateFunction = function (particles) {
  56248. var noiseTextureData = null;
  56249. var noiseTextureSize = null;
  56250. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56251. noiseTextureData = (_this.noiseTexture.readPixels());
  56252. noiseTextureSize = _this.noiseTexture.getSize();
  56253. }
  56254. var _loop_1 = function () {
  56255. particle = particles[index];
  56256. particle.age += _this._scaledUpdateSpeed;
  56257. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56258. _this._emitFromParticle(particle);
  56259. if (particle._attachedSubEmitters) {
  56260. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56261. subEmitter.particleSystem.disposeOnStop = true;
  56262. subEmitter.particleSystem.stop();
  56263. });
  56264. particle._attachedSubEmitters = null;
  56265. }
  56266. _this.recycleParticle(particle);
  56267. index--;
  56268. return "continue";
  56269. }
  56270. else {
  56271. var ratio = particle.age / particle.lifeTime;
  56272. // Color
  56273. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56274. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56275. if (currentGradient !== particle._currentColorGradient) {
  56276. particle._currentColor1.copyFrom(particle._currentColor2);
  56277. nextGradient.getColorToRef(particle._currentColor2);
  56278. particle._currentColorGradient = currentGradient;
  56279. }
  56280. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56281. });
  56282. }
  56283. else {
  56284. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56285. particle.color.addInPlace(_this._scaledColorStep);
  56286. if (particle.color.a < 0) {
  56287. particle.color.a = 0;
  56288. }
  56289. }
  56290. // Angular speed
  56291. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56292. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56293. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56294. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56295. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56296. particle._currentAngularSpeedGradient = currentGradient;
  56297. }
  56298. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56299. });
  56300. }
  56301. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56302. // Direction
  56303. var directionScale_1 = _this._scaledUpdateSpeed;
  56304. /// Velocity
  56305. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56306. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56307. if (currentGradient !== particle._currentVelocityGradient) {
  56308. particle._currentVelocity1 = particle._currentVelocity2;
  56309. particle._currentVelocity2 = nextGradient.getFactor();
  56310. particle._currentVelocityGradient = currentGradient;
  56311. }
  56312. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56313. });
  56314. }
  56315. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56316. /// Limit velocity
  56317. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56318. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56319. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56320. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56321. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56322. particle._currentLimitVelocityGradient = currentGradient;
  56323. }
  56324. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56325. var currentVelocity = particle.direction.length();
  56326. if (currentVelocity > limitVelocity) {
  56327. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56328. }
  56329. });
  56330. }
  56331. /// Drag
  56332. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56333. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56334. if (currentGradient !== particle._currentDragGradient) {
  56335. particle._currentDrag1 = particle._currentDrag2;
  56336. particle._currentDrag2 = nextGradient.getFactor();
  56337. particle._currentDragGradient = currentGradient;
  56338. }
  56339. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56340. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56341. });
  56342. }
  56343. particle.position.addInPlace(_this._scaledDirection);
  56344. // Noise
  56345. if (noiseTextureData && noiseTextureSize) {
  56346. var localPosition = BABYLON.Tmp.Vector3[0];
  56347. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56348. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56349. particle.position.subtractToRef(emitterPosition, localPosition);
  56350. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56351. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56352. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56353. var force = BABYLON.Tmp.Vector3[0];
  56354. var scaledForce = BABYLON.Tmp.Vector3[1];
  56355. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56356. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56357. particle.direction.addInPlace(scaledForce);
  56358. }
  56359. // Gravity
  56360. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56361. particle.direction.addInPlace(_this._scaledGravity);
  56362. // Size
  56363. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56364. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56365. if (currentGradient !== particle._currentSizeGradient) {
  56366. particle._currentSize1 = particle._currentSize2;
  56367. particle._currentSize2 = nextGradient.getFactor();
  56368. particle._currentSizeGradient = currentGradient;
  56369. }
  56370. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56371. });
  56372. }
  56373. // Remap data
  56374. if (_this._useRampGradients) {
  56375. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  56376. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  56377. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56378. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56379. particle.remapData.x = min;
  56380. particle.remapData.y = max - min;
  56381. });
  56382. }
  56383. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  56384. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  56385. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56386. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56387. particle.remapData.z = min;
  56388. particle.remapData.w = max - min;
  56389. });
  56390. }
  56391. }
  56392. if (_this._isAnimationSheetEnabled) {
  56393. particle.updateCellIndex();
  56394. }
  56395. // Update the position of the attached sub-emitters to match their attached particle
  56396. if (particle._attachedSubEmitters && particle._attachedSubEmitters.length > 0) {
  56397. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56398. ParticleSystem._InheritParticleInfoToSubEmitter(subEmitter, particle);
  56399. });
  56400. }
  56401. }
  56402. };
  56403. var particle;
  56404. for (var index = 0; index < particles.length; index++) {
  56405. _loop_1();
  56406. }
  56407. };
  56408. return _this;
  56409. }
  56410. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56411. /**
  56412. * Sets a callback that will be triggered when the system is disposed
  56413. */
  56414. set: function (callback) {
  56415. if (this._onDisposeObserver) {
  56416. this.onDisposeObservable.remove(this._onDisposeObserver);
  56417. }
  56418. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56419. },
  56420. enumerable: true,
  56421. configurable: true
  56422. });
  56423. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  56424. /** Gets or sets a boolean indicating that ramp gradients must be used
  56425. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  56426. */
  56427. get: function () {
  56428. return this._useRampGradients;
  56429. },
  56430. set: function (value) {
  56431. if (this._useRampGradients === value) {
  56432. return;
  56433. }
  56434. this._useRampGradients = value;
  56435. this._resetEffect();
  56436. },
  56437. enumerable: true,
  56438. configurable: true
  56439. });
  56440. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56441. //end of Sub-emitter
  56442. /**
  56443. * Gets the current list of active particles
  56444. */
  56445. get: function () {
  56446. return this._particles;
  56447. },
  56448. enumerable: true,
  56449. configurable: true
  56450. });
  56451. /**
  56452. * Returns the string "ParticleSystem"
  56453. * @returns a string containing the class name
  56454. */
  56455. ParticleSystem.prototype.getClassName = function () {
  56456. return "ParticleSystem";
  56457. };
  56458. ParticleSystem._InheritParticleInfoToSubEmitter = function (subEmitter, particle) {
  56459. if (subEmitter.particleSystem.emitter.position) {
  56460. var emitterMesh = subEmitter.particleSystem.emitter;
  56461. emitterMesh.position.copyFrom(particle.position);
  56462. if (subEmitter.inheritDirection) {
  56463. emitterMesh.position.subtractToRef(particle.direction, BABYLON.Tmp.Vector3[0]);
  56464. // Look at using Y as forward
  56465. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56466. }
  56467. }
  56468. else {
  56469. var emitterPosition = subEmitter.particleSystem.emitter;
  56470. emitterPosition.copyFrom(particle.position);
  56471. if (subEmitter.inheritDirection) {
  56472. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  56473. }
  56474. }
  56475. // Set inheritedVelocityOffset to be used when new particles are created
  56476. particle.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56477. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56478. };
  56479. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56480. var newGradient = new BABYLON.FactorGradient();
  56481. newGradient.gradient = gradient;
  56482. newGradient.factor1 = factor;
  56483. newGradient.factor2 = factor2;
  56484. factorGradients.push(newGradient);
  56485. factorGradients.sort(function (a, b) {
  56486. if (a.gradient < b.gradient) {
  56487. return -1;
  56488. }
  56489. else if (a.gradient > b.gradient) {
  56490. return 1;
  56491. }
  56492. return 0;
  56493. });
  56494. };
  56495. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56496. if (!factorGradients) {
  56497. return;
  56498. }
  56499. var index = 0;
  56500. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56501. var factorGradient = factorGradients_1[_i];
  56502. if (factorGradient.gradient === gradient) {
  56503. factorGradients.splice(index, 1);
  56504. break;
  56505. }
  56506. index++;
  56507. }
  56508. };
  56509. /**
  56510. * Adds a new life time gradient
  56511. * @param gradient defines the gradient to use (between 0 and 1)
  56512. * @param factor defines the life time factor to affect to the specified gradient
  56513. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56514. * @returns the current particle system
  56515. */
  56516. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56517. if (!this._lifeTimeGradients) {
  56518. this._lifeTimeGradients = [];
  56519. }
  56520. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56521. return this;
  56522. };
  56523. /**
  56524. * Remove a specific life time gradient
  56525. * @param gradient defines the gradient to remove
  56526. * @returns the current particle system
  56527. */
  56528. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56529. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56530. return this;
  56531. };
  56532. /**
  56533. * Adds a new size gradient
  56534. * @param gradient defines the gradient to use (between 0 and 1)
  56535. * @param factor defines the size factor to affect to the specified gradient
  56536. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56537. * @returns the current particle system
  56538. */
  56539. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56540. if (!this._sizeGradients) {
  56541. this._sizeGradients = [];
  56542. }
  56543. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56544. return this;
  56545. };
  56546. /**
  56547. * Remove a specific size gradient
  56548. * @param gradient defines the gradient to remove
  56549. * @returns the current particle system
  56550. */
  56551. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56552. this._removeFactorGradient(this._sizeGradients, gradient);
  56553. return this;
  56554. };
  56555. /**
  56556. * Adds a new color remap gradient
  56557. * @param gradient defines the gradient to use (between 0 and 1)
  56558. * @param min defines the color remap minimal range
  56559. * @param max defines the color remap maximal range
  56560. * @returns the current particle system
  56561. */
  56562. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  56563. if (!this._colorRemapGradients) {
  56564. this._colorRemapGradients = [];
  56565. }
  56566. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  56567. return this;
  56568. };
  56569. /**
  56570. * Remove a specific color remap gradient
  56571. * @param gradient defines the gradient to remove
  56572. * @returns the current particle system
  56573. */
  56574. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  56575. this._removeFactorGradient(this._colorRemapGradients, gradient);
  56576. return this;
  56577. };
  56578. /**
  56579. * Adds a new alpha remap gradient
  56580. * @param gradient defines the gradient to use (between 0 and 1)
  56581. * @param min defines the alpha remap minimal range
  56582. * @param max defines the alpha remap maximal range
  56583. * @returns the current particle system
  56584. */
  56585. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  56586. if (!this._alphaRemapGradients) {
  56587. this._alphaRemapGradients = [];
  56588. }
  56589. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  56590. return this;
  56591. };
  56592. /**
  56593. * Remove a specific alpha remap gradient
  56594. * @param gradient defines the gradient to remove
  56595. * @returns the current particle system
  56596. */
  56597. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  56598. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  56599. return this;
  56600. };
  56601. /**
  56602. * Adds a new angular speed gradient
  56603. * @param gradient defines the gradient to use (between 0 and 1)
  56604. * @param factor defines the angular speed to affect to the specified gradient
  56605. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56606. * @returns the current particle system
  56607. */
  56608. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56609. if (!this._angularSpeedGradients) {
  56610. this._angularSpeedGradients = [];
  56611. }
  56612. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56613. return this;
  56614. };
  56615. /**
  56616. * Remove a specific angular speed gradient
  56617. * @param gradient defines the gradient to remove
  56618. * @returns the current particle system
  56619. */
  56620. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56621. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56622. return this;
  56623. };
  56624. /**
  56625. * Adds a new velocity gradient
  56626. * @param gradient defines the gradient to use (between 0 and 1)
  56627. * @param factor defines the velocity to affect to the specified gradient
  56628. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56629. * @returns the current particle system
  56630. */
  56631. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56632. if (!this._velocityGradients) {
  56633. this._velocityGradients = [];
  56634. }
  56635. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56636. return this;
  56637. };
  56638. /**
  56639. * Remove a specific velocity gradient
  56640. * @param gradient defines the gradient to remove
  56641. * @returns the current particle system
  56642. */
  56643. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56644. this._removeFactorGradient(this._velocityGradients, gradient);
  56645. return this;
  56646. };
  56647. /**
  56648. * Adds a new limit velocity gradient
  56649. * @param gradient defines the gradient to use (between 0 and 1)
  56650. * @param factor defines the limit velocity value to affect to the specified gradient
  56651. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56652. * @returns the current particle system
  56653. */
  56654. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56655. if (!this._limitVelocityGradients) {
  56656. this._limitVelocityGradients = [];
  56657. }
  56658. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56659. return this;
  56660. };
  56661. /**
  56662. * Remove a specific limit velocity gradient
  56663. * @param gradient defines the gradient to remove
  56664. * @returns the current particle system
  56665. */
  56666. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56667. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56668. return this;
  56669. };
  56670. /**
  56671. * Adds a new drag gradient
  56672. * @param gradient defines the gradient to use (between 0 and 1)
  56673. * @param factor defines the drag value to affect to the specified gradient
  56674. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56675. * @returns the current particle system
  56676. */
  56677. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56678. if (!this._dragGradients) {
  56679. this._dragGradients = [];
  56680. }
  56681. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56682. return this;
  56683. };
  56684. /**
  56685. * Remove a specific drag gradient
  56686. * @param gradient defines the gradient to remove
  56687. * @returns the current particle system
  56688. */
  56689. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56690. this._removeFactorGradient(this._dragGradients, gradient);
  56691. return this;
  56692. };
  56693. /**
  56694. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56695. * @param gradient defines the gradient to use (between 0 and 1)
  56696. * @param factor defines the emit rate value to affect to the specified gradient
  56697. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56698. * @returns the current particle system
  56699. */
  56700. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56701. if (!this._emitRateGradients) {
  56702. this._emitRateGradients = [];
  56703. }
  56704. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56705. if (!this._currentEmitRateGradient) {
  56706. this._currentEmitRateGradient = this._emitRateGradients[0];
  56707. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56708. this._currentEmitRate2 = this._currentEmitRate1;
  56709. }
  56710. if (this._emitRateGradients.length === 2) {
  56711. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56712. }
  56713. return this;
  56714. };
  56715. /**
  56716. * Remove a specific emit rate gradient
  56717. * @param gradient defines the gradient to remove
  56718. * @returns the current particle system
  56719. */
  56720. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56721. this._removeFactorGradient(this._emitRateGradients, gradient);
  56722. return this;
  56723. };
  56724. /**
  56725. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56726. * @param gradient defines the gradient to use (between 0 and 1)
  56727. * @param factor defines the start size value to affect to the specified gradient
  56728. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56729. * @returns the current particle system
  56730. */
  56731. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56732. if (!this._startSizeGradients) {
  56733. this._startSizeGradients = [];
  56734. }
  56735. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56736. if (!this._currentStartSizeGradient) {
  56737. this._currentStartSizeGradient = this._startSizeGradients[0];
  56738. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56739. this._currentStartSize2 = this._currentStartSize1;
  56740. }
  56741. if (this._startSizeGradients.length === 2) {
  56742. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56743. }
  56744. return this;
  56745. };
  56746. /**
  56747. * Remove a specific start size gradient
  56748. * @param gradient defines the gradient to remove
  56749. * @returns the current particle system
  56750. */
  56751. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56752. this._removeFactorGradient(this._emitRateGradients, gradient);
  56753. return this;
  56754. };
  56755. ParticleSystem.prototype._createRampGradientTexture = function () {
  56756. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  56757. return;
  56758. }
  56759. var data = new Uint8Array(this._rawTextureWidth * 4);
  56760. var tmpColor = BABYLON.Tmp.Color4[0];
  56761. for (var x = 0; x < this._rawTextureWidth; x++) {
  56762. var ratio = x / this._rawTextureWidth;
  56763. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  56764. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  56765. data[x * 4] = tmpColor.r * 255;
  56766. data[x * 4 + 1] = tmpColor.g * 255;
  56767. data[x * 4 + 2] = tmpColor.b * 255;
  56768. data[x * 4 + 3] = tmpColor.a * 255;
  56769. });
  56770. }
  56771. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56772. };
  56773. /**
  56774. * Gets the current list of ramp gradients.
  56775. * You must use addRampGradient and removeRampGradient to udpate this list
  56776. * @returns the list of ramp gradients
  56777. */
  56778. ParticleSystem.prototype.getRampGradients = function () {
  56779. return this._rampGradients;
  56780. };
  56781. /**
  56782. * Adds a new ramp gradient used to remap particle colors
  56783. * @param gradient defines the gradient to use (between 0 and 1)
  56784. * @param color defines the color to affect to the specified gradient
  56785. * @returns the current particle system
  56786. */
  56787. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  56788. if (!this._rampGradients) {
  56789. this._rampGradients = [];
  56790. }
  56791. var rampGradient = new BABYLON.ColorGradient();
  56792. rampGradient.gradient = gradient;
  56793. rampGradient.color1 = color;
  56794. this._rampGradients.push(rampGradient);
  56795. this._rampGradients.sort(function (a, b) {
  56796. if (a.gradient < b.gradient) {
  56797. return -1;
  56798. }
  56799. else if (a.gradient > b.gradient) {
  56800. return 1;
  56801. }
  56802. return 0;
  56803. });
  56804. if (this._rampGradientsTexture) {
  56805. this._rampGradientsTexture.dispose();
  56806. this._rampGradientsTexture = null;
  56807. }
  56808. this._createRampGradientTexture();
  56809. return this;
  56810. };
  56811. /**
  56812. * Remove a specific ramp gradient
  56813. * @param gradient defines the gradient to remove
  56814. * @returns the current particle system
  56815. */
  56816. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  56817. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  56818. this._rampGradientsTexture = null;
  56819. if (this._rampGradients && this._rampGradients.length > 0) {
  56820. this._createRampGradientTexture();
  56821. }
  56822. return this;
  56823. };
  56824. /**
  56825. * Adds a new color gradient
  56826. * @param gradient defines the gradient to use (between 0 and 1)
  56827. * @param color defines the color to affect to the specified gradient
  56828. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56829. */
  56830. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56831. if (!this._colorGradients) {
  56832. this._colorGradients = [];
  56833. }
  56834. var colorGradient = new BABYLON.ColorGradient();
  56835. colorGradient.gradient = gradient;
  56836. colorGradient.color1 = color;
  56837. colorGradient.color2 = color2;
  56838. this._colorGradients.push(colorGradient);
  56839. this._colorGradients.sort(function (a, b) {
  56840. if (a.gradient < b.gradient) {
  56841. return -1;
  56842. }
  56843. else if (a.gradient > b.gradient) {
  56844. return 1;
  56845. }
  56846. return 0;
  56847. });
  56848. return this;
  56849. };
  56850. /**
  56851. * Remove a specific color gradient
  56852. * @param gradient defines the gradient to remove
  56853. */
  56854. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56855. if (!this._colorGradients) {
  56856. return this;
  56857. }
  56858. var index = 0;
  56859. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56860. var colorGradient = _a[_i];
  56861. if (colorGradient.gradient === gradient) {
  56862. this._colorGradients.splice(index, 1);
  56863. break;
  56864. }
  56865. index++;
  56866. }
  56867. return this;
  56868. };
  56869. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56870. u = Math.abs(u) * 0.5 + 0.5;
  56871. v = Math.abs(v) * 0.5 + 0.5;
  56872. var wrappedU = ((u * width) % width) | 0;
  56873. var wrappedV = ((v * height) % height) | 0;
  56874. var position = (wrappedU + wrappedV * width) * 4;
  56875. return pixels[position] / 255;
  56876. };
  56877. ParticleSystem.prototype._reset = function () {
  56878. this._resetEffect();
  56879. };
  56880. ParticleSystem.prototype._resetEffect = function () {
  56881. if (this._vertexBuffer) {
  56882. this._vertexBuffer.dispose();
  56883. this._vertexBuffer = null;
  56884. }
  56885. if (this._spriteBuffer) {
  56886. this._spriteBuffer.dispose();
  56887. this._spriteBuffer = null;
  56888. }
  56889. this._createVertexBuffers();
  56890. };
  56891. ParticleSystem.prototype._createVertexBuffers = function () {
  56892. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56893. if (this._isAnimationSheetEnabled) {
  56894. this._vertexBufferSize += 1;
  56895. }
  56896. if (!this._isBillboardBased) {
  56897. this._vertexBufferSize += 3;
  56898. }
  56899. if (this._useRampGradients) {
  56900. this._vertexBufferSize += 4;
  56901. }
  56902. var engine = this._scene.getEngine();
  56903. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56904. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56905. var dataOffset = 0;
  56906. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56907. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56908. dataOffset += 3;
  56909. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56910. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56911. dataOffset += 4;
  56912. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56913. this._vertexBuffers["angle"] = options;
  56914. dataOffset += 1;
  56915. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56916. this._vertexBuffers["size"] = size;
  56917. dataOffset += 2;
  56918. if (this._isAnimationSheetEnabled) {
  56919. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56920. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56921. dataOffset += 1;
  56922. }
  56923. if (!this._isBillboardBased) {
  56924. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56925. this._vertexBuffers["direction"] = directionBuffer;
  56926. dataOffset += 3;
  56927. }
  56928. if (this._useRampGradients) {
  56929. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56930. this._vertexBuffers["remapData"] = rampDataBuffer;
  56931. dataOffset += 4;
  56932. }
  56933. var offsets;
  56934. if (this._useInstancing) {
  56935. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56936. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56937. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56938. }
  56939. else {
  56940. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56941. dataOffset += 2;
  56942. }
  56943. this._vertexBuffers["offset"] = offsets;
  56944. };
  56945. ParticleSystem.prototype._createIndexBuffer = function () {
  56946. if (this._useInstancing) {
  56947. return;
  56948. }
  56949. var indices = [];
  56950. var index = 0;
  56951. for (var count = 0; count < this._capacity; count++) {
  56952. indices.push(index);
  56953. indices.push(index + 1);
  56954. indices.push(index + 2);
  56955. indices.push(index);
  56956. indices.push(index + 2);
  56957. indices.push(index + 3);
  56958. index += 4;
  56959. }
  56960. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56961. };
  56962. /**
  56963. * Gets the maximum number of particles active at the same time.
  56964. * @returns The max number of active particles.
  56965. */
  56966. ParticleSystem.prototype.getCapacity = function () {
  56967. return this._capacity;
  56968. };
  56969. /**
  56970. * Gets whether there are still active particles in the system.
  56971. * @returns True if it is alive, otherwise false.
  56972. */
  56973. ParticleSystem.prototype.isAlive = function () {
  56974. return this._alive;
  56975. };
  56976. /**
  56977. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56978. * @returns True if it has been started, otherwise false.
  56979. */
  56980. ParticleSystem.prototype.isStarted = function () {
  56981. return this._started;
  56982. };
  56983. /**
  56984. * Starts the particle system and begins to emit
  56985. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56986. */
  56987. ParticleSystem.prototype.start = function (delay) {
  56988. var _this = this;
  56989. if (delay === void 0) { delay = 0; }
  56990. if (delay) {
  56991. setTimeout(function () {
  56992. _this.start(0);
  56993. }, delay);
  56994. return;
  56995. }
  56996. // Convert the subEmitters field to the constant type field _subEmitters
  56997. this._subEmitters = new Array();
  56998. if (this.subEmitters) {
  56999. this.subEmitters.forEach(function (subEmitter) {
  57000. if (subEmitter instanceof ParticleSystem) {
  57001. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  57002. }
  57003. else if (subEmitter instanceof BABYLON.SubEmitter) {
  57004. _this._subEmitters.push([subEmitter]);
  57005. }
  57006. else if (subEmitter instanceof Array) {
  57007. _this._subEmitters.push(subEmitter);
  57008. }
  57009. });
  57010. }
  57011. this._started = true;
  57012. this._stopped = false;
  57013. this._actualFrame = 0;
  57014. if (this._subEmitters && this._subEmitters.length != 0) {
  57015. this.activeSubSystems = new Array();
  57016. }
  57017. if (this.preWarmCycles) {
  57018. for (var index = 0; index < this.preWarmCycles; index++) {
  57019. this.animate(true);
  57020. }
  57021. }
  57022. };
  57023. /**
  57024. * Stops the particle system.
  57025. * @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.
  57026. */
  57027. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  57028. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  57029. this._stopped = true;
  57030. if (stopSubEmitters) {
  57031. this._stopSubEmitters();
  57032. }
  57033. };
  57034. // animation sheet
  57035. /**
  57036. * Remove all active particles
  57037. */
  57038. ParticleSystem.prototype.reset = function () {
  57039. this._stockParticles = [];
  57040. this._particles = [];
  57041. };
  57042. /**
  57043. * @hidden (for internal use only)
  57044. */
  57045. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  57046. var offset = index * this._vertexBufferSize;
  57047. this._vertexData[offset++] = particle.position.x;
  57048. this._vertexData[offset++] = particle.position.y;
  57049. this._vertexData[offset++] = particle.position.z;
  57050. this._vertexData[offset++] = particle.color.r;
  57051. this._vertexData[offset++] = particle.color.g;
  57052. this._vertexData[offset++] = particle.color.b;
  57053. this._vertexData[offset++] = particle.color.a;
  57054. this._vertexData[offset++] = particle.angle;
  57055. this._vertexData[offset++] = particle.scale.x * particle.size;
  57056. this._vertexData[offset++] = particle.scale.y * particle.size;
  57057. if (this._isAnimationSheetEnabled) {
  57058. this._vertexData[offset++] = particle.cellIndex;
  57059. }
  57060. if (!this._isBillboardBased) {
  57061. if (particle._initialDirection) {
  57062. this._vertexData[offset++] = particle._initialDirection.x;
  57063. this._vertexData[offset++] = particle._initialDirection.y;
  57064. this._vertexData[offset++] = particle._initialDirection.z;
  57065. }
  57066. else {
  57067. this._vertexData[offset++] = particle.direction.x;
  57068. this._vertexData[offset++] = particle.direction.y;
  57069. this._vertexData[offset++] = particle.direction.z;
  57070. }
  57071. }
  57072. if (!this._useInstancing) {
  57073. if (this._isAnimationSheetEnabled) {
  57074. if (offsetX === 0)
  57075. offsetX = this._epsilon;
  57076. else if (offsetX === 1)
  57077. offsetX = 1 - this._epsilon;
  57078. if (offsetY === 0)
  57079. offsetY = this._epsilon;
  57080. else if (offsetY === 1)
  57081. offsetY = 1 - this._epsilon;
  57082. }
  57083. this._vertexData[offset++] = offsetX;
  57084. this._vertexData[offset++] = offsetY;
  57085. }
  57086. if (this._useRampGradients) {
  57087. this._vertexData[offset++] = particle.remapData.x;
  57088. this._vertexData[offset++] = particle.remapData.y;
  57089. this._vertexData[offset++] = particle.remapData.z;
  57090. this._vertexData[offset++] = particle.remapData.w;
  57091. }
  57092. };
  57093. ParticleSystem.prototype._stopSubEmitters = function () {
  57094. if (!this.activeSubSystems) {
  57095. return;
  57096. }
  57097. this.activeSubSystems.forEach(function (subSystem) {
  57098. subSystem.stop(true);
  57099. });
  57100. this.activeSubSystems = new Array();
  57101. };
  57102. ParticleSystem.prototype._removeFromRoot = function () {
  57103. if (!this._rootParticleSystem) {
  57104. return;
  57105. }
  57106. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  57107. if (index !== -1) {
  57108. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  57109. }
  57110. };
  57111. // End of sub system methods
  57112. ParticleSystem.prototype._update = function (newParticles) {
  57113. var _this = this;
  57114. // Update current
  57115. this._alive = this._particles.length > 0;
  57116. if (this.emitter.position) {
  57117. var emitterMesh = this.emitter;
  57118. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  57119. }
  57120. else {
  57121. var emitterPosition = this.emitter;
  57122. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57123. }
  57124. this.updateFunction(this._particles);
  57125. // Add new ones
  57126. var particle;
  57127. var _loop_2 = function () {
  57128. if (this_1._particles.length === this_1._capacity) {
  57129. return "break";
  57130. }
  57131. particle = this_1._createParticle();
  57132. this_1._particles.push(particle);
  57133. // Emitter
  57134. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  57135. if (this_1.startPositionFunction) {
  57136. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57137. }
  57138. else {
  57139. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57140. }
  57141. if (this_1.startDirectionFunction) {
  57142. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57143. }
  57144. else {
  57145. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57146. }
  57147. if (emitPower === 0) {
  57148. if (!particle._initialDirection) {
  57149. particle._initialDirection = particle.direction.clone();
  57150. }
  57151. else {
  57152. particle._initialDirection.copyFrom(particle.direction);
  57153. }
  57154. }
  57155. else {
  57156. particle._initialDirection = null;
  57157. }
  57158. particle.direction.scaleInPlace(emitPower);
  57159. // Life time
  57160. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  57161. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  57162. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  57163. var factorGradient1 = currentGradient;
  57164. var factorGradient2 = nextGradient;
  57165. var lifeTime1 = factorGradient1.getFactor();
  57166. var lifeTime2 = factorGradient2.getFactor();
  57167. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  57168. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  57169. });
  57170. }
  57171. else {
  57172. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  57173. }
  57174. // Size
  57175. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  57176. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  57177. }
  57178. else {
  57179. particle._currentSizeGradient = this_1._sizeGradients[0];
  57180. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  57181. particle.size = particle._currentSize1;
  57182. if (this_1._sizeGradients.length > 1) {
  57183. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57184. }
  57185. else {
  57186. particle._currentSize2 = particle._currentSize1;
  57187. }
  57188. }
  57189. // Size and scale
  57190. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57191. // Adjust scale by start size
  57192. if (this_1._startSizeGradients && this_1._startSizeGradients[0]) {
  57193. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57194. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57195. if (currentGradient !== _this._currentStartSizeGradient) {
  57196. _this._currentStartSize1 = _this._currentStartSize2;
  57197. _this._currentStartSize2 = nextGradient.getFactor();
  57198. _this._currentStartSizeGradient = currentGradient;
  57199. }
  57200. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57201. particle.scale.scaleInPlace(value);
  57202. });
  57203. }
  57204. // Angle
  57205. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57206. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57207. }
  57208. else {
  57209. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57210. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57211. particle._currentAngularSpeed1 = particle.angularSpeed;
  57212. if (this_1._angularSpeedGradients.length > 1) {
  57213. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57214. }
  57215. else {
  57216. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57217. }
  57218. }
  57219. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57220. // Velocity
  57221. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57222. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57223. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57224. if (this_1._velocityGradients.length > 1) {
  57225. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57226. }
  57227. else {
  57228. particle._currentVelocity2 = particle._currentVelocity1;
  57229. }
  57230. }
  57231. // Limit velocity
  57232. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57233. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57234. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57235. if (this_1._limitVelocityGradients.length > 1) {
  57236. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57237. }
  57238. else {
  57239. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57240. }
  57241. }
  57242. // Drag
  57243. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57244. particle._currentDragGradient = this_1._dragGradients[0];
  57245. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57246. if (this_1._dragGradients.length > 1) {
  57247. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57248. }
  57249. else {
  57250. particle._currentDrag2 = particle._currentDrag1;
  57251. }
  57252. }
  57253. // Color
  57254. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57255. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57256. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57257. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57258. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57259. }
  57260. else {
  57261. particle._currentColorGradient = this_1._colorGradients[0];
  57262. particle._currentColorGradient.getColorToRef(particle.color);
  57263. particle._currentColor1.copyFrom(particle.color);
  57264. if (this_1._colorGradients.length > 1) {
  57265. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57266. }
  57267. else {
  57268. particle._currentColor2.copyFrom(particle.color);
  57269. }
  57270. }
  57271. // Sheet
  57272. if (this_1._isAnimationSheetEnabled) {
  57273. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57274. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57275. }
  57276. // Inherited Velocity
  57277. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  57278. // Ramp
  57279. if (this_1._useRampGradients) {
  57280. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  57281. }
  57282. };
  57283. var this_1 = this, step;
  57284. for (var index = 0; index < newParticles; index++) {
  57285. var state_1 = _loop_2();
  57286. if (state_1 === "break")
  57287. break;
  57288. }
  57289. };
  57290. /** @hidden */
  57291. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  57292. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57293. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57294. if (useRampGradients === void 0) { useRampGradients = false; }
  57295. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57296. if (isAnimationSheetEnabled) {
  57297. attributeNamesOrOptions.push("cellIndex");
  57298. }
  57299. if (!isBillboardBased) {
  57300. attributeNamesOrOptions.push("direction");
  57301. }
  57302. if (useRampGradients) {
  57303. attributeNamesOrOptions.push("remapData");
  57304. }
  57305. return attributeNamesOrOptions;
  57306. };
  57307. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57308. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57309. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57310. if (isAnimationSheetEnabled) {
  57311. effectCreationOption.push("particlesInfos");
  57312. }
  57313. return effectCreationOption;
  57314. };
  57315. ParticleSystem.prototype._getEffect = function () {
  57316. if (this._customEffect) {
  57317. return this._customEffect;
  57318. }
  57319. ;
  57320. var defines = [];
  57321. if (this._scene.clipPlane) {
  57322. defines.push("#define CLIPPLANE");
  57323. }
  57324. if (this._scene.clipPlane2) {
  57325. defines.push("#define CLIPPLANE2");
  57326. }
  57327. if (this._scene.clipPlane3) {
  57328. defines.push("#define CLIPPLANE3");
  57329. }
  57330. if (this._scene.clipPlane4) {
  57331. defines.push("#define CLIPPLANE4");
  57332. }
  57333. if (this._isAnimationSheetEnabled) {
  57334. defines.push("#define ANIMATESHEET");
  57335. }
  57336. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57337. defines.push("#define BLENDMULTIPLYMODE");
  57338. }
  57339. if (this._useRampGradients) {
  57340. defines.push("#define RAMPGRADIENT");
  57341. }
  57342. if (this._isBillboardBased) {
  57343. defines.push("#define BILLBOARD");
  57344. switch (this.billboardMode) {
  57345. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57346. defines.push("#define BILLBOARDY");
  57347. break;
  57348. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57349. default:
  57350. break;
  57351. }
  57352. }
  57353. if (this._imageProcessingConfiguration) {
  57354. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57355. defines.push(this._imageProcessingConfigurationDefines.toString());
  57356. }
  57357. // Effect
  57358. var join = defines.join("\n");
  57359. if (this._cachedDefines !== join) {
  57360. this._cachedDefines = join;
  57361. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  57362. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57363. var samplers = ["diffuseSampler", "rampSampler"];
  57364. if (BABYLON.ImageProcessingConfiguration) {
  57365. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57366. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57367. }
  57368. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  57369. }
  57370. return this._effect;
  57371. };
  57372. /**
  57373. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57374. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57375. */
  57376. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57377. var _this = this;
  57378. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57379. if (!this._started)
  57380. return;
  57381. if (!preWarmOnly) {
  57382. var effect = this._getEffect();
  57383. // Check
  57384. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  57385. return;
  57386. if (this._currentRenderId === this._scene.getRenderId()) {
  57387. return;
  57388. }
  57389. this._currentRenderId = this._scene.getRenderId();
  57390. }
  57391. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57392. // Determine the number of particles we need to create
  57393. var newParticles;
  57394. if (this.manualEmitCount > -1) {
  57395. newParticles = this.manualEmitCount;
  57396. this._newPartsExcess = 0;
  57397. this.manualEmitCount = 0;
  57398. }
  57399. else {
  57400. var rate_1 = this.emitRate;
  57401. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57402. var ratio = this._actualFrame / this.targetStopDuration;
  57403. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57404. if (currentGradient !== _this._currentEmitRateGradient) {
  57405. _this._currentEmitRate1 = _this._currentEmitRate2;
  57406. _this._currentEmitRate2 = nextGradient.getFactor();
  57407. _this._currentEmitRateGradient = currentGradient;
  57408. }
  57409. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57410. });
  57411. }
  57412. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57413. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57414. }
  57415. if (this._newPartsExcess > 1.0) {
  57416. newParticles += this._newPartsExcess >> 0;
  57417. this._newPartsExcess -= this._newPartsExcess >> 0;
  57418. }
  57419. this._alive = false;
  57420. if (!this._stopped) {
  57421. this._actualFrame += this._scaledUpdateSpeed;
  57422. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57423. this.stop();
  57424. }
  57425. else {
  57426. newParticles = 0;
  57427. }
  57428. this._update(newParticles);
  57429. // Stopped?
  57430. if (this._stopped) {
  57431. if (!this._alive) {
  57432. this._started = false;
  57433. if (this.onAnimationEnd) {
  57434. this.onAnimationEnd();
  57435. }
  57436. if (this.disposeOnStop) {
  57437. this._scene._toBeDisposed.push(this);
  57438. }
  57439. }
  57440. }
  57441. if (!preWarmOnly) {
  57442. // Update VBO
  57443. var offset = 0;
  57444. for (var index = 0; index < this._particles.length; index++) {
  57445. var particle = this._particles[index];
  57446. this._appendParticleVertices(offset, particle);
  57447. offset += this._useInstancing ? 1 : 4;
  57448. }
  57449. if (this._vertexBuffer) {
  57450. this._vertexBuffer.update(this._vertexData);
  57451. }
  57452. }
  57453. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57454. this.stop();
  57455. }
  57456. };
  57457. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57458. this._appendParticleVertex(offset++, particle, 0, 0);
  57459. if (!this._useInstancing) {
  57460. this._appendParticleVertex(offset++, particle, 1, 0);
  57461. this._appendParticleVertex(offset++, particle, 1, 1);
  57462. this._appendParticleVertex(offset++, particle, 0, 1);
  57463. }
  57464. };
  57465. /**
  57466. * Rebuilds the particle system.
  57467. */
  57468. ParticleSystem.prototype.rebuild = function () {
  57469. this._createIndexBuffer();
  57470. if (this._vertexBuffer) {
  57471. this._vertexBuffer._rebuild();
  57472. }
  57473. };
  57474. /**
  57475. * Is this system ready to be used/rendered
  57476. * @return true if the system is ready
  57477. */
  57478. ParticleSystem.prototype.isReady = function () {
  57479. var effect = this._getEffect();
  57480. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57481. return false;
  57482. }
  57483. return true;
  57484. };
  57485. /**
  57486. * Renders the particle system in its current state.
  57487. * @returns the current number of particles
  57488. */
  57489. ParticleSystem.prototype.render = function () {
  57490. var effect = this._getEffect();
  57491. // Check
  57492. if (!this.isReady() || !this._particles.length) {
  57493. return 0;
  57494. }
  57495. var engine = this._scene.getEngine();
  57496. // Render
  57497. engine.enableEffect(effect);
  57498. engine.setState(false);
  57499. var viewMatrix = this._scene.getViewMatrix();
  57500. effect.setTexture("diffuseSampler", this.particleTexture);
  57501. effect.setMatrix("view", viewMatrix);
  57502. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57503. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57504. var baseSize = this.particleTexture.getBaseSize();
  57505. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57506. }
  57507. effect.setVector2("translationPivot", this.translationPivot);
  57508. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57509. if (this._isBillboardBased) {
  57510. var camera = this._scene.activeCamera;
  57511. effect.setVector3("eyePosition", camera.globalPosition);
  57512. }
  57513. if (this._rampGradientsTexture) {
  57514. effect.setTexture("rampSampler", this._rampGradientsTexture);
  57515. }
  57516. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57517. var invView = viewMatrix.clone();
  57518. invView.invert();
  57519. effect.setMatrix("invView", invView);
  57520. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57521. }
  57522. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57523. // image processing
  57524. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57525. this._imageProcessingConfiguration.bind(effect);
  57526. }
  57527. // Draw order
  57528. switch (this.blendMode) {
  57529. case ParticleSystem.BLENDMODE_ADD:
  57530. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57531. break;
  57532. case ParticleSystem.BLENDMODE_ONEONE:
  57533. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57534. break;
  57535. case ParticleSystem.BLENDMODE_STANDARD:
  57536. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57537. break;
  57538. case ParticleSystem.BLENDMODE_MULTIPLY:
  57539. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57540. break;
  57541. }
  57542. if (this.forceDepthWrite) {
  57543. engine.setDepthWrite(true);
  57544. }
  57545. if (this._useInstancing) {
  57546. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57547. engine.unbindInstanceAttributes();
  57548. }
  57549. else {
  57550. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57551. }
  57552. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57553. return this._particles.length;
  57554. };
  57555. /**
  57556. * Disposes the particle system and free the associated resources
  57557. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57558. */
  57559. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57560. if (disposeTexture === void 0) { disposeTexture = true; }
  57561. if (this._vertexBuffer) {
  57562. this._vertexBuffer.dispose();
  57563. this._vertexBuffer = null;
  57564. }
  57565. if (this._spriteBuffer) {
  57566. this._spriteBuffer.dispose();
  57567. this._spriteBuffer = null;
  57568. }
  57569. if (this._indexBuffer) {
  57570. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57571. this._indexBuffer = null;
  57572. }
  57573. if (disposeTexture && this.particleTexture) {
  57574. this.particleTexture.dispose();
  57575. this.particleTexture = null;
  57576. }
  57577. if (disposeTexture && this.noiseTexture) {
  57578. this.noiseTexture.dispose();
  57579. this.noiseTexture = null;
  57580. }
  57581. this._removeFromRoot();
  57582. if (this._disposeEmitterOnDispose && !this.emitter.isDisposed) {
  57583. this.emitter.dispose();
  57584. }
  57585. // Remove from scene
  57586. var index = this._scene.particleSystems.indexOf(this);
  57587. if (index > -1) {
  57588. this._scene.particleSystems.splice(index, 1);
  57589. }
  57590. // Callback
  57591. this.onDisposeObservable.notifyObservers(this);
  57592. this.onDisposeObservable.clear();
  57593. };
  57594. // Clone
  57595. /**
  57596. * Clones the particle system.
  57597. * @param name The name of the cloned object
  57598. * @param newEmitter The new emitter to use
  57599. * @returns the cloned particle system
  57600. */
  57601. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57602. var custom = null;
  57603. var program = null;
  57604. if (this.customShader != null) {
  57605. program = this.customShader;
  57606. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57607. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57608. }
  57609. else if (this._customEffect) {
  57610. custom = this._customEffect;
  57611. }
  57612. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57613. result.customShader = program;
  57614. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57615. if (newEmitter === undefined) {
  57616. newEmitter = this.emitter;
  57617. }
  57618. result.emitter = newEmitter;
  57619. if (this.particleTexture) {
  57620. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57621. }
  57622. // Clone gradients
  57623. if (this._colorGradients) {
  57624. this._colorGradients.forEach(function (v) {
  57625. result.addColorGradient(v.gradient, v.color1, v.color2);
  57626. });
  57627. }
  57628. if (this._dragGradients) {
  57629. this._dragGradients.forEach(function (v) {
  57630. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  57631. });
  57632. }
  57633. if (this._angularSpeedGradients) {
  57634. this._angularSpeedGradients.forEach(function (v) {
  57635. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  57636. });
  57637. }
  57638. if (this._emitRateGradients) {
  57639. this._emitRateGradients.forEach(function (v) {
  57640. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  57641. });
  57642. }
  57643. if (this._lifeTimeGradients) {
  57644. this._lifeTimeGradients.forEach(function (v) {
  57645. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  57646. });
  57647. }
  57648. if (this._limitVelocityGradients) {
  57649. this._limitVelocityGradients.forEach(function (v) {
  57650. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  57651. });
  57652. }
  57653. if (this._sizeGradients) {
  57654. this._sizeGradients.forEach(function (v) {
  57655. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  57656. });
  57657. }
  57658. if (this._startSizeGradients) {
  57659. this._startSizeGradients.forEach(function (v) {
  57660. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  57661. });
  57662. }
  57663. if (this._velocityGradients) {
  57664. this._velocityGradients.forEach(function (v) {
  57665. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  57666. });
  57667. }
  57668. if (this._rampGradients) {
  57669. this._rampGradients.forEach(function (v) {
  57670. result.addRampGradient(v.gradient, v.color1);
  57671. });
  57672. }
  57673. if (this._colorRemapGradients) {
  57674. this._colorRemapGradients.forEach(function (v) {
  57675. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  57676. });
  57677. }
  57678. if (this._alphaRemapGradients) {
  57679. this._alphaRemapGradients.forEach(function (v) {
  57680. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  57681. });
  57682. }
  57683. if (!this.preventAutoStart) {
  57684. result.start();
  57685. }
  57686. return result;
  57687. };
  57688. /**
  57689. * Serializes the particle system to a JSON object.
  57690. * @returns the JSON object
  57691. */
  57692. ParticleSystem.prototype.serialize = function () {
  57693. var serializationObject = {};
  57694. ParticleSystem._Serialize(serializationObject, this);
  57695. serializationObject.textureMask = this.textureMask.asArray();
  57696. serializationObject.customShader = this.customShader;
  57697. serializationObject.preventAutoStart = this.preventAutoStart;
  57698. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57699. return serializationObject;
  57700. };
  57701. /** @hidden */
  57702. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57703. serializationObject.name = particleSystem.name;
  57704. serializationObject.id = particleSystem.id;
  57705. serializationObject.capacity = particleSystem.getCapacity();
  57706. // Emitter
  57707. if (particleSystem.emitter.position) {
  57708. var emitterMesh = particleSystem.emitter;
  57709. serializationObject.emitterId = emitterMesh.id;
  57710. }
  57711. else {
  57712. var emitterPosition = particleSystem.emitter;
  57713. serializationObject.emitter = emitterPosition.asArray();
  57714. }
  57715. // Emitter
  57716. if (particleSystem.particleEmitterType) {
  57717. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57718. }
  57719. if (particleSystem.particleTexture) {
  57720. serializationObject.textureName = particleSystem.particleTexture.name;
  57721. }
  57722. // Animations
  57723. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57724. // Particle system
  57725. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57726. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57727. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57728. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57729. serializationObject.minSize = particleSystem.minSize;
  57730. serializationObject.maxSize = particleSystem.maxSize;
  57731. serializationObject.minScaleX = particleSystem.minScaleX;
  57732. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57733. serializationObject.minScaleY = particleSystem.minScaleY;
  57734. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57735. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57736. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57737. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57738. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57739. serializationObject.emitRate = particleSystem.emitRate;
  57740. serializationObject.gravity = particleSystem.gravity.asArray();
  57741. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57742. serializationObject.color1 = particleSystem.color1.asArray();
  57743. serializationObject.color2 = particleSystem.color2.asArray();
  57744. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57745. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57746. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57747. serializationObject.blendMode = particleSystem.blendMode;
  57748. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57749. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57750. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57751. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57752. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57753. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57754. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57755. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57756. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57757. var colorGradients = particleSystem.getColorGradients();
  57758. if (colorGradients) {
  57759. serializationObject.colorGradients = [];
  57760. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57761. var colorGradient = colorGradients_1[_i];
  57762. var serializedGradient = {
  57763. gradient: colorGradient.gradient,
  57764. color1: colorGradient.color1.asArray()
  57765. };
  57766. if (colorGradient.color2) {
  57767. serializedGradient.color2 = colorGradient.color2.asArray();
  57768. }
  57769. serializationObject.colorGradients.push(serializedGradient);
  57770. }
  57771. }
  57772. var rampGradients = particleSystem.getRampGradients();
  57773. if (rampGradients) {
  57774. serializationObject.rampGradients = [];
  57775. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  57776. var rampGradient = rampGradients_1[_a];
  57777. var serializedGradient = {
  57778. gradient: rampGradient.gradient,
  57779. color1: rampGradient.color1.asArray()
  57780. };
  57781. serializationObject.rampGradients.push(serializedGradient);
  57782. }
  57783. }
  57784. var colorRemapGradients = particleSystem.getColorRemapGradients();
  57785. if (colorRemapGradients) {
  57786. serializationObject.colorRemapGradients = [];
  57787. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  57788. var colorRemapGradient = colorRemapGradients_1[_b];
  57789. var serializedGradient = {
  57790. gradient: colorRemapGradient.gradient,
  57791. factor1: colorRemapGradient.factor1
  57792. };
  57793. if (colorRemapGradient.factor2 !== undefined) {
  57794. serializedGradient.factor2 = colorRemapGradient.factor2;
  57795. }
  57796. serializationObject.colorRemapGradients.push(serializedGradient);
  57797. }
  57798. }
  57799. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  57800. if (alphaRemapGradients) {
  57801. serializationObject.alphaRemapGradients = [];
  57802. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  57803. var alphaRemapGradient = alphaRemapGradients_1[_c];
  57804. var serializedGradient = {
  57805. gradient: alphaRemapGradient.gradient,
  57806. factor1: alphaRemapGradient.factor1
  57807. };
  57808. if (alphaRemapGradient.factor2 !== undefined) {
  57809. serializedGradient.factor2 = alphaRemapGradient.factor2;
  57810. }
  57811. serializationObject.alphaRemapGradients.push(serializedGradient);
  57812. }
  57813. }
  57814. var sizeGradients = particleSystem.getSizeGradients();
  57815. if (sizeGradients) {
  57816. serializationObject.sizeGradients = [];
  57817. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  57818. var sizeGradient = sizeGradients_1[_d];
  57819. var serializedGradient = {
  57820. gradient: sizeGradient.gradient,
  57821. factor1: sizeGradient.factor1
  57822. };
  57823. if (sizeGradient.factor2 !== undefined) {
  57824. serializedGradient.factor2 = sizeGradient.factor2;
  57825. }
  57826. serializationObject.sizeGradients.push(serializedGradient);
  57827. }
  57828. }
  57829. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57830. if (angularSpeedGradients) {
  57831. serializationObject.angularSpeedGradients = [];
  57832. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  57833. var angularSpeedGradient = angularSpeedGradients_1[_e];
  57834. var serializedGradient = {
  57835. gradient: angularSpeedGradient.gradient,
  57836. factor1: angularSpeedGradient.factor1
  57837. };
  57838. if (angularSpeedGradient.factor2 !== undefined) {
  57839. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57840. }
  57841. serializationObject.angularSpeedGradients.push(serializedGradient);
  57842. }
  57843. }
  57844. var velocityGradients = particleSystem.getVelocityGradients();
  57845. if (velocityGradients) {
  57846. serializationObject.velocityGradients = [];
  57847. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  57848. var velocityGradient = velocityGradients_1[_f];
  57849. var serializedGradient = {
  57850. gradient: velocityGradient.gradient,
  57851. factor1: velocityGradient.factor1
  57852. };
  57853. if (velocityGradient.factor2 !== undefined) {
  57854. serializedGradient.factor2 = velocityGradient.factor2;
  57855. }
  57856. serializationObject.velocityGradients.push(serializedGradient);
  57857. }
  57858. }
  57859. var dragGradients = particleSystem.getDragGradients();
  57860. if (dragGradients) {
  57861. serializationObject.dragyGradients = [];
  57862. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  57863. var dragGradient = dragGradients_1[_g];
  57864. var serializedGradient = {
  57865. gradient: dragGradient.gradient,
  57866. factor1: dragGradient.factor1
  57867. };
  57868. if (dragGradient.factor2 !== undefined) {
  57869. serializedGradient.factor2 = dragGradient.factor2;
  57870. }
  57871. serializationObject.dragGradients.push(serializedGradient);
  57872. }
  57873. }
  57874. var emitRateGradients = particleSystem.getEmitRateGradients();
  57875. if (emitRateGradients) {
  57876. serializationObject.emitRateGradients = [];
  57877. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  57878. var emitRateGradient = emitRateGradients_1[_h];
  57879. var serializedGradient = {
  57880. gradient: emitRateGradient.gradient,
  57881. factor1: emitRateGradient.factor1
  57882. };
  57883. if (emitRateGradient.factor2 !== undefined) {
  57884. serializedGradient.factor2 = emitRateGradient.factor2;
  57885. }
  57886. serializationObject.emitRateGradients.push(serializedGradient);
  57887. }
  57888. }
  57889. var startSizeGradients = particleSystem.getStartSizeGradients();
  57890. if (startSizeGradients) {
  57891. serializationObject.startSizeGradients = [];
  57892. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  57893. var startSizeGradient = startSizeGradients_1[_j];
  57894. var serializedGradient = {
  57895. gradient: startSizeGradient.gradient,
  57896. factor1: startSizeGradient.factor1
  57897. };
  57898. if (startSizeGradient.factor2 !== undefined) {
  57899. serializedGradient.factor2 = startSizeGradient.factor2;
  57900. }
  57901. serializationObject.startSizeGradients.push(serializedGradient);
  57902. }
  57903. }
  57904. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57905. if (limitVelocityGradients) {
  57906. serializationObject.limitVelocityGradients = [];
  57907. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  57908. var limitVelocityGradient = limitVelocityGradients_1[_k];
  57909. var serializedGradient = {
  57910. gradient: limitVelocityGradient.gradient,
  57911. factor1: limitVelocityGradient.factor1
  57912. };
  57913. if (limitVelocityGradient.factor2 !== undefined) {
  57914. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57915. }
  57916. serializationObject.limitVelocityGradients.push(serializedGradient);
  57917. }
  57918. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57919. }
  57920. if (BABYLON.ProceduralTexture && particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57921. var noiseTexture = particleSystem.noiseTexture;
  57922. serializationObject.noiseTexture = noiseTexture.serialize();
  57923. }
  57924. };
  57925. /** @hidden */
  57926. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57927. // Texture
  57928. if (parsedParticleSystem.textureName) {
  57929. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57930. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57931. }
  57932. // Emitter
  57933. if (parsedParticleSystem.emitterId === undefined) {
  57934. particleSystem.emitter = BABYLON.Vector3.Zero();
  57935. }
  57936. else if (parsedParticleSystem.emitterId) {
  57937. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57938. }
  57939. else {
  57940. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57941. }
  57942. // Misc.
  57943. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57944. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57945. }
  57946. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57947. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57948. }
  57949. // Animations
  57950. if (parsedParticleSystem.animations) {
  57951. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57952. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57953. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57954. }
  57955. }
  57956. if (parsedParticleSystem.autoAnimate) {
  57957. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57958. }
  57959. // Particle system
  57960. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57961. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57962. particleSystem.minSize = parsedParticleSystem.minSize;
  57963. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57964. if (parsedParticleSystem.minScaleX) {
  57965. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57966. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57967. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57968. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57969. }
  57970. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57971. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57972. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57973. }
  57974. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57975. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57976. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57977. }
  57978. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57979. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57980. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57981. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57982. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57983. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57984. if (parsedParticleSystem.noiseStrength) {
  57985. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57986. }
  57987. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57988. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57989. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57990. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57991. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57992. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57993. if (parsedParticleSystem.colorGradients) {
  57994. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57995. var colorGradient = _a[_i];
  57996. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57997. }
  57998. }
  57999. if (parsedParticleSystem.rampGradients) {
  58000. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  58001. var rampGradient = _c[_b];
  58002. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color4.FromArray(rampGradient.color1));
  58003. }
  58004. }
  58005. if (parsedParticleSystem.colorRemapGradients) {
  58006. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  58007. var colorRemapGradient = _e[_d];
  58008. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  58009. }
  58010. }
  58011. if (parsedParticleSystem.alphaRemapGradients) {
  58012. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  58013. var alphaRemapGradient = _g[_f];
  58014. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  58015. }
  58016. }
  58017. if (parsedParticleSystem.sizeGradients) {
  58018. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  58019. var sizeGradient = _j[_h];
  58020. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58021. }
  58022. }
  58023. if (parsedParticleSystem.sizeGradients) {
  58024. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  58025. var sizeGradient = _l[_k];
  58026. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58027. }
  58028. }
  58029. if (parsedParticleSystem.angularSpeedGradients) {
  58030. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  58031. var angularSpeedGradient = _o[_m];
  58032. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  58033. }
  58034. }
  58035. if (parsedParticleSystem.velocityGradients) {
  58036. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  58037. var velocityGradient = _q[_p];
  58038. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  58039. }
  58040. }
  58041. if (parsedParticleSystem.dragGradients) {
  58042. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  58043. var dragGradient = _s[_r];
  58044. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  58045. }
  58046. }
  58047. if (parsedParticleSystem.emitRateGradients) {
  58048. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  58049. var emitRateGradient = _u[_t];
  58050. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  58051. }
  58052. }
  58053. if (parsedParticleSystem.startSizeGradients) {
  58054. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  58055. var startSizeGradient = _w[_v];
  58056. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  58057. }
  58058. }
  58059. if (parsedParticleSystem.limitVelocityGradients) {
  58060. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  58061. var limitVelocityGradient = _y[_x];
  58062. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  58063. }
  58064. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  58065. }
  58066. if (parsedParticleSystem.noiseTexture) {
  58067. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  58068. }
  58069. // Emitter
  58070. var emitterType;
  58071. if (parsedParticleSystem.particleEmitterType) {
  58072. switch (parsedParticleSystem.particleEmitterType.type) {
  58073. case "SphereParticleEmitter":
  58074. emitterType = new BABYLON.SphereParticleEmitter();
  58075. break;
  58076. case "SphereDirectedParticleEmitter":
  58077. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58078. break;
  58079. case "ConeEmitter":
  58080. case "ConeParticleEmitter":
  58081. emitterType = new BABYLON.ConeParticleEmitter();
  58082. break;
  58083. case "BoxEmitter":
  58084. case "BoxParticleEmitter":
  58085. default:
  58086. emitterType = new BABYLON.BoxParticleEmitter();
  58087. break;
  58088. }
  58089. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58090. }
  58091. else {
  58092. emitterType = new BABYLON.BoxParticleEmitter();
  58093. emitterType.parse(parsedParticleSystem);
  58094. }
  58095. particleSystem.particleEmitterType = emitterType;
  58096. // Animation sheet
  58097. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  58098. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  58099. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  58100. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  58101. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  58102. };
  58103. /**
  58104. * Parses a JSON object to create a particle system.
  58105. * @param parsedParticleSystem The JSON object to parse
  58106. * @param scene The scene to create the particle system in
  58107. * @param rootUrl The root url to use to load external dependencies like texture
  58108. * @returns the Parsed particle system
  58109. */
  58110. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58111. var name = parsedParticleSystem.name;
  58112. var custom = null;
  58113. var program = null;
  58114. if (parsedParticleSystem.customShader) {
  58115. program = parsedParticleSystem.customShader;
  58116. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58117. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58118. }
  58119. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  58120. particleSystem.customShader = program;
  58121. if (parsedParticleSystem.id) {
  58122. particleSystem.id = parsedParticleSystem.id;
  58123. }
  58124. // Auto start
  58125. if (parsedParticleSystem.preventAutoStart) {
  58126. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  58127. }
  58128. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58129. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  58130. if (!particleSystem.preventAutoStart) {
  58131. particleSystem.start();
  58132. }
  58133. return particleSystem;
  58134. };
  58135. return ParticleSystem;
  58136. }(BABYLON.BaseParticleSystem));
  58137. BABYLON.ParticleSystem = ParticleSystem;
  58138. })(BABYLON || (BABYLON = {}));
  58139. //# sourceMappingURL=babylon.particleSystem.js.map
  58140. var BABYLON;
  58141. (function (BABYLON) {
  58142. /**
  58143. * Particle emitter emitting particles from the inside of a box.
  58144. * It emits the particles randomly between 2 given directions.
  58145. */
  58146. var BoxParticleEmitter = /** @class */ (function () {
  58147. /**
  58148. * Creates a new instance BoxParticleEmitter
  58149. */
  58150. function BoxParticleEmitter() {
  58151. /**
  58152. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58153. */
  58154. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58155. /**
  58156. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58157. */
  58158. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58159. /**
  58160. * 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.
  58161. */
  58162. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  58163. /**
  58164. * 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.
  58165. */
  58166. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  58167. }
  58168. /**
  58169. * Called by the particle System when the direction is computed for the created particle.
  58170. * @param worldMatrix is the world matrix of the particle system
  58171. * @param directionToUpdate is the direction vector to update with the result
  58172. * @param particle is the particle we are computed the direction for
  58173. */
  58174. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58175. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58176. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58177. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58178. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58179. };
  58180. /**
  58181. * Called by the particle System when the position is computed for the created particle.
  58182. * @param worldMatrix is the world matrix of the particle system
  58183. * @param positionToUpdate is the position vector to update with the result
  58184. * @param particle is the particle we are computed the position for
  58185. */
  58186. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58187. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  58188. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  58189. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  58190. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58191. };
  58192. /**
  58193. * Clones the current emitter and returns a copy of it
  58194. * @returns the new emitter
  58195. */
  58196. BoxParticleEmitter.prototype.clone = function () {
  58197. var newOne = new BoxParticleEmitter();
  58198. BABYLON.Tools.DeepCopy(this, newOne);
  58199. return newOne;
  58200. };
  58201. /**
  58202. * Called by the GPUParticleSystem to setup the update shader
  58203. * @param effect defines the update shader
  58204. */
  58205. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  58206. effect.setVector3("direction1", this.direction1);
  58207. effect.setVector3("direction2", this.direction2);
  58208. effect.setVector3("minEmitBox", this.minEmitBox);
  58209. effect.setVector3("maxEmitBox", this.maxEmitBox);
  58210. };
  58211. /**
  58212. * Returns a string to use to update the GPU particles update shader
  58213. * @returns a string containng the defines string
  58214. */
  58215. BoxParticleEmitter.prototype.getEffectDefines = function () {
  58216. return "#define BOXEMITTER";
  58217. };
  58218. /**
  58219. * Returns the string "BoxParticleEmitter"
  58220. * @returns a string containing the class name
  58221. */
  58222. BoxParticleEmitter.prototype.getClassName = function () {
  58223. return "BoxParticleEmitter";
  58224. };
  58225. /**
  58226. * Serializes the particle system to a JSON object.
  58227. * @returns the JSON object
  58228. */
  58229. BoxParticleEmitter.prototype.serialize = function () {
  58230. var serializationObject = {};
  58231. serializationObject.type = this.getClassName();
  58232. serializationObject.direction1 = this.direction1.asArray();
  58233. serializationObject.direction2 = this.direction2.asArray();
  58234. serializationObject.minEmitBox = this.minEmitBox.asArray();
  58235. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  58236. return serializationObject;
  58237. };
  58238. /**
  58239. * Parse properties from a JSON object
  58240. * @param serializationObject defines the JSON object
  58241. */
  58242. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  58243. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58244. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58245. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  58246. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  58247. };
  58248. return BoxParticleEmitter;
  58249. }());
  58250. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  58251. })(BABYLON || (BABYLON = {}));
  58252. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  58253. var BABYLON;
  58254. (function (BABYLON) {
  58255. /**
  58256. * Particle emitter emitting particles from the inside of a cylinder.
  58257. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  58258. */
  58259. var CylinderParticleEmitter = /** @class */ (function () {
  58260. /**
  58261. * Creates a new instance CylinderParticleEmitter
  58262. * @param radius the radius of the emission cylinder (1 by default)
  58263. * @param height the height of the emission cylinder (1 by default)
  58264. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58265. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58266. */
  58267. function CylinderParticleEmitter(
  58268. /**
  58269. * The radius of the emission cylinder.
  58270. */
  58271. radius,
  58272. /**
  58273. * The height of the emission cylinder.
  58274. */
  58275. height,
  58276. /**
  58277. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58278. */
  58279. radiusRange,
  58280. /**
  58281. * How much to randomize the particle direction [0-1].
  58282. */
  58283. directionRandomizer) {
  58284. if (radius === void 0) { radius = 1; }
  58285. if (height === void 0) { height = 1; }
  58286. if (radiusRange === void 0) { radiusRange = 1; }
  58287. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58288. this.radius = radius;
  58289. this.height = height;
  58290. this.radiusRange = radiusRange;
  58291. this.directionRandomizer = directionRandomizer;
  58292. }
  58293. /**
  58294. * Called by the particle System when the direction is computed for the created particle.
  58295. * @param worldMatrix is the world matrix of the particle system
  58296. * @param directionToUpdate is the direction vector to update with the result
  58297. * @param particle is the particle we are computed the direction for
  58298. */
  58299. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58300. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58301. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  58302. var angle = Math.atan2(direction.x, direction.z);
  58303. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58304. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58305. direction.x = Math.sin(angle);
  58306. direction.z = Math.cos(angle);
  58307. direction.normalize();
  58308. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58309. };
  58310. /**
  58311. * Called by the particle System when the position is computed for the created particle.
  58312. * @param worldMatrix is the world matrix of the particle system
  58313. * @param positionToUpdate is the position vector to update with the result
  58314. * @param particle is the particle we are computed the position for
  58315. */
  58316. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58317. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58318. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58319. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58320. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58321. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58322. var xPos = positionRadius * Math.cos(angle);
  58323. var zPos = positionRadius * Math.sin(angle);
  58324. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58325. };
  58326. /**
  58327. * Clones the current emitter and returns a copy of it
  58328. * @returns the new emitter
  58329. */
  58330. CylinderParticleEmitter.prototype.clone = function () {
  58331. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58332. BABYLON.Tools.DeepCopy(this, newOne);
  58333. return newOne;
  58334. };
  58335. /**
  58336. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58337. * @param effect defines the update shader
  58338. */
  58339. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58340. effect.setFloat("radius", this.radius);
  58341. effect.setFloat("height", this.height);
  58342. effect.setFloat("radiusRange", this.radiusRange);
  58343. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58344. };
  58345. /**
  58346. * Returns a string to use to update the GPU particles update shader
  58347. * @returns a string containng the defines string
  58348. */
  58349. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58350. return "#define CYLINDEREMITTER";
  58351. };
  58352. /**
  58353. * Returns the string "CylinderParticleEmitter"
  58354. * @returns a string containing the class name
  58355. */
  58356. CylinderParticleEmitter.prototype.getClassName = function () {
  58357. return "CylinderParticleEmitter";
  58358. };
  58359. /**
  58360. * Serializes the particle system to a JSON object.
  58361. * @returns the JSON object
  58362. */
  58363. CylinderParticleEmitter.prototype.serialize = function () {
  58364. var serializationObject = {};
  58365. serializationObject.type = this.getClassName();
  58366. serializationObject.radius = this.radius;
  58367. serializationObject.height = this.height;
  58368. serializationObject.radiusRange = this.radiusRange;
  58369. serializationObject.directionRandomizer = this.directionRandomizer;
  58370. return serializationObject;
  58371. };
  58372. /**
  58373. * Parse properties from a JSON object
  58374. * @param serializationObject defines the JSON object
  58375. */
  58376. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58377. this.radius = serializationObject.radius;
  58378. this.height = serializationObject.height;
  58379. this.radiusRange = serializationObject.radiusRange;
  58380. this.directionRandomizer = serializationObject.directionRandomizer;
  58381. };
  58382. return CylinderParticleEmitter;
  58383. }());
  58384. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58385. /**
  58386. * Particle emitter emitting particles from the inside of a cylinder.
  58387. * It emits the particles randomly between two vectors.
  58388. */
  58389. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58390. __extends(CylinderDirectedParticleEmitter, _super);
  58391. /**
  58392. * Creates a new instance CylinderDirectedParticleEmitter
  58393. * @param radius the radius of the emission cylinder (1 by default)
  58394. * @param height the height of the emission cylinder (1 by default)
  58395. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58396. * @param direction1 the min limit of the emission direction (up vector by default)
  58397. * @param direction2 the max limit of the emission direction (up vector by default)
  58398. */
  58399. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58400. /**
  58401. * The min limit of the emission direction.
  58402. */
  58403. direction1,
  58404. /**
  58405. * The max limit of the emission direction.
  58406. */
  58407. direction2) {
  58408. if (radius === void 0) { radius = 1; }
  58409. if (height === void 0) { height = 1; }
  58410. if (radiusRange === void 0) { radiusRange = 1; }
  58411. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58412. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58413. var _this = _super.call(this, radius, height, radiusRange) || this;
  58414. _this.direction1 = direction1;
  58415. _this.direction2 = direction2;
  58416. return _this;
  58417. }
  58418. /**
  58419. * Called by the particle System when the direction is computed for the created particle.
  58420. * @param worldMatrix is the world matrix of the particle system
  58421. * @param directionToUpdate is the direction vector to update with the result
  58422. * @param particle is the particle we are computed the direction for
  58423. */
  58424. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58425. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58426. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58427. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58428. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58429. };
  58430. /**
  58431. * Clones the current emitter and returns a copy of it
  58432. * @returns the new emitter
  58433. */
  58434. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58435. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58436. BABYLON.Tools.DeepCopy(this, newOne);
  58437. return newOne;
  58438. };
  58439. /**
  58440. * Called by the GPUParticleSystem to setup the update shader
  58441. * @param effect defines the update shader
  58442. */
  58443. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58444. effect.setFloat("radius", this.radius);
  58445. effect.setFloat("height", this.height);
  58446. effect.setFloat("radiusRange", this.radiusRange);
  58447. effect.setVector3("direction1", this.direction1);
  58448. effect.setVector3("direction2", this.direction2);
  58449. };
  58450. /**
  58451. * Returns a string to use to update the GPU particles update shader
  58452. * @returns a string containng the defines string
  58453. */
  58454. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58455. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58456. };
  58457. /**
  58458. * Returns the string "CylinderDirectedParticleEmitter"
  58459. * @returns a string containing the class name
  58460. */
  58461. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58462. return "CylinderDirectedParticleEmitter";
  58463. };
  58464. /**
  58465. * Serializes the particle system to a JSON object.
  58466. * @returns the JSON object
  58467. */
  58468. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58469. var serializationObject = _super.prototype.serialize.call(this);
  58470. serializationObject.direction1 = this.direction1.asArray();
  58471. serializationObject.direction2 = this.direction2.asArray();
  58472. return serializationObject;
  58473. };
  58474. /**
  58475. * Parse properties from a JSON object
  58476. * @param serializationObject defines the JSON object
  58477. */
  58478. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58479. _super.prototype.parse.call(this, serializationObject);
  58480. this.direction1.copyFrom(serializationObject.direction1);
  58481. this.direction2.copyFrom(serializationObject.direction2);
  58482. };
  58483. return CylinderDirectedParticleEmitter;
  58484. }(CylinderParticleEmitter));
  58485. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58486. })(BABYLON || (BABYLON = {}));
  58487. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58488. var BABYLON;
  58489. (function (BABYLON) {
  58490. /**
  58491. * Particle emitter emitting particles from the inside of a cone.
  58492. * It emits the particles alongside the cone volume from the base to the particle.
  58493. * The emission direction might be randomized.
  58494. */
  58495. var ConeParticleEmitter = /** @class */ (function () {
  58496. /**
  58497. * Creates a new instance ConeParticleEmitter
  58498. * @param radius the radius of the emission cone (1 by default)
  58499. * @param angles the cone base angle (PI by default)
  58500. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58501. */
  58502. function ConeParticleEmitter(radius, angle,
  58503. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58504. directionRandomizer) {
  58505. if (radius === void 0) { radius = 1; }
  58506. if (angle === void 0) { angle = Math.PI; }
  58507. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58508. this.directionRandomizer = directionRandomizer;
  58509. /**
  58510. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58511. */
  58512. this.radiusRange = 1;
  58513. /**
  58514. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58515. */
  58516. this.heightRange = 1;
  58517. /**
  58518. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58519. */
  58520. this.emitFromSpawnPointOnly = false;
  58521. this.angle = angle;
  58522. this.radius = radius;
  58523. }
  58524. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58525. /**
  58526. * Gets or sets the radius of the emission cone
  58527. */
  58528. get: function () {
  58529. return this._radius;
  58530. },
  58531. set: function (value) {
  58532. this._radius = value;
  58533. this._buildHeight();
  58534. },
  58535. enumerable: true,
  58536. configurable: true
  58537. });
  58538. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58539. /**
  58540. * Gets or sets the angle of the emission cone
  58541. */
  58542. get: function () {
  58543. return this._angle;
  58544. },
  58545. set: function (value) {
  58546. this._angle = value;
  58547. this._buildHeight();
  58548. },
  58549. enumerable: true,
  58550. configurable: true
  58551. });
  58552. ConeParticleEmitter.prototype._buildHeight = function () {
  58553. if (this._angle !== 0) {
  58554. this._height = this._radius / Math.tan(this._angle / 2);
  58555. }
  58556. else {
  58557. this._height = 1;
  58558. }
  58559. };
  58560. /**
  58561. * Called by the particle System when the direction is computed for the created particle.
  58562. * @param worldMatrix is the world matrix of the particle system
  58563. * @param directionToUpdate is the direction vector to update with the result
  58564. * @param particle is the particle we are computed the direction for
  58565. */
  58566. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58567. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58568. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58569. }
  58570. else {
  58571. // measure the direction Vector from the emitter to the particle.
  58572. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58573. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58574. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58575. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58576. direction.x += randX;
  58577. direction.y += randY;
  58578. direction.z += randZ;
  58579. direction.normalize();
  58580. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58581. }
  58582. };
  58583. /**
  58584. * Called by the particle System when the position is computed for the created particle.
  58585. * @param worldMatrix is the world matrix of the particle system
  58586. * @param positionToUpdate is the position vector to update with the result
  58587. * @param particle is the particle we are computed the position for
  58588. */
  58589. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58590. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58591. var h;
  58592. if (!this.emitFromSpawnPointOnly) {
  58593. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58594. // Better distribution in a cone at normal angles.
  58595. h = 1 - h * h;
  58596. }
  58597. else {
  58598. h = 0.0001;
  58599. }
  58600. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58601. radius = radius * h;
  58602. var randX = radius * Math.sin(s);
  58603. var randZ = radius * Math.cos(s);
  58604. var randY = h * this._height;
  58605. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58606. };
  58607. /**
  58608. * Clones the current emitter and returns a copy of it
  58609. * @returns the new emitter
  58610. */
  58611. ConeParticleEmitter.prototype.clone = function () {
  58612. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58613. BABYLON.Tools.DeepCopy(this, newOne);
  58614. return newOne;
  58615. };
  58616. /**
  58617. * Called by the GPUParticleSystem to setup the update shader
  58618. * @param effect defines the update shader
  58619. */
  58620. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58621. effect.setFloat2("radius", this._radius, this.radiusRange);
  58622. effect.setFloat("coneAngle", this._angle);
  58623. effect.setFloat2("height", this._height, this.heightRange);
  58624. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58625. };
  58626. /**
  58627. * Returns a string to use to update the GPU particles update shader
  58628. * @returns a string containng the defines string
  58629. */
  58630. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58631. var defines = "#define CONEEMITTER";
  58632. if (this.emitFromSpawnPointOnly) {
  58633. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58634. }
  58635. return defines;
  58636. };
  58637. /**
  58638. * Returns the string "ConeParticleEmitter"
  58639. * @returns a string containing the class name
  58640. */
  58641. ConeParticleEmitter.prototype.getClassName = function () {
  58642. return "ConeParticleEmitter";
  58643. };
  58644. /**
  58645. * Serializes the particle system to a JSON object.
  58646. * @returns the JSON object
  58647. */
  58648. ConeParticleEmitter.prototype.serialize = function () {
  58649. var serializationObject = {};
  58650. serializationObject.type = this.getClassName();
  58651. serializationObject.radius = this._radius;
  58652. serializationObject.angle = this._angle;
  58653. serializationObject.directionRandomizer = this.directionRandomizer;
  58654. return serializationObject;
  58655. };
  58656. /**
  58657. * Parse properties from a JSON object
  58658. * @param serializationObject defines the JSON object
  58659. */
  58660. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58661. this.radius = serializationObject.radius;
  58662. this.angle = serializationObject.angle;
  58663. this.directionRandomizer = serializationObject.directionRandomizer;
  58664. };
  58665. return ConeParticleEmitter;
  58666. }());
  58667. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58668. })(BABYLON || (BABYLON = {}));
  58669. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58670. var BABYLON;
  58671. (function (BABYLON) {
  58672. /**
  58673. * Particle emitter emitting particles from the inside of a sphere.
  58674. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58675. */
  58676. var SphereParticleEmitter = /** @class */ (function () {
  58677. /**
  58678. * Creates a new instance SphereParticleEmitter
  58679. * @param radius the radius of the emission sphere (1 by default)
  58680. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58681. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58682. */
  58683. function SphereParticleEmitter(
  58684. /**
  58685. * The radius of the emission sphere.
  58686. */
  58687. radius,
  58688. /**
  58689. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58690. */
  58691. radiusRange,
  58692. /**
  58693. * How much to randomize the particle direction [0-1].
  58694. */
  58695. directionRandomizer) {
  58696. if (radius === void 0) { radius = 1; }
  58697. if (radiusRange === void 0) { radiusRange = 1; }
  58698. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58699. this.radius = radius;
  58700. this.radiusRange = radiusRange;
  58701. this.directionRandomizer = directionRandomizer;
  58702. }
  58703. /**
  58704. * Called by the particle System when the direction is computed for the created particle.
  58705. * @param worldMatrix is the world matrix of the particle system
  58706. * @param directionToUpdate is the direction vector to update with the result
  58707. * @param particle is the particle we are computed the direction for
  58708. */
  58709. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58710. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58711. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58712. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58713. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58714. direction.x += randX;
  58715. direction.y += randY;
  58716. direction.z += randZ;
  58717. direction.normalize();
  58718. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58719. };
  58720. /**
  58721. * Called by the particle System when the position is computed for the created particle.
  58722. * @param worldMatrix is the world matrix of the particle system
  58723. * @param positionToUpdate is the position vector to update with the result
  58724. * @param particle is the particle we are computed the position for
  58725. */
  58726. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58727. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58728. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58729. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58730. var theta = Math.acos(2 * v - 1);
  58731. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58732. var randY = randRadius * Math.cos(theta);
  58733. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58734. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58735. };
  58736. /**
  58737. * Clones the current emitter and returns a copy of it
  58738. * @returns the new emitter
  58739. */
  58740. SphereParticleEmitter.prototype.clone = function () {
  58741. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58742. BABYLON.Tools.DeepCopy(this, newOne);
  58743. return newOne;
  58744. };
  58745. /**
  58746. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58747. * @param effect defines the update shader
  58748. */
  58749. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58750. effect.setFloat("radius", this.radius);
  58751. effect.setFloat("radiusRange", this.radiusRange);
  58752. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58753. };
  58754. /**
  58755. * Returns a string to use to update the GPU particles update shader
  58756. * @returns a string containng the defines string
  58757. */
  58758. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58759. return "#define SPHEREEMITTER";
  58760. };
  58761. /**
  58762. * Returns the string "SphereParticleEmitter"
  58763. * @returns a string containing the class name
  58764. */
  58765. SphereParticleEmitter.prototype.getClassName = function () {
  58766. return "SphereParticleEmitter";
  58767. };
  58768. /**
  58769. * Serializes the particle system to a JSON object.
  58770. * @returns the JSON object
  58771. */
  58772. SphereParticleEmitter.prototype.serialize = function () {
  58773. var serializationObject = {};
  58774. serializationObject.type = this.getClassName();
  58775. serializationObject.radius = this.radius;
  58776. serializationObject.radiusRange = this.radiusRange;
  58777. serializationObject.directionRandomizer = this.directionRandomizer;
  58778. return serializationObject;
  58779. };
  58780. /**
  58781. * Parse properties from a JSON object
  58782. * @param serializationObject defines the JSON object
  58783. */
  58784. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58785. this.radius = serializationObject.radius;
  58786. this.radiusRange = serializationObject.radiusRange;
  58787. this.directionRandomizer = serializationObject.directionRandomizer;
  58788. };
  58789. return SphereParticleEmitter;
  58790. }());
  58791. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58792. /**
  58793. * Particle emitter emitting particles from the inside of a sphere.
  58794. * It emits the particles randomly between two vectors.
  58795. */
  58796. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58797. __extends(SphereDirectedParticleEmitter, _super);
  58798. /**
  58799. * Creates a new instance SphereDirectedParticleEmitter
  58800. * @param radius the radius of the emission sphere (1 by default)
  58801. * @param direction1 the min limit of the emission direction (up vector by default)
  58802. * @param direction2 the max limit of the emission direction (up vector by default)
  58803. */
  58804. function SphereDirectedParticleEmitter(radius,
  58805. /**
  58806. * The min limit of the emission direction.
  58807. */
  58808. direction1,
  58809. /**
  58810. * The max limit of the emission direction.
  58811. */
  58812. direction2) {
  58813. if (radius === void 0) { radius = 1; }
  58814. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58815. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58816. var _this = _super.call(this, radius) || this;
  58817. _this.direction1 = direction1;
  58818. _this.direction2 = direction2;
  58819. return _this;
  58820. }
  58821. /**
  58822. * Called by the particle System when the direction is computed for the created particle.
  58823. * @param worldMatrix is the world matrix of the particle system
  58824. * @param directionToUpdate is the direction vector to update with the result
  58825. * @param particle is the particle we are computed the direction for
  58826. */
  58827. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58828. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58829. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58830. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58831. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58832. };
  58833. /**
  58834. * Clones the current emitter and returns a copy of it
  58835. * @returns the new emitter
  58836. */
  58837. SphereDirectedParticleEmitter.prototype.clone = function () {
  58838. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58839. BABYLON.Tools.DeepCopy(this, newOne);
  58840. return newOne;
  58841. };
  58842. /**
  58843. * Called by the GPUParticleSystem to setup the update shader
  58844. * @param effect defines the update shader
  58845. */
  58846. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58847. effect.setFloat("radius", this.radius);
  58848. effect.setFloat("radiusRange", this.radiusRange);
  58849. effect.setVector3("direction1", this.direction1);
  58850. effect.setVector3("direction2", this.direction2);
  58851. };
  58852. /**
  58853. * Returns a string to use to update the GPU particles update shader
  58854. * @returns a string containng the defines string
  58855. */
  58856. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58857. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58858. };
  58859. /**
  58860. * Returns the string "SphereDirectedParticleEmitter"
  58861. * @returns a string containing the class name
  58862. */
  58863. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58864. return "SphereDirectedParticleEmitter";
  58865. };
  58866. /**
  58867. * Serializes the particle system to a JSON object.
  58868. * @returns the JSON object
  58869. */
  58870. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58871. var serializationObject = _super.prototype.serialize.call(this);
  58872. serializationObject.direction1 = this.direction1.asArray();
  58873. serializationObject.direction2 = this.direction2.asArray();
  58874. return serializationObject;
  58875. };
  58876. /**
  58877. * Parse properties from a JSON object
  58878. * @param serializationObject defines the JSON object
  58879. */
  58880. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58881. _super.prototype.parse.call(this, serializationObject);
  58882. this.direction1.copyFrom(serializationObject.direction1);
  58883. this.direction2.copyFrom(serializationObject.direction2);
  58884. };
  58885. return SphereDirectedParticleEmitter;
  58886. }(SphereParticleEmitter));
  58887. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58888. })(BABYLON || (BABYLON = {}));
  58889. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58890. var BABYLON;
  58891. (function (BABYLON) {
  58892. /**
  58893. * Particle emitter emitting particles from the inside of a hemisphere.
  58894. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58895. */
  58896. var HemisphericParticleEmitter = /** @class */ (function () {
  58897. /**
  58898. * Creates a new instance HemisphericParticleEmitter
  58899. * @param radius the radius of the emission hemisphere (1 by default)
  58900. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58901. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58902. */
  58903. function HemisphericParticleEmitter(
  58904. /**
  58905. * The radius of the emission hemisphere.
  58906. */
  58907. radius,
  58908. /**
  58909. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58910. */
  58911. radiusRange,
  58912. /**
  58913. * How much to randomize the particle direction [0-1].
  58914. */
  58915. directionRandomizer) {
  58916. if (radius === void 0) { radius = 1; }
  58917. if (radiusRange === void 0) { radiusRange = 1; }
  58918. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58919. this.radius = radius;
  58920. this.radiusRange = radiusRange;
  58921. this.directionRandomizer = directionRandomizer;
  58922. }
  58923. /**
  58924. * Called by the particle System when the direction is computed for the created particle.
  58925. * @param worldMatrix is the world matrix of the particle system
  58926. * @param directionToUpdate is the direction vector to update with the result
  58927. * @param particle is the particle we are computed the direction for
  58928. */
  58929. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58930. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58931. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58932. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58933. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58934. direction.x += randX;
  58935. direction.y += randY;
  58936. direction.z += randZ;
  58937. direction.normalize();
  58938. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58939. };
  58940. /**
  58941. * Called by the particle System when the position is computed for the created particle.
  58942. * @param worldMatrix is the world matrix of the particle system
  58943. * @param positionToUpdate is the position vector to update with the result
  58944. * @param particle is the particle we are computed the position for
  58945. */
  58946. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58947. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58948. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58949. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58950. var theta = Math.acos(2 * v - 1);
  58951. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58952. var randY = randRadius * Math.cos(theta);
  58953. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58954. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58955. };
  58956. /**
  58957. * Clones the current emitter and returns a copy of it
  58958. * @returns the new emitter
  58959. */
  58960. HemisphericParticleEmitter.prototype.clone = function () {
  58961. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58962. BABYLON.Tools.DeepCopy(this, newOne);
  58963. return newOne;
  58964. };
  58965. /**
  58966. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58967. * @param effect defines the update shader
  58968. */
  58969. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58970. effect.setFloat("radius", this.radius);
  58971. effect.setFloat("radiusRange", this.radiusRange);
  58972. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58973. };
  58974. /**
  58975. * Returns a string to use to update the GPU particles update shader
  58976. * @returns a string containng the defines string
  58977. */
  58978. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58979. return "#define HEMISPHERICEMITTER";
  58980. };
  58981. /**
  58982. * Returns the string "HemisphericParticleEmitter"
  58983. * @returns a string containing the class name
  58984. */
  58985. HemisphericParticleEmitter.prototype.getClassName = function () {
  58986. return "HemisphericParticleEmitter";
  58987. };
  58988. /**
  58989. * Serializes the particle system to a JSON object.
  58990. * @returns the JSON object
  58991. */
  58992. HemisphericParticleEmitter.prototype.serialize = function () {
  58993. var serializationObject = {};
  58994. serializationObject.type = this.getClassName();
  58995. serializationObject.radius = this.radius;
  58996. serializationObject.radiusRange = this.radiusRange;
  58997. serializationObject.directionRandomizer = this.directionRandomizer;
  58998. return serializationObject;
  58999. };
  59000. /**
  59001. * Parse properties from a JSON object
  59002. * @param serializationObject defines the JSON object
  59003. */
  59004. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  59005. this.radius = serializationObject.radius;
  59006. this.radiusRange = serializationObject.radiusRange;
  59007. this.directionRandomizer = serializationObject.directionRandomizer;
  59008. };
  59009. return HemisphericParticleEmitter;
  59010. }());
  59011. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  59012. })(BABYLON || (BABYLON = {}));
  59013. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  59014. var BABYLON;
  59015. (function (BABYLON) {
  59016. /**
  59017. * Particle emitter emitting particles from a point.
  59018. * It emits the particles randomly between 2 given directions.
  59019. */
  59020. var PointParticleEmitter = /** @class */ (function () {
  59021. /**
  59022. * Creates a new instance PointParticleEmitter
  59023. */
  59024. function PointParticleEmitter() {
  59025. /**
  59026. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59027. */
  59028. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59029. /**
  59030. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59031. */
  59032. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59033. }
  59034. /**
  59035. * Called by the particle System when the direction is computed for the created particle.
  59036. * @param worldMatrix is the world matrix of the particle system
  59037. * @param directionToUpdate is the direction vector to update with the result
  59038. * @param particle is the particle we are computed the direction for
  59039. */
  59040. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59041. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59042. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59043. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59044. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59045. };
  59046. /**
  59047. * Called by the particle System when the position is computed for the created particle.
  59048. * @param worldMatrix is the world matrix of the particle system
  59049. * @param positionToUpdate is the position vector to update with the result
  59050. * @param particle is the particle we are computed the position for
  59051. */
  59052. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59053. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  59054. };
  59055. /**
  59056. * Clones the current emitter and returns a copy of it
  59057. * @returns the new emitter
  59058. */
  59059. PointParticleEmitter.prototype.clone = function () {
  59060. var newOne = new PointParticleEmitter();
  59061. BABYLON.Tools.DeepCopy(this, newOne);
  59062. return newOne;
  59063. };
  59064. /**
  59065. * Called by the GPUParticleSystem to setup the update shader
  59066. * @param effect defines the update shader
  59067. */
  59068. PointParticleEmitter.prototype.applyToShader = function (effect) {
  59069. effect.setVector3("direction1", this.direction1);
  59070. effect.setVector3("direction2", this.direction2);
  59071. };
  59072. /**
  59073. * Returns a string to use to update the GPU particles update shader
  59074. * @returns a string containng the defines string
  59075. */
  59076. PointParticleEmitter.prototype.getEffectDefines = function () {
  59077. return "#define POINTEMITTER";
  59078. };
  59079. /**
  59080. * Returns the string "PointParticleEmitter"
  59081. * @returns a string containing the class name
  59082. */
  59083. PointParticleEmitter.prototype.getClassName = function () {
  59084. return "PointParticleEmitter";
  59085. };
  59086. /**
  59087. * Serializes the particle system to a JSON object.
  59088. * @returns the JSON object
  59089. */
  59090. PointParticleEmitter.prototype.serialize = function () {
  59091. var serializationObject = {};
  59092. serializationObject.type = this.getClassName();
  59093. serializationObject.direction1 = this.direction1.asArray();
  59094. serializationObject.direction2 = this.direction2.asArray();
  59095. return serializationObject;
  59096. };
  59097. /**
  59098. * Parse properties from a JSON object
  59099. * @param serializationObject defines the JSON object
  59100. */
  59101. PointParticleEmitter.prototype.parse = function (serializationObject) {
  59102. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59103. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59104. };
  59105. return PointParticleEmitter;
  59106. }());
  59107. BABYLON.PointParticleEmitter = PointParticleEmitter;
  59108. })(BABYLON || (BABYLON = {}));
  59109. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  59110. var BABYLON;
  59111. (function (BABYLON) {
  59112. // Adds the parsers to the scene parsers.
  59113. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  59114. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  59115. if (!individualParser) {
  59116. return;
  59117. }
  59118. // Particles Systems
  59119. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59120. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59121. var parsedParticleSystem = parsedData.particleSystems[index];
  59122. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  59123. }
  59124. }
  59125. });
  59126. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  59127. if (parsedParticleSystem.activeParticleCount) {
  59128. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59129. return ps;
  59130. }
  59131. else {
  59132. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59133. return ps;
  59134. }
  59135. });
  59136. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  59137. if (uniformsNames === void 0) { uniformsNames = []; }
  59138. if (samplers === void 0) { samplers = []; }
  59139. if (defines === void 0) { defines = ""; }
  59140. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  59141. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  59142. if (defines.indexOf(" BILLBOARD") === -1) {
  59143. defines += "\n#define BILLBOARD\n";
  59144. }
  59145. if (samplers.indexOf("diffuseSampler") === -1) {
  59146. samplers.push("diffuseSampler");
  59147. }
  59148. return this.createEffect({
  59149. vertex: "particles",
  59150. fragmentElement: fragmentName
  59151. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  59152. };
  59153. })(BABYLON || (BABYLON = {}));
  59154. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  59155. var BABYLON;
  59156. (function (BABYLON) {
  59157. /**
  59158. * Type of sub emitter
  59159. */
  59160. var SubEmitterType;
  59161. (function (SubEmitterType) {
  59162. /**
  59163. * Attached to the particle over it's lifetime
  59164. */
  59165. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  59166. /**
  59167. * Created when the particle dies
  59168. */
  59169. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  59170. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  59171. /**
  59172. * Sub emitter class used to emit particles from an existing particle
  59173. */
  59174. var SubEmitter = /** @class */ (function () {
  59175. /**
  59176. * Creates a sub emitter
  59177. * @param particleSystem the particle system to be used by the sub emitter
  59178. */
  59179. function SubEmitter(
  59180. /**
  59181. * the particle system to be used by the sub emitter
  59182. */
  59183. particleSystem) {
  59184. this.particleSystem = particleSystem;
  59185. /**
  59186. * Type of the submitter (Default: END)
  59187. */
  59188. this.type = SubEmitterType.END;
  59189. /**
  59190. * 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)
  59191. * Note: This only is supported when using an emitter of type Mesh
  59192. */
  59193. this.inheritDirection = false;
  59194. /**
  59195. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  59196. */
  59197. this.inheritedVelocityAmount = 0;
  59198. }
  59199. /**
  59200. * Clones the sub emitter
  59201. * @returns the cloned sub emitter
  59202. */
  59203. SubEmitter.prototype.clone = function () {
  59204. // Clone particle system
  59205. var emitter = this.particleSystem.emitter;
  59206. if (!emitter) {
  59207. emitter = new BABYLON.Vector3();
  59208. }
  59209. else if (emitter instanceof BABYLON.Vector3) {
  59210. emitter = emitter.clone();
  59211. }
  59212. else if (emitter instanceof BABYLON.AbstractMesh) {
  59213. emitter = new BABYLON.Mesh("", emitter._scene);
  59214. }
  59215. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  59216. // Clone properties
  59217. clone.type = this.type;
  59218. clone.inheritDirection = this.inheritDirection;
  59219. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  59220. clone.particleSystem._disposeEmitterOnDispose = true;
  59221. return clone;
  59222. };
  59223. return SubEmitter;
  59224. }());
  59225. BABYLON.SubEmitter = SubEmitter;
  59226. })(BABYLON || (BABYLON = {}));
  59227. //# sourceMappingURL=babylon.subEmitter.js.map
  59228. var BABYLON;
  59229. (function (BABYLON) {
  59230. var ShaderMaterial = /** @class */ (function (_super) {
  59231. __extends(ShaderMaterial, _super);
  59232. function ShaderMaterial(name, scene, shaderPath, options) {
  59233. var _this = _super.call(this, name, scene) || this;
  59234. _this._textures = {};
  59235. _this._textureArrays = {};
  59236. _this._floats = {};
  59237. _this._ints = {};
  59238. _this._floatsArrays = {};
  59239. _this._colors3 = {};
  59240. _this._colors3Arrays = {};
  59241. _this._colors4 = {};
  59242. _this._vectors2 = {};
  59243. _this._vectors3 = {};
  59244. _this._vectors4 = {};
  59245. _this._matrices = {};
  59246. _this._matrices3x3 = {};
  59247. _this._matrices2x2 = {};
  59248. _this._vectors2Arrays = {};
  59249. _this._vectors3Arrays = {};
  59250. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59251. _this._shaderPath = shaderPath;
  59252. options.needAlphaBlending = options.needAlphaBlending || false;
  59253. options.needAlphaTesting = options.needAlphaTesting || false;
  59254. options.attributes = options.attributes || ["position", "normal", "uv"];
  59255. options.uniforms = options.uniforms || ["worldViewProjection"];
  59256. options.uniformBuffers = options.uniformBuffers || [];
  59257. options.samplers = options.samplers || [];
  59258. options.defines = options.defines || [];
  59259. _this._options = options;
  59260. return _this;
  59261. }
  59262. ShaderMaterial.prototype.getClassName = function () {
  59263. return "ShaderMaterial";
  59264. };
  59265. ShaderMaterial.prototype.needAlphaBlending = function () {
  59266. return this._options.needAlphaBlending;
  59267. };
  59268. ShaderMaterial.prototype.needAlphaTesting = function () {
  59269. return this._options.needAlphaTesting;
  59270. };
  59271. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59272. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59273. this._options.uniforms.push(uniformName);
  59274. }
  59275. };
  59276. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59277. if (this._options.samplers.indexOf(name) === -1) {
  59278. this._options.samplers.push(name);
  59279. }
  59280. this._textures[name] = texture;
  59281. return this;
  59282. };
  59283. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59284. if (this._options.samplers.indexOf(name) === -1) {
  59285. this._options.samplers.push(name);
  59286. }
  59287. this._checkUniform(name);
  59288. this._textureArrays[name] = textures;
  59289. return this;
  59290. };
  59291. ShaderMaterial.prototype.setFloat = function (name, value) {
  59292. this._checkUniform(name);
  59293. this._floats[name] = value;
  59294. return this;
  59295. };
  59296. ShaderMaterial.prototype.setInt = function (name, value) {
  59297. this._checkUniform(name);
  59298. this._ints[name] = value;
  59299. return this;
  59300. };
  59301. ShaderMaterial.prototype.setFloats = function (name, value) {
  59302. this._checkUniform(name);
  59303. this._floatsArrays[name] = value;
  59304. return this;
  59305. };
  59306. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59307. this._checkUniform(name);
  59308. this._colors3[name] = value;
  59309. return this;
  59310. };
  59311. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59312. this._checkUniform(name);
  59313. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59314. color.toArray(arr, arr.length);
  59315. return arr;
  59316. }, []);
  59317. return this;
  59318. };
  59319. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59320. this._checkUniform(name);
  59321. this._colors4[name] = value;
  59322. return this;
  59323. };
  59324. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59325. this._checkUniform(name);
  59326. this._vectors2[name] = value;
  59327. return this;
  59328. };
  59329. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59330. this._checkUniform(name);
  59331. this._vectors3[name] = value;
  59332. return this;
  59333. };
  59334. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59335. this._checkUniform(name);
  59336. this._vectors4[name] = value;
  59337. return this;
  59338. };
  59339. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59340. this._checkUniform(name);
  59341. this._matrices[name] = value;
  59342. return this;
  59343. };
  59344. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59345. this._checkUniform(name);
  59346. this._matrices3x3[name] = value;
  59347. return this;
  59348. };
  59349. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59350. this._checkUniform(name);
  59351. this._matrices2x2[name] = value;
  59352. return this;
  59353. };
  59354. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59355. this._checkUniform(name);
  59356. this._vectors2Arrays[name] = value;
  59357. return this;
  59358. };
  59359. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59360. this._checkUniform(name);
  59361. this._vectors3Arrays[name] = value;
  59362. return this;
  59363. };
  59364. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59365. if (!mesh) {
  59366. return true;
  59367. }
  59368. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59369. return false;
  59370. }
  59371. return false;
  59372. };
  59373. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59374. var scene = this.getScene();
  59375. var engine = scene.getEngine();
  59376. if (!this.checkReadyOnEveryCall) {
  59377. if (this._renderId === scene.getRenderId()) {
  59378. if (this._checkCache(scene, mesh, useInstances)) {
  59379. return true;
  59380. }
  59381. }
  59382. }
  59383. // Instances
  59384. var defines = [];
  59385. var attribs = [];
  59386. var fallbacks = new BABYLON.EffectFallbacks();
  59387. if (useInstances) {
  59388. defines.push("#define INSTANCES");
  59389. }
  59390. for (var index = 0; index < this._options.defines.length; index++) {
  59391. defines.push(this._options.defines[index]);
  59392. }
  59393. for (var index = 0; index < this._options.attributes.length; index++) {
  59394. attribs.push(this._options.attributes[index]);
  59395. }
  59396. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59397. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59398. defines.push("#define VERTEXCOLOR");
  59399. }
  59400. // Bones
  59401. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59402. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59403. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59404. if (mesh.numBoneInfluencers > 4) {
  59405. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59406. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59407. }
  59408. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59409. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59410. fallbacks.addCPUSkinningFallback(0, mesh);
  59411. if (this._options.uniforms.indexOf("mBones") === -1) {
  59412. this._options.uniforms.push("mBones");
  59413. }
  59414. }
  59415. else {
  59416. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59417. }
  59418. // Textures
  59419. for (var name in this._textures) {
  59420. if (!this._textures[name].isReady()) {
  59421. return false;
  59422. }
  59423. }
  59424. // Alpha test
  59425. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59426. defines.push("#define ALPHATEST");
  59427. }
  59428. var previousEffect = this._effect;
  59429. var join = defines.join("\n");
  59430. this._effect = engine.createEffect(this._shaderPath, {
  59431. attributes: attribs,
  59432. uniformsNames: this._options.uniforms,
  59433. uniformBuffersNames: this._options.uniformBuffers,
  59434. samplers: this._options.samplers,
  59435. defines: join,
  59436. fallbacks: fallbacks,
  59437. onCompiled: this.onCompiled,
  59438. onError: this.onError
  59439. }, engine);
  59440. if (!this._effect.isReady()) {
  59441. return false;
  59442. }
  59443. if (previousEffect !== this._effect) {
  59444. scene.resetCachedMaterial();
  59445. }
  59446. this._renderId = scene.getRenderId();
  59447. return true;
  59448. };
  59449. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59450. var scene = this.getScene();
  59451. if (!this._effect) {
  59452. return;
  59453. }
  59454. if (this._options.uniforms.indexOf("world") !== -1) {
  59455. this._effect.setMatrix("world", world);
  59456. }
  59457. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59458. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59459. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59460. }
  59461. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59462. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59463. }
  59464. };
  59465. ShaderMaterial.prototype.bind = function (world, mesh) {
  59466. // Std values
  59467. this.bindOnlyWorldMatrix(world);
  59468. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59469. if (this._options.uniforms.indexOf("view") !== -1) {
  59470. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59471. }
  59472. if (this._options.uniforms.indexOf("projection") !== -1) {
  59473. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59474. }
  59475. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59476. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59477. }
  59478. // Bones
  59479. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59480. var name;
  59481. // Texture
  59482. for (name in this._textures) {
  59483. this._effect.setTexture(name, this._textures[name]);
  59484. }
  59485. // Texture arrays
  59486. for (name in this._textureArrays) {
  59487. this._effect.setTextureArray(name, this._textureArrays[name]);
  59488. }
  59489. // Int
  59490. for (name in this._ints) {
  59491. this._effect.setInt(name, this._ints[name]);
  59492. }
  59493. // Float
  59494. for (name in this._floats) {
  59495. this._effect.setFloat(name, this._floats[name]);
  59496. }
  59497. // Floats
  59498. for (name in this._floatsArrays) {
  59499. this._effect.setArray(name, this._floatsArrays[name]);
  59500. }
  59501. // Color3
  59502. for (name in this._colors3) {
  59503. this._effect.setColor3(name, this._colors3[name]);
  59504. }
  59505. for (name in this._colors3Arrays) {
  59506. this._effect.setArray3(name, this._colors3Arrays[name]);
  59507. }
  59508. // Color4
  59509. for (name in this._colors4) {
  59510. var color = this._colors4[name];
  59511. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59512. }
  59513. // Vector2
  59514. for (name in this._vectors2) {
  59515. this._effect.setVector2(name, this._vectors2[name]);
  59516. }
  59517. // Vector3
  59518. for (name in this._vectors3) {
  59519. this._effect.setVector3(name, this._vectors3[name]);
  59520. }
  59521. // Vector4
  59522. for (name in this._vectors4) {
  59523. this._effect.setVector4(name, this._vectors4[name]);
  59524. }
  59525. // Matrix
  59526. for (name in this._matrices) {
  59527. this._effect.setMatrix(name, this._matrices[name]);
  59528. }
  59529. // Matrix 3x3
  59530. for (name in this._matrices3x3) {
  59531. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59532. }
  59533. // Matrix 2x2
  59534. for (name in this._matrices2x2) {
  59535. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59536. }
  59537. // Vector2Array
  59538. for (name in this._vectors2Arrays) {
  59539. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59540. }
  59541. // Vector3Array
  59542. for (name in this._vectors3Arrays) {
  59543. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59544. }
  59545. }
  59546. this._afterBind(mesh);
  59547. };
  59548. ShaderMaterial.prototype.getActiveTextures = function () {
  59549. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59550. for (var name in this._textures) {
  59551. activeTextures.push(this._textures[name]);
  59552. }
  59553. for (var name in this._textureArrays) {
  59554. var array = this._textureArrays[name];
  59555. for (var index = 0; index < array.length; index++) {
  59556. activeTextures.push(array[index]);
  59557. }
  59558. }
  59559. return activeTextures;
  59560. };
  59561. ShaderMaterial.prototype.hasTexture = function (texture) {
  59562. if (_super.prototype.hasTexture.call(this, texture)) {
  59563. return true;
  59564. }
  59565. for (var name in this._textures) {
  59566. if (this._textures[name] === texture) {
  59567. return true;
  59568. }
  59569. }
  59570. for (var name in this._textureArrays) {
  59571. var array = this._textureArrays[name];
  59572. for (var index = 0; index < array.length; index++) {
  59573. if (array[index] === texture) {
  59574. return true;
  59575. }
  59576. }
  59577. }
  59578. return false;
  59579. };
  59580. ShaderMaterial.prototype.clone = function (name) {
  59581. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59582. return newShaderMaterial;
  59583. };
  59584. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59585. if (forceDisposeTextures) {
  59586. var name;
  59587. for (name in this._textures) {
  59588. this._textures[name].dispose();
  59589. }
  59590. for (name in this._textureArrays) {
  59591. var array = this._textureArrays[name];
  59592. for (var index = 0; index < array.length; index++) {
  59593. array[index].dispose();
  59594. }
  59595. }
  59596. }
  59597. this._textures = {};
  59598. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59599. };
  59600. ShaderMaterial.prototype.serialize = function () {
  59601. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59602. serializationObject.customType = "BABYLON.ShaderMaterial";
  59603. serializationObject.options = this._options;
  59604. serializationObject.shaderPath = this._shaderPath;
  59605. var name;
  59606. // Texture
  59607. serializationObject.textures = {};
  59608. for (name in this._textures) {
  59609. serializationObject.textures[name] = this._textures[name].serialize();
  59610. }
  59611. // Texture arrays
  59612. serializationObject.textureArrays = {};
  59613. for (name in this._textureArrays) {
  59614. serializationObject.textureArrays[name] = [];
  59615. var array = this._textureArrays[name];
  59616. for (var index = 0; index < array.length; index++) {
  59617. serializationObject.textureArrays[name].push(array[index].serialize());
  59618. }
  59619. }
  59620. // Float
  59621. serializationObject.floats = {};
  59622. for (name in this._floats) {
  59623. serializationObject.floats[name] = this._floats[name];
  59624. }
  59625. // Float s
  59626. serializationObject.FloatArrays = {};
  59627. for (name in this._floatsArrays) {
  59628. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59629. }
  59630. // Color3
  59631. serializationObject.colors3 = {};
  59632. for (name in this._colors3) {
  59633. serializationObject.colors3[name] = this._colors3[name].asArray();
  59634. }
  59635. // Color3 array
  59636. serializationObject.colors3Arrays = {};
  59637. for (name in this._colors3Arrays) {
  59638. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59639. }
  59640. // Color4
  59641. serializationObject.colors4 = {};
  59642. for (name in this._colors4) {
  59643. serializationObject.colors4[name] = this._colors4[name].asArray();
  59644. }
  59645. // Vector2
  59646. serializationObject.vectors2 = {};
  59647. for (name in this._vectors2) {
  59648. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59649. }
  59650. // Vector3
  59651. serializationObject.vectors3 = {};
  59652. for (name in this._vectors3) {
  59653. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59654. }
  59655. // Vector4
  59656. serializationObject.vectors4 = {};
  59657. for (name in this._vectors4) {
  59658. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59659. }
  59660. // Matrix
  59661. serializationObject.matrices = {};
  59662. for (name in this._matrices) {
  59663. serializationObject.matrices[name] = this._matrices[name].asArray();
  59664. }
  59665. // Matrix 3x3
  59666. serializationObject.matrices3x3 = {};
  59667. for (name in this._matrices3x3) {
  59668. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59669. }
  59670. // Matrix 2x2
  59671. serializationObject.matrices2x2 = {};
  59672. for (name in this._matrices2x2) {
  59673. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59674. }
  59675. // Vector2Array
  59676. serializationObject.vectors2Arrays = {};
  59677. for (name in this._vectors2Arrays) {
  59678. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59679. }
  59680. // Vector3Array
  59681. serializationObject.vectors3Arrays = {};
  59682. for (name in this._vectors3Arrays) {
  59683. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59684. }
  59685. return serializationObject;
  59686. };
  59687. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59688. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59689. var name;
  59690. // Texture
  59691. for (name in source.textures) {
  59692. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59693. }
  59694. // Texture arrays
  59695. for (name in source.textureArrays) {
  59696. var array = source.textureArrays[name];
  59697. var textureArray = new Array();
  59698. for (var index = 0; index < array.length; index++) {
  59699. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59700. }
  59701. material.setTextureArray(name, textureArray);
  59702. }
  59703. // Float
  59704. for (name in source.floats) {
  59705. material.setFloat(name, source.floats[name]);
  59706. }
  59707. // Float s
  59708. for (name in source.floatsArrays) {
  59709. material.setFloats(name, source.floatsArrays[name]);
  59710. }
  59711. // Color3
  59712. for (name in source.colors3) {
  59713. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59714. }
  59715. // Color3 arrays
  59716. for (name in source.colors3Arrays) {
  59717. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59718. if (i % 3 === 0) {
  59719. arr.push([num]);
  59720. }
  59721. else {
  59722. arr[arr.length - 1].push(num);
  59723. }
  59724. return arr;
  59725. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59726. material.setColor3Array(name, colors);
  59727. }
  59728. // Color4
  59729. for (name in source.colors4) {
  59730. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59731. }
  59732. // Vector2
  59733. for (name in source.vectors2) {
  59734. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59735. }
  59736. // Vector3
  59737. for (name in source.vectors3) {
  59738. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59739. }
  59740. // Vector4
  59741. for (name in source.vectors4) {
  59742. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59743. }
  59744. // Matrix
  59745. for (name in source.matrices) {
  59746. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59747. }
  59748. // Matrix 3x3
  59749. for (name in source.matrices3x3) {
  59750. material.setMatrix3x3(name, source.matrices3x3[name]);
  59751. }
  59752. // Matrix 2x2
  59753. for (name in source.matrices2x2) {
  59754. material.setMatrix2x2(name, source.matrices2x2[name]);
  59755. }
  59756. // Vector2Array
  59757. for (name in source.vectors2Arrays) {
  59758. material.setArray2(name, source.vectors2Arrays[name]);
  59759. }
  59760. // Vector3Array
  59761. for (name in source.vectors3Arrays) {
  59762. material.setArray3(name, source.vectors3Arrays[name]);
  59763. }
  59764. return material;
  59765. };
  59766. return ShaderMaterial;
  59767. }(BABYLON.Material));
  59768. BABYLON.ShaderMaterial = ShaderMaterial;
  59769. })(BABYLON || (BABYLON = {}));
  59770. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59771. var BABYLON;
  59772. (function (BABYLON) {
  59773. var GroundMesh = /** @class */ (function (_super) {
  59774. __extends(GroundMesh, _super);
  59775. function GroundMesh(name, scene) {
  59776. var _this = _super.call(this, name, scene) || this;
  59777. _this.generateOctree = false;
  59778. return _this;
  59779. }
  59780. GroundMesh.prototype.getClassName = function () {
  59781. return "GroundMesh";
  59782. };
  59783. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59784. get: function () {
  59785. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59786. },
  59787. enumerable: true,
  59788. configurable: true
  59789. });
  59790. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59791. get: function () {
  59792. return this._subdivisionsX;
  59793. },
  59794. enumerable: true,
  59795. configurable: true
  59796. });
  59797. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59798. get: function () {
  59799. return this._subdivisionsY;
  59800. },
  59801. enumerable: true,
  59802. configurable: true
  59803. });
  59804. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59805. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59806. this._subdivisionsX = chunksCount;
  59807. this._subdivisionsY = chunksCount;
  59808. this.subdivide(chunksCount);
  59809. // Call the octree system optimization if it is defined.
  59810. var thisAsAny = this;
  59811. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  59812. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59813. }
  59814. };
  59815. /**
  59816. * Returns a height (y) value in the Worl system :
  59817. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59818. * Returns the ground y position if (x, z) are outside the ground surface.
  59819. */
  59820. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59821. var world = this.getWorldMatrix();
  59822. var invMat = BABYLON.Tmp.Matrix[5];
  59823. world.invertToRef(invMat);
  59824. var tmpVect = BABYLON.Tmp.Vector3[8];
  59825. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59826. x = tmpVect.x;
  59827. z = tmpVect.z;
  59828. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59829. return this.position.y;
  59830. }
  59831. if (!this._heightQuads || this._heightQuads.length == 0) {
  59832. this._initHeightQuads();
  59833. this._computeHeightQuads();
  59834. }
  59835. var facet = this._getFacetAt(x, z);
  59836. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59837. // return y in the World system
  59838. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59839. return tmpVect.y;
  59840. };
  59841. /**
  59842. * Returns a normalized vector (Vector3) orthogonal to the ground
  59843. * at the ground coordinates (x, z) expressed in the World system.
  59844. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59845. */
  59846. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59847. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59848. this.getNormalAtCoordinatesToRef(x, z, normal);
  59849. return normal;
  59850. };
  59851. /**
  59852. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59853. * at the ground coordinates (x, z) expressed in the World system.
  59854. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59855. * Returns the GroundMesh.
  59856. */
  59857. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59858. var world = this.getWorldMatrix();
  59859. var tmpMat = BABYLON.Tmp.Matrix[5];
  59860. world.invertToRef(tmpMat);
  59861. var tmpVect = BABYLON.Tmp.Vector3[8];
  59862. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59863. x = tmpVect.x;
  59864. z = tmpVect.z;
  59865. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59866. return this;
  59867. }
  59868. if (!this._heightQuads || this._heightQuads.length == 0) {
  59869. this._initHeightQuads();
  59870. this._computeHeightQuads();
  59871. }
  59872. var facet = this._getFacetAt(x, z);
  59873. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59874. return this;
  59875. };
  59876. /**
  59877. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59878. * if the ground has been updated.
  59879. * This can be used in the render loop.
  59880. * Returns the GroundMesh.
  59881. */
  59882. GroundMesh.prototype.updateCoordinateHeights = function () {
  59883. if (!this._heightQuads || this._heightQuads.length == 0) {
  59884. this._initHeightQuads();
  59885. }
  59886. this._computeHeightQuads();
  59887. return this;
  59888. };
  59889. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59890. GroundMesh.prototype._getFacetAt = function (x, z) {
  59891. // retrieve col and row from x, z coordinates in the ground local system
  59892. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59893. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59894. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59895. var facet;
  59896. if (z < quad.slope.x * x + quad.slope.y) {
  59897. facet = quad.facet1;
  59898. }
  59899. else {
  59900. facet = quad.facet2;
  59901. }
  59902. return facet;
  59903. };
  59904. // Creates and populates the heightMap array with "facet" elements :
  59905. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59906. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59907. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59908. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59909. // Returns the GroundMesh.
  59910. GroundMesh.prototype._initHeightQuads = function () {
  59911. var subdivisionsX = this._subdivisionsX;
  59912. var subdivisionsY = this._subdivisionsY;
  59913. this._heightQuads = new Array();
  59914. for (var row = 0; row < subdivisionsY; row++) {
  59915. for (var col = 0; col < subdivisionsX; col++) {
  59916. 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) };
  59917. this._heightQuads[row * subdivisionsX + col] = quad;
  59918. }
  59919. }
  59920. return this;
  59921. };
  59922. // Compute each quad element values and update the the heightMap array :
  59923. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59924. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59925. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59926. // Returns the GroundMesh.
  59927. GroundMesh.prototype._computeHeightQuads = function () {
  59928. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59929. if (!positions) {
  59930. return this;
  59931. }
  59932. var v1 = BABYLON.Tmp.Vector3[3];
  59933. var v2 = BABYLON.Tmp.Vector3[2];
  59934. var v3 = BABYLON.Tmp.Vector3[1];
  59935. var v4 = BABYLON.Tmp.Vector3[0];
  59936. var v1v2 = BABYLON.Tmp.Vector3[4];
  59937. var v1v3 = BABYLON.Tmp.Vector3[5];
  59938. var v1v4 = BABYLON.Tmp.Vector3[6];
  59939. var norm1 = BABYLON.Tmp.Vector3[7];
  59940. var norm2 = BABYLON.Tmp.Vector3[8];
  59941. var i = 0;
  59942. var j = 0;
  59943. var k = 0;
  59944. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59945. var h = 0;
  59946. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59947. var d2 = 0;
  59948. var subdivisionsX = this._subdivisionsX;
  59949. var subdivisionsY = this._subdivisionsY;
  59950. for (var row = 0; row < subdivisionsY; row++) {
  59951. for (var col = 0; col < subdivisionsX; col++) {
  59952. i = col * 3;
  59953. j = row * (subdivisionsX + 1) * 3;
  59954. k = (row + 1) * (subdivisionsX + 1) * 3;
  59955. v1.x = positions[j + i];
  59956. v1.y = positions[j + i + 1];
  59957. v1.z = positions[j + i + 2];
  59958. v2.x = positions[j + i + 3];
  59959. v2.y = positions[j + i + 4];
  59960. v2.z = positions[j + i + 5];
  59961. v3.x = positions[k + i];
  59962. v3.y = positions[k + i + 1];
  59963. v3.z = positions[k + i + 2];
  59964. v4.x = positions[k + i + 3];
  59965. v4.y = positions[k + i + 4];
  59966. v4.z = positions[k + i + 5];
  59967. // 2D slope V1V4
  59968. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59969. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59970. // facet equations :
  59971. // we compute each facet normal vector
  59972. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59973. // we compute the value d by applying the equation to v1 which belongs to the plane
  59974. // then we store the facet equation in a Vector4
  59975. v2.subtractToRef(v1, v1v2);
  59976. v3.subtractToRef(v1, v1v3);
  59977. v4.subtractToRef(v1, v1v4);
  59978. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59979. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59980. norm1.normalize();
  59981. norm2.normalize();
  59982. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59983. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59984. var quad = this._heightQuads[row * subdivisionsX + col];
  59985. quad.slope.copyFromFloats(cd, h);
  59986. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59987. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59988. }
  59989. }
  59990. return this;
  59991. };
  59992. GroundMesh.prototype.serialize = function (serializationObject) {
  59993. _super.prototype.serialize.call(this, serializationObject);
  59994. serializationObject.subdivisionsX = this._subdivisionsX;
  59995. serializationObject.subdivisionsY = this._subdivisionsY;
  59996. serializationObject.minX = this._minX;
  59997. serializationObject.maxX = this._maxX;
  59998. serializationObject.minZ = this._minZ;
  59999. serializationObject.maxZ = this._maxZ;
  60000. serializationObject.width = this._width;
  60001. serializationObject.height = this._height;
  60002. };
  60003. GroundMesh.Parse = function (parsedMesh, scene) {
  60004. var result = new GroundMesh(parsedMesh.name, scene);
  60005. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60006. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60007. result._minX = parsedMesh.minX;
  60008. result._maxX = parsedMesh.maxX;
  60009. result._minZ = parsedMesh.minZ;
  60010. result._maxZ = parsedMesh.maxZ;
  60011. result._width = parsedMesh.width;
  60012. result._height = parsedMesh.height;
  60013. return result;
  60014. };
  60015. return GroundMesh;
  60016. }(BABYLON.Mesh));
  60017. BABYLON.GroundMesh = GroundMesh;
  60018. })(BABYLON || (BABYLON = {}));
  60019. //# sourceMappingURL=babylon.groundMesh.js.map
  60020. var BABYLON;
  60021. (function (BABYLON) {
  60022. /**
  60023. * Creates an instance based on a source mesh.
  60024. */
  60025. var InstancedMesh = /** @class */ (function (_super) {
  60026. __extends(InstancedMesh, _super);
  60027. function InstancedMesh(name, source) {
  60028. var _this = _super.call(this, name, source.getScene()) || this;
  60029. source.instances.push(_this);
  60030. _this._sourceMesh = source;
  60031. _this.position.copyFrom(source.position);
  60032. _this.rotation.copyFrom(source.rotation);
  60033. _this.scaling.copyFrom(source.scaling);
  60034. if (source.rotationQuaternion) {
  60035. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60036. }
  60037. _this.infiniteDistance = source.infiniteDistance;
  60038. _this.setPivotMatrix(source.getPivotMatrix());
  60039. _this.refreshBoundingInfo();
  60040. _this._syncSubMeshes();
  60041. return _this;
  60042. }
  60043. /**
  60044. * Returns the string "InstancedMesh".
  60045. */
  60046. InstancedMesh.prototype.getClassName = function () {
  60047. return "InstancedMesh";
  60048. };
  60049. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60050. // Methods
  60051. get: function () {
  60052. return this._sourceMesh.receiveShadows;
  60053. },
  60054. enumerable: true,
  60055. configurable: true
  60056. });
  60057. Object.defineProperty(InstancedMesh.prototype, "material", {
  60058. get: function () {
  60059. return this._sourceMesh.material;
  60060. },
  60061. enumerable: true,
  60062. configurable: true
  60063. });
  60064. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60065. get: function () {
  60066. return this._sourceMesh.visibility;
  60067. },
  60068. enumerable: true,
  60069. configurable: true
  60070. });
  60071. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60072. get: function () {
  60073. return this._sourceMesh.skeleton;
  60074. },
  60075. enumerable: true,
  60076. configurable: true
  60077. });
  60078. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60079. get: function () {
  60080. return this._sourceMesh.renderingGroupId;
  60081. },
  60082. set: function (value) {
  60083. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60084. return;
  60085. }
  60086. //no-op with warning
  60087. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60088. },
  60089. enumerable: true,
  60090. configurable: true
  60091. });
  60092. /**
  60093. * Returns the total number of vertices (integer).
  60094. */
  60095. InstancedMesh.prototype.getTotalVertices = function () {
  60096. return this._sourceMesh.getTotalVertices();
  60097. };
  60098. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60099. get: function () {
  60100. return this._sourceMesh;
  60101. },
  60102. enumerable: true,
  60103. configurable: true
  60104. });
  60105. /**
  60106. * Is this node ready to be used/rendered
  60107. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60108. * @return {boolean} is it ready
  60109. */
  60110. InstancedMesh.prototype.isReady = function (completeCheck) {
  60111. if (completeCheck === void 0) { completeCheck = false; }
  60112. return this._sourceMesh.isReady(completeCheck, true);
  60113. };
  60114. /**
  60115. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60116. */
  60117. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60118. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60119. };
  60120. /**
  60121. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60122. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60123. * The `data` are either a numeric array either a Float32Array.
  60124. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60125. * 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).
  60126. * Note that a new underlying VertexBuffer object is created each call.
  60127. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60128. *
  60129. * Possible `kind` values :
  60130. * - BABYLON.VertexBuffer.PositionKind
  60131. * - BABYLON.VertexBuffer.UVKind
  60132. * - BABYLON.VertexBuffer.UV2Kind
  60133. * - BABYLON.VertexBuffer.UV3Kind
  60134. * - BABYLON.VertexBuffer.UV4Kind
  60135. * - BABYLON.VertexBuffer.UV5Kind
  60136. * - BABYLON.VertexBuffer.UV6Kind
  60137. * - BABYLON.VertexBuffer.ColorKind
  60138. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60139. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60140. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60141. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60142. *
  60143. * Returns the Mesh.
  60144. */
  60145. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60146. if (this.sourceMesh) {
  60147. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60148. }
  60149. return this.sourceMesh;
  60150. };
  60151. /**
  60152. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60153. * If the mesh has no geometry, it is simply returned as it is.
  60154. * The `data` are either a numeric array either a Float32Array.
  60155. * No new underlying VertexBuffer object is created.
  60156. * 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.
  60157. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60158. *
  60159. * Possible `kind` values :
  60160. * - BABYLON.VertexBuffer.PositionKind
  60161. * - BABYLON.VertexBuffer.UVKind
  60162. * - BABYLON.VertexBuffer.UV2Kind
  60163. * - BABYLON.VertexBuffer.UV3Kind
  60164. * - BABYLON.VertexBuffer.UV4Kind
  60165. * - BABYLON.VertexBuffer.UV5Kind
  60166. * - BABYLON.VertexBuffer.UV6Kind
  60167. * - BABYLON.VertexBuffer.ColorKind
  60168. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60169. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60170. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60171. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60172. *
  60173. * Returns the Mesh.
  60174. */
  60175. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60176. if (this.sourceMesh) {
  60177. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60178. }
  60179. return this.sourceMesh;
  60180. };
  60181. /**
  60182. * Sets the mesh indices.
  60183. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60184. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60185. * This method creates a new index buffer each call.
  60186. * Returns the Mesh.
  60187. */
  60188. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60189. if (totalVertices === void 0) { totalVertices = null; }
  60190. if (this.sourceMesh) {
  60191. this.sourceMesh.setIndices(indices, totalVertices);
  60192. }
  60193. return this.sourceMesh;
  60194. };
  60195. /**
  60196. * Boolean : True if the mesh owns the requested kind of data.
  60197. */
  60198. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60199. return this._sourceMesh.isVerticesDataPresent(kind);
  60200. };
  60201. /**
  60202. * Returns an array of indices (IndicesArray).
  60203. */
  60204. InstancedMesh.prototype.getIndices = function () {
  60205. return this._sourceMesh.getIndices();
  60206. };
  60207. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60208. get: function () {
  60209. return this._sourceMesh._positions;
  60210. },
  60211. enumerable: true,
  60212. configurable: true
  60213. });
  60214. /**
  60215. * Sets a new updated BoundingInfo to the mesh.
  60216. * Returns the mesh.
  60217. */
  60218. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60219. var meshBB = this._sourceMesh.getBoundingInfo();
  60220. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60221. this._updateBoundingInfo();
  60222. return this;
  60223. };
  60224. /** @hidden */
  60225. InstancedMesh.prototype._preActivate = function () {
  60226. if (this._currentLOD) {
  60227. this._currentLOD._preActivate();
  60228. }
  60229. return this;
  60230. };
  60231. /** @hidden */
  60232. InstancedMesh.prototype._activate = function (renderId) {
  60233. if (this._currentLOD) {
  60234. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60235. }
  60236. return this;
  60237. };
  60238. /**
  60239. * Returns the current associated LOD AbstractMesh.
  60240. */
  60241. InstancedMesh.prototype.getLOD = function (camera) {
  60242. if (!camera) {
  60243. return this;
  60244. }
  60245. var boundingInfo = this.getBoundingInfo();
  60246. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60247. if (this._currentLOD === this.sourceMesh) {
  60248. return this;
  60249. }
  60250. return this._currentLOD;
  60251. };
  60252. /** @hidden */
  60253. InstancedMesh.prototype._syncSubMeshes = function () {
  60254. this.releaseSubMeshes();
  60255. if (this._sourceMesh.subMeshes) {
  60256. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60257. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60258. }
  60259. }
  60260. return this;
  60261. };
  60262. /** @hidden */
  60263. InstancedMesh.prototype._generatePointsArray = function () {
  60264. return this._sourceMesh._generatePointsArray();
  60265. };
  60266. /**
  60267. * Creates a new InstancedMesh from the current mesh.
  60268. * - name (string) : the cloned mesh name
  60269. * - newParent (optional Node) : the optional Node to parent the clone to.
  60270. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60271. *
  60272. * Returns the clone.
  60273. */
  60274. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60275. var result = this._sourceMesh.createInstance(name);
  60276. // Deep copy
  60277. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60278. // Bounding info
  60279. this.refreshBoundingInfo();
  60280. // Parent
  60281. if (newParent) {
  60282. result.parent = newParent;
  60283. }
  60284. if (!doNotCloneChildren) {
  60285. // Children
  60286. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60287. var mesh = this.getScene().meshes[index];
  60288. if (mesh.parent === this) {
  60289. mesh.clone(mesh.name, result);
  60290. }
  60291. }
  60292. }
  60293. result.computeWorldMatrix(true);
  60294. return result;
  60295. };
  60296. /**
  60297. * Disposes the InstancedMesh.
  60298. * Returns nothing.
  60299. */
  60300. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60301. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60302. // Remove from mesh
  60303. var index = this._sourceMesh.instances.indexOf(this);
  60304. this._sourceMesh.instances.splice(index, 1);
  60305. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60306. };
  60307. return InstancedMesh;
  60308. }(BABYLON.AbstractMesh));
  60309. BABYLON.InstancedMesh = InstancedMesh;
  60310. })(BABYLON || (BABYLON = {}));
  60311. //# sourceMappingURL=babylon.instancedMesh.js.map
  60312. var BABYLON;
  60313. (function (BABYLON) {
  60314. var LinesMesh = /** @class */ (function (_super) {
  60315. __extends(LinesMesh, _super);
  60316. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60317. if (scene === void 0) { scene = null; }
  60318. if (parent === void 0) { parent = null; }
  60319. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60320. _this.useVertexColor = useVertexColor;
  60321. _this.useVertexAlpha = useVertexAlpha;
  60322. _this.color = new BABYLON.Color3(1, 1, 1);
  60323. _this.alpha = 1;
  60324. if (source) {
  60325. _this.color = source.color.clone();
  60326. _this.alpha = source.alpha;
  60327. _this.useVertexColor = source.useVertexColor;
  60328. _this.useVertexAlpha = source.useVertexAlpha;
  60329. }
  60330. _this._intersectionThreshold = 0.1;
  60331. var defines = [];
  60332. var options = {
  60333. attributes: [BABYLON.VertexBuffer.PositionKind],
  60334. uniforms: ["world", "viewProjection"],
  60335. needAlphaBlending: true,
  60336. defines: defines
  60337. };
  60338. if (useVertexAlpha === false) {
  60339. options.needAlphaBlending = false;
  60340. }
  60341. if (!useVertexColor) {
  60342. options.uniforms.push("color");
  60343. }
  60344. else {
  60345. options.defines.push("#define VERTEXCOLOR");
  60346. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60347. }
  60348. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60349. return _this;
  60350. }
  60351. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60352. /**
  60353. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60354. * This margin is expressed in world space coordinates, so its value may vary.
  60355. * Default value is 0.1
  60356. * @returns the intersection Threshold value.
  60357. */
  60358. get: function () {
  60359. return this._intersectionThreshold;
  60360. },
  60361. /**
  60362. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60363. * This margin is expressed in world space coordinates, so its value may vary.
  60364. * @param value the new threshold to apply
  60365. */
  60366. set: function (value) {
  60367. if (this._intersectionThreshold === value) {
  60368. return;
  60369. }
  60370. this._intersectionThreshold = value;
  60371. if (this.geometry) {
  60372. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60373. }
  60374. },
  60375. enumerable: true,
  60376. configurable: true
  60377. });
  60378. /**
  60379. * Returns the string "LineMesh"
  60380. */
  60381. LinesMesh.prototype.getClassName = function () {
  60382. return "LinesMesh";
  60383. };
  60384. Object.defineProperty(LinesMesh.prototype, "material", {
  60385. /**
  60386. * @hidden
  60387. */
  60388. get: function () {
  60389. return this._colorShader;
  60390. },
  60391. /**
  60392. * @hidden
  60393. */
  60394. set: function (value) {
  60395. // Do nothing
  60396. },
  60397. enumerable: true,
  60398. configurable: true
  60399. });
  60400. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60401. /**
  60402. * @hidden
  60403. */
  60404. get: function () {
  60405. return false;
  60406. },
  60407. enumerable: true,
  60408. configurable: true
  60409. });
  60410. LinesMesh.prototype.createInstance = function (name) {
  60411. throw new Error("LinesMeshes do not support createInstance.");
  60412. };
  60413. /** @hidden */
  60414. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60415. if (!this._geometry) {
  60416. return this;
  60417. }
  60418. // VBOs
  60419. this._geometry._bind(this._colorShader.getEffect());
  60420. // Color
  60421. if (!this.useVertexColor) {
  60422. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60423. }
  60424. return this;
  60425. };
  60426. /** @hidden */
  60427. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60428. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60429. return this;
  60430. }
  60431. var engine = this.getScene().getEngine();
  60432. // Draw order
  60433. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60434. return this;
  60435. };
  60436. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60437. this._colorShader.dispose();
  60438. _super.prototype.dispose.call(this, doNotRecurse);
  60439. };
  60440. /**
  60441. * Returns a new LineMesh object cloned from the current one.
  60442. */
  60443. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60444. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60445. };
  60446. return LinesMesh;
  60447. }(BABYLON.Mesh));
  60448. BABYLON.LinesMesh = LinesMesh;
  60449. })(BABYLON || (BABYLON = {}));
  60450. //# sourceMappingURL=babylon.linesMesh.js.map
  60451. var BABYLON;
  60452. (function (BABYLON) {
  60453. /**
  60454. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60455. * The underlying implementation relies on an associative array to ensure the best performances.
  60456. * The value can be anything including 'null' but except 'undefined'
  60457. */
  60458. var StringDictionary = /** @class */ (function () {
  60459. function StringDictionary() {
  60460. this._count = 0;
  60461. this._data = {};
  60462. }
  60463. /**
  60464. * This will clear this dictionary and copy the content from the 'source' one.
  60465. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60466. * @param source the dictionary to take the content from and copy to this dictionary
  60467. */
  60468. StringDictionary.prototype.copyFrom = function (source) {
  60469. var _this = this;
  60470. this.clear();
  60471. source.forEach(function (t, v) { return _this.add(t, v); });
  60472. };
  60473. /**
  60474. * Get a value based from its key
  60475. * @param key the given key to get the matching value from
  60476. * @return the value if found, otherwise undefined is returned
  60477. */
  60478. StringDictionary.prototype.get = function (key) {
  60479. var val = this._data[key];
  60480. if (val !== undefined) {
  60481. return val;
  60482. }
  60483. return undefined;
  60484. };
  60485. /**
  60486. * Get a value from its key or add it if it doesn't exist.
  60487. * This method will ensure you that a given key/data will be present in the dictionary.
  60488. * @param key the given key to get the matching value from
  60489. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60490. * The factory will only be invoked if there's no data for the given key.
  60491. * @return the value corresponding to the key.
  60492. */
  60493. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60494. var val = this.get(key);
  60495. if (val !== undefined) {
  60496. return val;
  60497. }
  60498. val = factory(key);
  60499. if (val) {
  60500. this.add(key, val);
  60501. }
  60502. return val;
  60503. };
  60504. /**
  60505. * Get a value from its key if present in the dictionary otherwise add it
  60506. * @param key the key to get the value from
  60507. * @param val if there's no such key/value pair in the dictionary add it with this value
  60508. * @return the value corresponding to the key
  60509. */
  60510. StringDictionary.prototype.getOrAdd = function (key, val) {
  60511. var curVal = this.get(key);
  60512. if (curVal !== undefined) {
  60513. return curVal;
  60514. }
  60515. this.add(key, val);
  60516. return val;
  60517. };
  60518. /**
  60519. * Check if there's a given key in the dictionary
  60520. * @param key the key to check for
  60521. * @return true if the key is present, false otherwise
  60522. */
  60523. StringDictionary.prototype.contains = function (key) {
  60524. return this._data[key] !== undefined;
  60525. };
  60526. /**
  60527. * Add a new key and its corresponding value
  60528. * @param key the key to add
  60529. * @param value the value corresponding to the key
  60530. * @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
  60531. */
  60532. StringDictionary.prototype.add = function (key, value) {
  60533. if (this._data[key] !== undefined) {
  60534. return false;
  60535. }
  60536. this._data[key] = value;
  60537. ++this._count;
  60538. return true;
  60539. };
  60540. StringDictionary.prototype.set = function (key, value) {
  60541. if (this._data[key] === undefined) {
  60542. return false;
  60543. }
  60544. this._data[key] = value;
  60545. return true;
  60546. };
  60547. /**
  60548. * Get the element of the given key and remove it from the dictionary
  60549. * @param key
  60550. */
  60551. StringDictionary.prototype.getAndRemove = function (key) {
  60552. var val = this.get(key);
  60553. if (val !== undefined) {
  60554. delete this._data[key];
  60555. --this._count;
  60556. return val;
  60557. }
  60558. return null;
  60559. };
  60560. /**
  60561. * Remove a key/value from the dictionary.
  60562. * @param key the key to remove
  60563. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60564. */
  60565. StringDictionary.prototype.remove = function (key) {
  60566. if (this.contains(key)) {
  60567. delete this._data[key];
  60568. --this._count;
  60569. return true;
  60570. }
  60571. return false;
  60572. };
  60573. /**
  60574. * Clear the whole content of the dictionary
  60575. */
  60576. StringDictionary.prototype.clear = function () {
  60577. this._data = {};
  60578. this._count = 0;
  60579. };
  60580. Object.defineProperty(StringDictionary.prototype, "count", {
  60581. get: function () {
  60582. return this._count;
  60583. },
  60584. enumerable: true,
  60585. configurable: true
  60586. });
  60587. /**
  60588. * Execute a callback on each key/val of the dictionary.
  60589. * Note that you can remove any element in this dictionary in the callback implementation
  60590. * @param callback the callback to execute on a given key/value pair
  60591. */
  60592. StringDictionary.prototype.forEach = function (callback) {
  60593. for (var cur in this._data) {
  60594. var val = this._data[cur];
  60595. callback(cur, val);
  60596. }
  60597. };
  60598. /**
  60599. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60600. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60601. * Note that you can remove any element in this dictionary in the callback implementation
  60602. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60603. */
  60604. StringDictionary.prototype.first = function (callback) {
  60605. for (var cur in this._data) {
  60606. var val = this._data[cur];
  60607. var res = callback(cur, val);
  60608. if (res) {
  60609. return res;
  60610. }
  60611. }
  60612. return null;
  60613. };
  60614. return StringDictionary;
  60615. }());
  60616. BABYLON.StringDictionary = StringDictionary;
  60617. })(BABYLON || (BABYLON = {}));
  60618. //# sourceMappingURL=babylon.stringDictionary.js.map
  60619. var BABYLON;
  60620. (function (BABYLON) {
  60621. var Debug;
  60622. (function (Debug) {
  60623. /**
  60624. * Class used to render a debug view of a given skeleton
  60625. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60626. */
  60627. var SkeletonViewer = /** @class */ (function () {
  60628. /**
  60629. * Creates a new SkeletonViewer
  60630. * @param skeleton defines the skeleton to render
  60631. * @param mesh defines the mesh attached to the skeleton
  60632. * @param scene defines the hosting scene
  60633. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60634. * @param renderingGroupId defines the rendering group id to use with the viewer
  60635. */
  60636. function SkeletonViewer(
  60637. /** defines the skeleton to render */
  60638. skeleton,
  60639. /** defines the mesh attached to the skeleton */
  60640. mesh, scene,
  60641. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60642. autoUpdateBonesMatrices,
  60643. /** defines the rendering group id to use with the viewer */
  60644. renderingGroupId) {
  60645. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60646. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60647. this.skeleton = skeleton;
  60648. this.mesh = mesh;
  60649. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60650. this.renderingGroupId = renderingGroupId;
  60651. /** Gets or sets the color used to render the skeleton */
  60652. this.color = BABYLON.Color3.White();
  60653. this._debugLines = new Array();
  60654. this._isEnabled = false;
  60655. this._scene = scene;
  60656. this.update();
  60657. this._renderFunction = this.update.bind(this);
  60658. }
  60659. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60660. get: function () {
  60661. return this._isEnabled;
  60662. },
  60663. /** Gets or sets a boolean indicating if the viewer is enabled */
  60664. set: function (value) {
  60665. if (this._isEnabled === value) {
  60666. return;
  60667. }
  60668. this._isEnabled = value;
  60669. if (value) {
  60670. this._scene.registerBeforeRender(this._renderFunction);
  60671. }
  60672. else {
  60673. this._scene.unregisterBeforeRender(this._renderFunction);
  60674. }
  60675. },
  60676. enumerable: true,
  60677. configurable: true
  60678. });
  60679. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60680. if (x === void 0) { x = 0; }
  60681. if (y === void 0) { y = 0; }
  60682. if (z === void 0) { z = 0; }
  60683. var tmat = BABYLON.Tmp.Matrix[0];
  60684. var parentBone = bone.getParent();
  60685. tmat.copyFrom(bone.getLocalMatrix());
  60686. if (x !== 0 || y !== 0 || z !== 0) {
  60687. var tmat2 = BABYLON.Tmp.Matrix[1];
  60688. BABYLON.Matrix.IdentityToRef(tmat2);
  60689. tmat2.m[12] = x;
  60690. tmat2.m[13] = y;
  60691. tmat2.m[14] = z;
  60692. tmat2.multiplyToRef(tmat, tmat);
  60693. }
  60694. if (parentBone) {
  60695. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60696. }
  60697. tmat.multiplyToRef(meshMat, tmat);
  60698. position.x = tmat.m[12];
  60699. position.y = tmat.m[13];
  60700. position.z = tmat.m[14];
  60701. };
  60702. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60703. var len = bones.length;
  60704. var meshPos = this.mesh.position;
  60705. for (var i = 0; i < len; i++) {
  60706. var bone = bones[i];
  60707. var points = this._debugLines[i];
  60708. if (!points) {
  60709. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60710. this._debugLines[i] = points;
  60711. }
  60712. this._getBonePosition(points[0], bone, meshMat);
  60713. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60714. points[0].subtractInPlace(meshPos);
  60715. points[1].subtractInPlace(meshPos);
  60716. }
  60717. };
  60718. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60719. var len = bones.length;
  60720. var boneNum = 0;
  60721. var meshPos = this.mesh.position;
  60722. for (var i = len - 1; i >= 0; i--) {
  60723. var childBone = bones[i];
  60724. var parentBone = childBone.getParent();
  60725. if (!parentBone) {
  60726. continue;
  60727. }
  60728. var points = this._debugLines[boneNum];
  60729. if (!points) {
  60730. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60731. this._debugLines[boneNum] = points;
  60732. }
  60733. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60734. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60735. points[0].subtractInPlace(meshPos);
  60736. points[1].subtractInPlace(meshPos);
  60737. boneNum++;
  60738. }
  60739. };
  60740. /** Update the viewer to sync with current skeleton state */
  60741. SkeletonViewer.prototype.update = function () {
  60742. if (this.autoUpdateBonesMatrices) {
  60743. this.skeleton.computeAbsoluteTransforms();
  60744. }
  60745. if (this.skeleton.bones[0].length === undefined) {
  60746. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60747. }
  60748. else {
  60749. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60750. }
  60751. if (!this._debugMesh) {
  60752. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60753. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60754. }
  60755. else {
  60756. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60757. }
  60758. this._debugMesh.position.copyFrom(this.mesh.position);
  60759. this._debugMesh.color = this.color;
  60760. };
  60761. /** Release associated resources */
  60762. SkeletonViewer.prototype.dispose = function () {
  60763. if (this._debugMesh) {
  60764. this.isEnabled = false;
  60765. this._debugMesh.dispose();
  60766. this._debugMesh = null;
  60767. }
  60768. };
  60769. return SkeletonViewer;
  60770. }());
  60771. Debug.SkeletonViewer = SkeletonViewer;
  60772. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60773. })(BABYLON || (BABYLON = {}));
  60774. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60775. /**
  60776. * Module Debug contains the (visual) components to debug a scene correctly
  60777. */
  60778. var BABYLON;
  60779. (function (BABYLON) {
  60780. var Debug;
  60781. (function (Debug) {
  60782. /**
  60783. * The Axes viewer will show 3 axes in a specific point in space
  60784. */
  60785. var AxesViewer = /** @class */ (function () {
  60786. /**
  60787. * Creates a new AxesViewer
  60788. * @param scene defines the hosting scene
  60789. * @param scaleLines defines a number used to scale line length (1 by default)
  60790. */
  60791. function AxesViewer(scene, scaleLines) {
  60792. if (scaleLines === void 0) { scaleLines = 1; }
  60793. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60794. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60795. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60796. /**
  60797. * Gets or sets a number used to scale line length
  60798. */
  60799. this.scaleLines = 1;
  60800. this.scaleLines = scaleLines;
  60801. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60802. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60803. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60804. this._xmesh.renderingGroupId = 2;
  60805. this._ymesh.renderingGroupId = 2;
  60806. this._zmesh.renderingGroupId = 2;
  60807. this._xmesh.material.checkReadyOnlyOnce = true;
  60808. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60809. this._ymesh.material.checkReadyOnlyOnce = true;
  60810. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60811. this._zmesh.material.checkReadyOnlyOnce = true;
  60812. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60813. this.scene = scene;
  60814. }
  60815. /**
  60816. * Force the viewer to update
  60817. * @param position defines the position of the viewer
  60818. * @param xaxis defines the x axis of the viewer
  60819. * @param yaxis defines the y axis of the viewer
  60820. * @param zaxis defines the z axis of the viewer
  60821. */
  60822. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60823. var scaleLines = this.scaleLines;
  60824. if (this._xmesh) {
  60825. this._xmesh.position.copyFrom(position);
  60826. }
  60827. if (this._ymesh) {
  60828. this._ymesh.position.copyFrom(position);
  60829. }
  60830. if (this._zmesh) {
  60831. this._zmesh.position.copyFrom(position);
  60832. }
  60833. var point2 = this._xline[1];
  60834. point2.x = xaxis.x * scaleLines;
  60835. point2.y = xaxis.y * scaleLines;
  60836. point2.z = xaxis.z * scaleLines;
  60837. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60838. point2 = this._yline[1];
  60839. point2.x = yaxis.x * scaleLines;
  60840. point2.y = yaxis.y * scaleLines;
  60841. point2.z = yaxis.z * scaleLines;
  60842. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60843. point2 = this._zline[1];
  60844. point2.x = zaxis.x * scaleLines;
  60845. point2.y = zaxis.y * scaleLines;
  60846. point2.z = zaxis.z * scaleLines;
  60847. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60848. };
  60849. /** Releases resources */
  60850. AxesViewer.prototype.dispose = function () {
  60851. if (this._xmesh) {
  60852. this._xmesh.dispose();
  60853. }
  60854. if (this._ymesh) {
  60855. this._ymesh.dispose();
  60856. }
  60857. if (this._zmesh) {
  60858. this._zmesh.dispose();
  60859. }
  60860. this._xmesh = null;
  60861. this._ymesh = null;
  60862. this._zmesh = null;
  60863. this.scene = null;
  60864. };
  60865. return AxesViewer;
  60866. }());
  60867. Debug.AxesViewer = AxesViewer;
  60868. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60869. })(BABYLON || (BABYLON = {}));
  60870. //# sourceMappingURL=babylon.axesViewer.js.map
  60871. var BABYLON;
  60872. (function (BABYLON) {
  60873. var Debug;
  60874. (function (Debug) {
  60875. /**
  60876. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60877. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60878. */
  60879. var BoneAxesViewer = /** @class */ (function (_super) {
  60880. __extends(BoneAxesViewer, _super);
  60881. /**
  60882. * Creates a new BoneAxesViewer
  60883. * @param scene defines the hosting scene
  60884. * @param bone defines the target bone
  60885. * @param mesh defines the target mesh
  60886. * @param scaleLines defines a scaling factor for line length (1 by default)
  60887. */
  60888. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60889. if (scaleLines === void 0) { scaleLines = 1; }
  60890. var _this = _super.call(this, scene, scaleLines) || this;
  60891. /** Gets current position */
  60892. _this.pos = BABYLON.Vector3.Zero();
  60893. /** Gets direction of X axis */
  60894. _this.xaxis = BABYLON.Vector3.Zero();
  60895. /** Gets direction of Y axis */
  60896. _this.yaxis = BABYLON.Vector3.Zero();
  60897. /** Gets direction of Z axis */
  60898. _this.zaxis = BABYLON.Vector3.Zero();
  60899. _this.mesh = mesh;
  60900. _this.bone = bone;
  60901. return _this;
  60902. }
  60903. /**
  60904. * Force the viewer to update
  60905. */
  60906. BoneAxesViewer.prototype.update = function () {
  60907. if (!this.mesh || !this.bone) {
  60908. return;
  60909. }
  60910. var bone = this.bone;
  60911. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60912. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60913. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60914. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60915. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60916. };
  60917. /** Releases resources */
  60918. BoneAxesViewer.prototype.dispose = function () {
  60919. if (this.mesh) {
  60920. this.mesh = null;
  60921. this.bone = null;
  60922. _super.prototype.dispose.call(this);
  60923. }
  60924. };
  60925. return BoneAxesViewer;
  60926. }(Debug.AxesViewer));
  60927. Debug.BoneAxesViewer = BoneAxesViewer;
  60928. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60929. })(BABYLON || (BABYLON = {}));
  60930. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60931. var BABYLON;
  60932. (function (BABYLON) {
  60933. var RayHelper = /** @class */ (function () {
  60934. function RayHelper(ray) {
  60935. this.ray = ray;
  60936. }
  60937. RayHelper.CreateAndShow = function (ray, scene, color) {
  60938. var helper = new RayHelper(ray);
  60939. helper.show(scene, color);
  60940. return helper;
  60941. };
  60942. RayHelper.prototype.show = function (scene, color) {
  60943. if (!this._renderFunction && this.ray) {
  60944. var ray = this.ray;
  60945. this._renderFunction = this._render.bind(this);
  60946. this._scene = scene;
  60947. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60948. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60949. if (this._renderFunction) {
  60950. this._scene.registerBeforeRender(this._renderFunction);
  60951. }
  60952. }
  60953. if (color && this._renderLine) {
  60954. this._renderLine.color.copyFrom(color);
  60955. }
  60956. };
  60957. RayHelper.prototype.hide = function () {
  60958. if (this._renderFunction && this._scene) {
  60959. this._scene.unregisterBeforeRender(this._renderFunction);
  60960. this._scene = null;
  60961. this._renderFunction = null;
  60962. if (this._renderLine) {
  60963. this._renderLine.dispose();
  60964. this._renderLine = null;
  60965. }
  60966. this._renderPoints = [];
  60967. }
  60968. };
  60969. RayHelper.prototype._render = function () {
  60970. var ray = this.ray;
  60971. if (!ray) {
  60972. return;
  60973. }
  60974. var point = this._renderPoints[1];
  60975. var len = Math.min(ray.length, 1000000);
  60976. point.copyFrom(ray.direction);
  60977. point.scaleInPlace(len);
  60978. point.addInPlace(ray.origin);
  60979. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60980. };
  60981. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60982. this._attachedToMesh = mesh;
  60983. var ray = this.ray;
  60984. if (!ray) {
  60985. return;
  60986. }
  60987. if (!ray.direction) {
  60988. ray.direction = BABYLON.Vector3.Zero();
  60989. }
  60990. if (!ray.origin) {
  60991. ray.origin = BABYLON.Vector3.Zero();
  60992. }
  60993. if (length) {
  60994. ray.length = length;
  60995. }
  60996. if (!meshSpaceOrigin) {
  60997. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60998. }
  60999. if (!meshSpaceDirection) {
  61000. // -1 so that this will work with Mesh.lookAt
  61001. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61002. }
  61003. if (!this._meshSpaceDirection) {
  61004. this._meshSpaceDirection = meshSpaceDirection.clone();
  61005. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61006. }
  61007. else {
  61008. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61009. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61010. }
  61011. if (!this._updateToMeshFunction) {
  61012. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61013. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61014. }
  61015. this._updateToMesh();
  61016. };
  61017. RayHelper.prototype.detachFromMesh = function () {
  61018. if (this._attachedToMesh) {
  61019. if (this._updateToMeshFunction) {
  61020. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61021. }
  61022. this._attachedToMesh = null;
  61023. this._updateToMeshFunction = null;
  61024. }
  61025. };
  61026. RayHelper.prototype._updateToMesh = function () {
  61027. var ray = this.ray;
  61028. if (!this._attachedToMesh || !ray) {
  61029. return;
  61030. }
  61031. if (this._attachedToMesh._isDisposed) {
  61032. this.detachFromMesh();
  61033. return;
  61034. }
  61035. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61036. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61037. };
  61038. RayHelper.prototype.dispose = function () {
  61039. this.hide();
  61040. this.detachFromMesh();
  61041. this.ray = null;
  61042. };
  61043. return RayHelper;
  61044. }());
  61045. BABYLON.RayHelper = RayHelper;
  61046. })(BABYLON || (BABYLON = {}));
  61047. //# sourceMappingURL=babylon.rayHelper.js.map
  61048. var BABYLON;
  61049. (function (BABYLON) {
  61050. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  61051. get: function () {
  61052. if (!this._debugLayer) {
  61053. this._debugLayer = new DebugLayer(this);
  61054. }
  61055. return this._debugLayer;
  61056. },
  61057. enumerable: true,
  61058. configurable: true
  61059. });
  61060. var DebugLayer = /** @class */ (function () {
  61061. function DebugLayer(scene) {
  61062. var _this = this;
  61063. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61064. this.onPropertyChangedObservable = new BABYLON.Observable();
  61065. this._scene = scene;
  61066. this._scene.onDisposeObservable.add(function () {
  61067. // Debug layer
  61068. if (_this._scene._debugLayer) {
  61069. _this._scene._debugLayer.hide();
  61070. }
  61071. });
  61072. }
  61073. /** Creates the inspector window. */
  61074. DebugLayer.prototype._createInspector = function (config) {
  61075. if (config === void 0) { config = {}; }
  61076. var popup = config.popup || false;
  61077. var initialTab = config.initialTab || 0;
  61078. var parentElement = config.parentElement || null;
  61079. if (!this._inspector) {
  61080. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61081. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61082. } // else nothing to do as instance is already created
  61083. };
  61084. DebugLayer.prototype.isVisible = function () {
  61085. if (!this._inspector) {
  61086. return false;
  61087. }
  61088. return true;
  61089. };
  61090. DebugLayer.prototype.hide = function () {
  61091. if (this._inspector) {
  61092. try {
  61093. this._inspector.dispose();
  61094. }
  61095. catch (e) {
  61096. // If the inspector has been removed directly from the inspector tool
  61097. }
  61098. this.onPropertyChangedObservable.clear();
  61099. this._inspector = null;
  61100. }
  61101. };
  61102. /**
  61103. *
  61104. * Launch the debugLayer.
  61105. *
  61106. * initialTab:
  61107. * | Value | Tab Name |
  61108. * | --- | --- |
  61109. * | 0 | Scene |
  61110. * | 1 | Console |
  61111. * | 2 | Stats |
  61112. * | 3 | Textures |
  61113. * | 4 | Mesh |
  61114. * | 5 | Light |
  61115. * | 6 | Material |
  61116. * | 7 | GLTF |
  61117. * | 8 | GUI |
  61118. * | 9 | Physics |
  61119. * | 10 | Camera |
  61120. * | 11 | Audio |
  61121. *
  61122. */
  61123. DebugLayer.prototype.show = function (config) {
  61124. if (config === void 0) { config = {}; }
  61125. if (typeof this.BJSINSPECTOR == 'undefined') {
  61126. // Load inspector and add it to the DOM
  61127. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61128. }
  61129. else {
  61130. // Otherwise creates the inspector
  61131. this._createInspector(config);
  61132. }
  61133. };
  61134. /**
  61135. * Gets the active tab
  61136. * @return the index of the active tab or -1 if the inspector is hidden
  61137. */
  61138. DebugLayer.prototype.getActiveTab = function () {
  61139. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  61140. };
  61141. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61142. return DebugLayer;
  61143. }());
  61144. BABYLON.DebugLayer = DebugLayer;
  61145. })(BABYLON || (BABYLON = {}));
  61146. //# sourceMappingURL=babylon.debugLayer.js.map
  61147. var BABYLON;
  61148. (function (BABYLON) {
  61149. var Debug;
  61150. (function (Debug) {
  61151. /**
  61152. * Used to show the physics impostor around the specific mesh
  61153. */
  61154. var PhysicsViewer = /** @class */ (function () {
  61155. /**
  61156. * Creates a new PhysicsViewer
  61157. * @param scene defines the hosting scene
  61158. */
  61159. function PhysicsViewer(scene) {
  61160. /** @hidden */
  61161. this._impostors = [];
  61162. /** @hidden */
  61163. this._meshes = [];
  61164. /** @hidden */
  61165. this._numMeshes = 0;
  61166. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61167. var physicEngine = this._scene.getPhysicsEngine();
  61168. if (physicEngine) {
  61169. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  61170. }
  61171. }
  61172. /** @hidden */
  61173. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61174. var plugin = this._physicsEnginePlugin;
  61175. for (var i = 0; i < this._numMeshes; i++) {
  61176. var impostor = this._impostors[i];
  61177. if (!impostor) {
  61178. continue;
  61179. }
  61180. if (impostor.isDisposed) {
  61181. this.hideImpostor(this._impostors[i--]);
  61182. }
  61183. else {
  61184. var mesh = this._meshes[i];
  61185. if (mesh && plugin) {
  61186. plugin.syncMeshWithImpostor(mesh, impostor);
  61187. }
  61188. }
  61189. }
  61190. };
  61191. /**
  61192. * Renders a specified physic impostor
  61193. * @param impostor defines the impostor to render
  61194. */
  61195. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61196. if (!this._scene) {
  61197. return;
  61198. }
  61199. for (var i = 0; i < this._numMeshes; i++) {
  61200. if (this._impostors[i] == impostor) {
  61201. return;
  61202. }
  61203. }
  61204. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61205. if (debugMesh) {
  61206. this._impostors[this._numMeshes] = impostor;
  61207. this._meshes[this._numMeshes] = debugMesh;
  61208. if (this._numMeshes === 0) {
  61209. this._renderFunction = this._updateDebugMeshes.bind(this);
  61210. this._scene.registerBeforeRender(this._renderFunction);
  61211. }
  61212. this._numMeshes++;
  61213. }
  61214. };
  61215. /**
  61216. * Hides a specified physic impostor
  61217. * @param impostor defines the impostor to hide
  61218. */
  61219. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61220. if (!impostor || !this._scene) {
  61221. return;
  61222. }
  61223. var removed = false;
  61224. for (var i = 0; i < this._numMeshes; i++) {
  61225. if (this._impostors[i] == impostor) {
  61226. var mesh = this._meshes[i];
  61227. if (!mesh) {
  61228. continue;
  61229. }
  61230. this._scene.removeMesh(mesh);
  61231. mesh.dispose();
  61232. this._numMeshes--;
  61233. if (this._numMeshes > 0) {
  61234. this._meshes[i] = this._meshes[this._numMeshes];
  61235. this._impostors[i] = this._impostors[this._numMeshes];
  61236. this._meshes[this._numMeshes] = null;
  61237. this._impostors[this._numMeshes] = null;
  61238. }
  61239. else {
  61240. this._meshes[0] = null;
  61241. this._impostors[0] = null;
  61242. }
  61243. removed = true;
  61244. break;
  61245. }
  61246. }
  61247. if (removed && this._numMeshes === 0) {
  61248. this._scene.unregisterBeforeRender(this._renderFunction);
  61249. }
  61250. };
  61251. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61252. if (!this._debugMaterial) {
  61253. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61254. this._debugMaterial.wireframe = true;
  61255. }
  61256. return this._debugMaterial;
  61257. };
  61258. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61259. if (!this._debugBoxMesh) {
  61260. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61261. this._debugBoxMesh.renderingGroupId = 1;
  61262. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61263. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61264. scene.removeMesh(this._debugBoxMesh);
  61265. }
  61266. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61267. };
  61268. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61269. if (!this._debugSphereMesh) {
  61270. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61271. this._debugSphereMesh.renderingGroupId = 1;
  61272. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61273. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61274. scene.removeMesh(this._debugSphereMesh);
  61275. }
  61276. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61277. };
  61278. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61279. var mesh = null;
  61280. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61281. mesh = this._getDebugBoxMesh(scene);
  61282. impostor.getBoxSizeToRef(mesh.scaling);
  61283. }
  61284. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61285. mesh = this._getDebugSphereMesh(scene);
  61286. var radius = impostor.getRadius();
  61287. mesh.scaling.x = radius * 2;
  61288. mesh.scaling.y = radius * 2;
  61289. mesh.scaling.z = radius * 2;
  61290. }
  61291. return mesh;
  61292. };
  61293. /** Releases all resources */
  61294. PhysicsViewer.prototype.dispose = function () {
  61295. for (var i = 0; i < this._numMeshes; i++) {
  61296. this.hideImpostor(this._impostors[i]);
  61297. }
  61298. if (this._debugBoxMesh) {
  61299. this._debugBoxMesh.dispose();
  61300. }
  61301. if (this._debugSphereMesh) {
  61302. this._debugSphereMesh.dispose();
  61303. }
  61304. if (this._debugMaterial) {
  61305. this._debugMaterial.dispose();
  61306. }
  61307. this._impostors.length = 0;
  61308. this._scene = null;
  61309. this._physicsEnginePlugin = null;
  61310. };
  61311. return PhysicsViewer;
  61312. }());
  61313. Debug.PhysicsViewer = PhysicsViewer;
  61314. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61315. })(BABYLON || (BABYLON = {}));
  61316. //# sourceMappingURL=babylon.physicsViewer.js.map
  61317. var BABYLON;
  61318. (function (BABYLON) {
  61319. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  61320. get: function () {
  61321. return this._forceShowBoundingBoxes || false;
  61322. },
  61323. set: function (value) {
  61324. this._forceShowBoundingBoxes = value;
  61325. // Lazyly creates a BB renderer if needed.
  61326. if (value) {
  61327. this.getBoundingBoxRenderer();
  61328. }
  61329. },
  61330. enumerable: true,
  61331. configurable: true
  61332. });
  61333. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  61334. if (!this._boundingBoxRenderer) {
  61335. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  61336. }
  61337. return this._boundingBoxRenderer;
  61338. };
  61339. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  61340. get: function () {
  61341. return this._showBoundingBox || false;
  61342. },
  61343. set: function (value) {
  61344. this._showBoundingBox = value;
  61345. // Lazyly creates a BB renderer if needed.
  61346. if (value) {
  61347. this.getScene().getBoundingBoxRenderer();
  61348. }
  61349. },
  61350. enumerable: true,
  61351. configurable: true
  61352. });
  61353. var BoundingBoxRenderer = /** @class */ (function () {
  61354. function BoundingBoxRenderer(scene) {
  61355. /**
  61356. * The component name helpfull to identify the component in the list of scene components.
  61357. */
  61358. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  61359. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61360. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61361. this.showBackLines = true;
  61362. this.renderList = new BABYLON.SmartArray(32);
  61363. this._vertexBuffers = {};
  61364. this.scene = scene;
  61365. scene._addComponent(this);
  61366. }
  61367. /**
  61368. * Registers the component in a given scene
  61369. */
  61370. BoundingBoxRenderer.prototype.register = function () {
  61371. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  61372. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  61373. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  61374. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  61375. };
  61376. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  61377. if (mesh.showSubMeshesBoundingBox) {
  61378. var boundingInfo = subMesh.getBoundingInfo();
  61379. if (boundingInfo !== null && boundingInfo !== undefined) {
  61380. this.renderList.push(boundingInfo.boundingBox);
  61381. }
  61382. }
  61383. };
  61384. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  61385. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  61386. var boundingInfo = sourceMesh.getBoundingInfo();
  61387. this.renderList.push(boundingInfo.boundingBox);
  61388. }
  61389. };
  61390. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61391. if (this._colorShader) {
  61392. return;
  61393. }
  61394. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  61395. attributes: [BABYLON.VertexBuffer.PositionKind],
  61396. uniforms: ["world", "viewProjection", "color"]
  61397. });
  61398. var engine = this.scene.getEngine();
  61399. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61400. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61401. this._createIndexBuffer();
  61402. };
  61403. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61404. var engine = this.scene.getEngine();
  61405. 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]);
  61406. };
  61407. /**
  61408. * Rebuilds the elements related to this component in case of
  61409. * context lost for instance.
  61410. */
  61411. BoundingBoxRenderer.prototype.rebuild = function () {
  61412. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61413. if (vb) {
  61414. vb._rebuild();
  61415. }
  61416. this._createIndexBuffer();
  61417. };
  61418. BoundingBoxRenderer.prototype.reset = function () {
  61419. this.renderList.reset();
  61420. };
  61421. BoundingBoxRenderer.prototype.render = function () {
  61422. if (this.renderList.length === 0) {
  61423. return;
  61424. }
  61425. this._prepareRessources();
  61426. if (!this._colorShader.isReady()) {
  61427. return;
  61428. }
  61429. var engine = this.scene.getEngine();
  61430. engine.setDepthWrite(false);
  61431. this._colorShader._preBind();
  61432. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61433. var boundingBox = this.renderList.data[boundingBoxIndex];
  61434. var min = boundingBox.minimum;
  61435. var max = boundingBox.maximum;
  61436. var diff = max.subtract(min);
  61437. var median = min.add(diff.scale(0.5));
  61438. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61439. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61440. .multiply(boundingBox.getWorldMatrix());
  61441. // VBOs
  61442. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61443. if (this.showBackLines) {
  61444. // Back
  61445. engine.setDepthFunctionToGreaterOrEqual();
  61446. this.scene.resetCachedMaterial();
  61447. this._colorShader.setColor4("color", this.backColor.toColor4());
  61448. this._colorShader.bind(worldMatrix);
  61449. // Draw order
  61450. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61451. }
  61452. // Front
  61453. engine.setDepthFunctionToLess();
  61454. this.scene.resetCachedMaterial();
  61455. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61456. this._colorShader.bind(worldMatrix);
  61457. // Draw order
  61458. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61459. }
  61460. this._colorShader.unbind();
  61461. engine.setDepthFunctionToLessOrEqual();
  61462. engine.setDepthWrite(true);
  61463. };
  61464. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61465. this._prepareRessources();
  61466. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61467. return;
  61468. }
  61469. var engine = this.scene.getEngine();
  61470. engine.setDepthWrite(false);
  61471. engine.setColorWrite(false);
  61472. this._colorShader._preBind();
  61473. var boundingBox = mesh._boundingInfo.boundingBox;
  61474. var min = boundingBox.minimum;
  61475. var max = boundingBox.maximum;
  61476. var diff = max.subtract(min);
  61477. var median = min.add(diff.scale(0.5));
  61478. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61479. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61480. .multiply(boundingBox.getWorldMatrix());
  61481. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61482. engine.setDepthFunctionToLess();
  61483. this.scene.resetCachedMaterial();
  61484. this._colorShader.bind(worldMatrix);
  61485. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61486. this._colorShader.unbind();
  61487. engine.setDepthFunctionToLessOrEqual();
  61488. engine.setDepthWrite(true);
  61489. engine.setColorWrite(true);
  61490. };
  61491. BoundingBoxRenderer.prototype.dispose = function () {
  61492. if (!this._colorShader) {
  61493. return;
  61494. }
  61495. this.renderList.dispose();
  61496. this._colorShader.dispose();
  61497. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61498. if (buffer) {
  61499. buffer.dispose();
  61500. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61501. }
  61502. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61503. };
  61504. return BoundingBoxRenderer;
  61505. }());
  61506. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61507. })(BABYLON || (BABYLON = {}));
  61508. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61509. var BABYLON;
  61510. (function (BABYLON) {
  61511. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61512. return this._gl.createTransformFeedback();
  61513. };
  61514. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61515. this._gl.deleteTransformFeedback(value);
  61516. };
  61517. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61518. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61519. };
  61520. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61521. if (usePoints === void 0) { usePoints = true; }
  61522. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61523. };
  61524. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61525. this._gl.endTransformFeedback();
  61526. };
  61527. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61528. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61529. };
  61530. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61531. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61532. };
  61533. })(BABYLON || (BABYLON = {}));
  61534. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61535. var BABYLON;
  61536. (function (BABYLON) {
  61537. /**
  61538. * This represents a GPU particle system in Babylon
  61539. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61540. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61541. */
  61542. var GPUParticleSystem = /** @class */ (function (_super) {
  61543. __extends(GPUParticleSystem, _super);
  61544. /**
  61545. * Instantiates a GPU particle system.
  61546. * 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.
  61547. * @param name The name of the particle system
  61548. * @param options The options used to create the system
  61549. * @param scene The scene the particle system belongs to
  61550. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61551. */
  61552. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61553. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61554. var _this = _super.call(this, name) || this;
  61555. /**
  61556. * The layer mask we are rendering the particles through.
  61557. */
  61558. _this.layerMask = 0x0FFFFFFF;
  61559. _this._accumulatedCount = 0;
  61560. _this._targetIndex = 0;
  61561. _this._currentRenderId = -1;
  61562. _this._started = false;
  61563. _this._stopped = false;
  61564. _this._timeDelta = 0;
  61565. _this._attributesStrideSize = 21;
  61566. _this._actualFrame = 0;
  61567. _this._rawTextureWidth = 256;
  61568. /**
  61569. * An event triggered when the system is disposed.
  61570. */
  61571. _this.onDisposeObservable = new BABYLON.Observable();
  61572. /**
  61573. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61574. * to override the particles.
  61575. */
  61576. _this.forceDepthWrite = false;
  61577. _this._preWarmDone = false;
  61578. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61579. // Setup the default processing configuration to the scene.
  61580. _this._attachImageProcessingConfiguration(null);
  61581. _this._engine = _this._scene.getEngine();
  61582. if (!options.randomTextureSize) {
  61583. delete options.randomTextureSize;
  61584. }
  61585. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61586. var optionsAsNumber = options;
  61587. if (isFinite(optionsAsNumber)) {
  61588. fullOptions.capacity = optionsAsNumber;
  61589. }
  61590. _this._capacity = fullOptions.capacity;
  61591. _this._activeCount = fullOptions.capacity;
  61592. _this._currentActiveCount = 0;
  61593. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61594. _this._scene.particleSystems.push(_this);
  61595. _this._updateEffectOptions = {
  61596. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset"],
  61597. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61598. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61599. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61600. uniformBuffersNames: [],
  61601. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61602. defines: "",
  61603. fallbacks: null,
  61604. onCompiled: null,
  61605. onError: null,
  61606. indexParameters: null,
  61607. maxSimultaneousLights: 0,
  61608. transformFeedbackVaryings: []
  61609. };
  61610. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61611. // Random data
  61612. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61613. var d = [];
  61614. for (var i = 0; i < maxTextureSize; ++i) {
  61615. d.push(Math.random());
  61616. d.push(Math.random());
  61617. d.push(Math.random());
  61618. d.push(Math.random());
  61619. }
  61620. _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);
  61621. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61622. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61623. d = [];
  61624. for (var i = 0; i < maxTextureSize; ++i) {
  61625. d.push(Math.random());
  61626. d.push(Math.random());
  61627. d.push(Math.random());
  61628. d.push(Math.random());
  61629. }
  61630. _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);
  61631. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61632. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61633. _this._randomTextureSize = maxTextureSize;
  61634. return _this;
  61635. }
  61636. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61637. /**
  61638. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61639. */
  61640. get: function () {
  61641. if (!BABYLON.Engine.LastCreatedEngine) {
  61642. return false;
  61643. }
  61644. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61645. },
  61646. enumerable: true,
  61647. configurable: true
  61648. });
  61649. /**
  61650. * Gets the maximum number of particles active at the same time.
  61651. * @returns The max number of active particles.
  61652. */
  61653. GPUParticleSystem.prototype.getCapacity = function () {
  61654. return this._capacity;
  61655. };
  61656. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61657. /**
  61658. * Gets or set the number of active particles
  61659. */
  61660. get: function () {
  61661. return this._activeCount;
  61662. },
  61663. set: function (value) {
  61664. this._activeCount = Math.min(value, this._capacity);
  61665. },
  61666. enumerable: true,
  61667. configurable: true
  61668. });
  61669. /**
  61670. * Is this system ready to be used/rendered
  61671. * @return true if the system is ready
  61672. */
  61673. GPUParticleSystem.prototype.isReady = function () {
  61674. if (!this._updateEffect) {
  61675. this._recreateUpdateEffect();
  61676. this._recreateRenderEffect();
  61677. return false;
  61678. }
  61679. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61680. return false;
  61681. }
  61682. return true;
  61683. };
  61684. /**
  61685. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61686. * @returns True if it has been started, otherwise false.
  61687. */
  61688. GPUParticleSystem.prototype.isStarted = function () {
  61689. return this._started;
  61690. };
  61691. /**
  61692. * Starts the particle system and begins to emit
  61693. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  61694. */
  61695. GPUParticleSystem.prototype.start = function (delay) {
  61696. var _this = this;
  61697. if (delay === void 0) { delay = 0; }
  61698. if (delay) {
  61699. setTimeout(function () {
  61700. _this.start(0);
  61701. }, delay);
  61702. return;
  61703. }
  61704. this._started = true;
  61705. this._stopped = false;
  61706. this._preWarmDone = false;
  61707. };
  61708. /**
  61709. * Stops the particle system.
  61710. */
  61711. GPUParticleSystem.prototype.stop = function () {
  61712. this._stopped = true;
  61713. };
  61714. /**
  61715. * Remove all active particles
  61716. */
  61717. GPUParticleSystem.prototype.reset = function () {
  61718. this._releaseBuffers();
  61719. this._releaseVAOs();
  61720. this._currentActiveCount = 0;
  61721. this._targetIndex = 0;
  61722. };
  61723. /**
  61724. * Returns the string "GPUParticleSystem"
  61725. * @returns a string containing the class name
  61726. */
  61727. GPUParticleSystem.prototype.getClassName = function () {
  61728. return "GPUParticleSystem";
  61729. };
  61730. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61731. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  61732. this._releaseBuffers();
  61733. return this;
  61734. };
  61735. /**
  61736. * Adds a new color gradient
  61737. * @param gradient defines the gradient to use (between 0 and 1)
  61738. * @param color defines the color to affect to the specified gradient
  61739. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61740. * @returns the current particle system
  61741. */
  61742. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61743. if (!this._colorGradients) {
  61744. this._colorGradients = [];
  61745. }
  61746. var colorGradient = new BABYLON.ColorGradient();
  61747. colorGradient.gradient = gradient;
  61748. colorGradient.color1 = color1;
  61749. this._colorGradients.push(colorGradient);
  61750. this._colorGradients.sort(function (a, b) {
  61751. if (a.gradient < b.gradient) {
  61752. return -1;
  61753. }
  61754. else if (a.gradient > b.gradient) {
  61755. return 1;
  61756. }
  61757. return 0;
  61758. });
  61759. if (this._colorGradientsTexture) {
  61760. this._colorGradientsTexture.dispose();
  61761. this._colorGradientsTexture = null;
  61762. }
  61763. this._releaseBuffers();
  61764. return this;
  61765. };
  61766. /**
  61767. * Remove a specific color gradient
  61768. * @param gradient defines the gradient to remove
  61769. * @returns the current particle system
  61770. */
  61771. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61772. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  61773. this._colorGradientsTexture = null;
  61774. return this;
  61775. };
  61776. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61777. var valueGradient = new BABYLON.FactorGradient();
  61778. valueGradient.gradient = gradient;
  61779. valueGradient.factor1 = factor;
  61780. factorGradients.push(valueGradient);
  61781. factorGradients.sort(function (a, b) {
  61782. if (a.gradient < b.gradient) {
  61783. return -1;
  61784. }
  61785. else if (a.gradient > b.gradient) {
  61786. return 1;
  61787. }
  61788. return 0;
  61789. });
  61790. this._releaseBuffers();
  61791. };
  61792. /**
  61793. * Adds a new size gradient
  61794. * @param gradient defines the gradient to use (between 0 and 1)
  61795. * @param factor defines the size factor to affect to the specified gradient
  61796. * @returns the current particle system
  61797. */
  61798. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61799. if (!this._sizeGradients) {
  61800. this._sizeGradients = [];
  61801. }
  61802. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61803. if (this._sizeGradientsTexture) {
  61804. this._sizeGradientsTexture.dispose();
  61805. this._sizeGradientsTexture = null;
  61806. }
  61807. this._releaseBuffers();
  61808. return this;
  61809. };
  61810. /**
  61811. * Remove a specific size gradient
  61812. * @param gradient defines the gradient to remove
  61813. * @returns the current particle system
  61814. */
  61815. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61816. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61817. this._sizeGradientsTexture = null;
  61818. return this;
  61819. };
  61820. /**
  61821. * Adds a new angular speed gradient
  61822. * @param gradient defines the gradient to use (between 0 and 1)
  61823. * @param factor defines the angular speed to affect to the specified gradient
  61824. * @returns the current particle system
  61825. */
  61826. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61827. if (!this._angularSpeedGradients) {
  61828. this._angularSpeedGradients = [];
  61829. }
  61830. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61831. if (this._angularSpeedGradientsTexture) {
  61832. this._angularSpeedGradientsTexture.dispose();
  61833. this._angularSpeedGradientsTexture = null;
  61834. }
  61835. this._releaseBuffers();
  61836. return this;
  61837. };
  61838. /**
  61839. * Remove a specific angular speed gradient
  61840. * @param gradient defines the gradient to remove
  61841. * @returns the current particle system
  61842. */
  61843. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61844. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61845. this._angularSpeedGradientsTexture = null;
  61846. return this;
  61847. };
  61848. /**
  61849. * Adds a new velocity gradient
  61850. * @param gradient defines the gradient to use (between 0 and 1)
  61851. * @param factor defines the velocity to affect to the specified gradient
  61852. * @returns the current particle system
  61853. */
  61854. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61855. if (!this._velocityGradients) {
  61856. this._velocityGradients = [];
  61857. }
  61858. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61859. if (this._velocityGradientsTexture) {
  61860. this._velocityGradientsTexture.dispose();
  61861. this._velocityGradientsTexture = null;
  61862. }
  61863. this._releaseBuffers();
  61864. return this;
  61865. };
  61866. /**
  61867. * Remove a specific velocity gradient
  61868. * @param gradient defines the gradient to remove
  61869. * @returns the current particle system
  61870. */
  61871. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61872. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61873. this._velocityGradientsTexture = null;
  61874. return this;
  61875. };
  61876. /**
  61877. * Adds a new limit velocity gradient
  61878. * @param gradient defines the gradient to use (between 0 and 1)
  61879. * @param factor defines the limit velocity value to affect to the specified gradient
  61880. * @returns the current particle system
  61881. */
  61882. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61883. if (!this._limitVelocityGradients) {
  61884. this._limitVelocityGradients = [];
  61885. }
  61886. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61887. if (this._limitVelocityGradientsTexture) {
  61888. this._limitVelocityGradientsTexture.dispose();
  61889. this._limitVelocityGradientsTexture = null;
  61890. }
  61891. this._releaseBuffers();
  61892. return this;
  61893. };
  61894. /**
  61895. * Remove a specific limit velocity gradient
  61896. * @param gradient defines the gradient to remove
  61897. * @returns the current particle system
  61898. */
  61899. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61900. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61901. this._limitVelocityGradientsTexture = null;
  61902. return this;
  61903. };
  61904. /**
  61905. * Adds a new drag gradient
  61906. * @param gradient defines the gradient to use (between 0 and 1)
  61907. * @param factor defines the drag value to affect to the specified gradient
  61908. * @returns the current particle system
  61909. */
  61910. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61911. if (!this._dragGradients) {
  61912. this._dragGradients = [];
  61913. }
  61914. this._addFactorGradient(this._dragGradients, gradient, factor);
  61915. if (this._dragGradientsTexture) {
  61916. this._dragGradientsTexture.dispose();
  61917. this._dragGradientsTexture = null;
  61918. }
  61919. this._releaseBuffers();
  61920. return this;
  61921. };
  61922. /**
  61923. * Remove a specific drag gradient
  61924. * @param gradient defines the gradient to remove
  61925. * @returns the current particle system
  61926. */
  61927. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61928. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  61929. this._dragGradientsTexture = null;
  61930. return this;
  61931. };
  61932. /**
  61933. * Not supported by GPUParticleSystem
  61934. * @param gradient defines the gradient to use (between 0 and 1)
  61935. * @param factor defines the emit rate value to affect to the specified gradient
  61936. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61937. * @returns the current particle system
  61938. */
  61939. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61940. // Do nothing as emit rate is not supported by GPUParticleSystem
  61941. return this;
  61942. };
  61943. /**
  61944. * Not supported by GPUParticleSystem
  61945. * @param gradient defines the gradient to remove
  61946. * @returns the current particle system
  61947. */
  61948. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61949. // Do nothing as emit rate is not supported by GPUParticleSystem
  61950. return this;
  61951. };
  61952. /**
  61953. * Not supported by GPUParticleSystem
  61954. * @param gradient defines the gradient to use (between 0 and 1)
  61955. * @param factor defines the start size value to affect to the specified gradient
  61956. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61957. * @returns the current particle system
  61958. */
  61959. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61960. // Do nothing as start size is not supported by GPUParticleSystem
  61961. return this;
  61962. };
  61963. /**
  61964. * Not supported by GPUParticleSystem
  61965. * @param gradient defines the gradient to remove
  61966. * @returns the current particle system
  61967. */
  61968. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61969. // Do nothing as start size is not supported by GPUParticleSystem
  61970. return this;
  61971. };
  61972. /**
  61973. * Not supported by GPUParticleSystem
  61974. * @param gradient defines the gradient to use (between 0 and 1)
  61975. * @param min defines the color remap minimal range
  61976. * @param max defines the color remap maximal range
  61977. * @returns the current particle system
  61978. */
  61979. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  61980. // Do nothing as start size is not supported by GPUParticleSystem
  61981. return this;
  61982. };
  61983. /**
  61984. * Not supported by GPUParticleSystem
  61985. * @param gradient defines the gradient to remove
  61986. * @returns the current particle system
  61987. */
  61988. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  61989. // Do nothing as start size is not supported by GPUParticleSystem
  61990. return this;
  61991. };
  61992. /**
  61993. * Not supported by GPUParticleSystem
  61994. * @param gradient defines the gradient to use (between 0 and 1)
  61995. * @param min defines the alpha remap minimal range
  61996. * @param max defines the alpha remap maximal range
  61997. * @returns the current particle system
  61998. */
  61999. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  62000. // Do nothing as start size is not supported by GPUParticleSystem
  62001. return this;
  62002. };
  62003. /**
  62004. * Not supported by GPUParticleSystem
  62005. * @param gradient defines the gradient to remove
  62006. * @returns the current particle system
  62007. */
  62008. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  62009. // Do nothing as start size is not supported by GPUParticleSystem
  62010. return this;
  62011. };
  62012. /**
  62013. * Not supported by GPUParticleSystem
  62014. * @param gradient defines the gradient to use (between 0 and 1)
  62015. * @param color defines the color to affect to the specified gradient
  62016. * @returns the current particle system
  62017. */
  62018. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  62019. //Not supported by GPUParticleSystem
  62020. return this;
  62021. };
  62022. /**
  62023. * Not supported by GPUParticleSystem
  62024. * @param gradient defines the gradient to remove
  62025. * @returns the current particle system
  62026. */
  62027. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  62028. //Not supported by GPUParticleSystem
  62029. return this;
  62030. };
  62031. /**
  62032. * Not supported by GPUParticleSystem
  62033. * @returns the list of ramp gradients
  62034. */
  62035. GPUParticleSystem.prototype.getRampGradients = function () {
  62036. return null;
  62037. };
  62038. GPUParticleSystem.prototype._reset = function () {
  62039. this._releaseBuffers();
  62040. };
  62041. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  62042. var updateVertexBuffers = {};
  62043. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  62044. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  62045. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  62046. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  62047. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  62048. var offset = 12;
  62049. if (!this._colorGradientsTexture) {
  62050. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  62051. offset += 4;
  62052. }
  62053. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  62054. offset += 3;
  62055. if (!this._isBillboardBased) {
  62056. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  62057. offset += 3;
  62058. }
  62059. if (this._angularSpeedGradientsTexture) {
  62060. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  62061. offset += 1;
  62062. }
  62063. else {
  62064. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  62065. offset += 2;
  62066. }
  62067. if (this._isAnimationSheetEnabled) {
  62068. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  62069. offset += 1;
  62070. if (this.spriteRandomStartCell) {
  62071. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  62072. offset += 1;
  62073. }
  62074. }
  62075. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  62076. this._engine.bindArrayBuffer(null);
  62077. return vao;
  62078. };
  62079. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  62080. var renderVertexBuffers = {};
  62081. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  62082. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  62083. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  62084. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  62085. var offset = 12;
  62086. if (!this._colorGradientsTexture) {
  62087. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  62088. offset += 4;
  62089. }
  62090. offset += 3; // Direction
  62091. if (!this._isBillboardBased) {
  62092. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  62093. offset += 3;
  62094. }
  62095. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  62096. if (this._angularSpeedGradientsTexture) {
  62097. offset++;
  62098. }
  62099. else {
  62100. offset += 2;
  62101. }
  62102. if (this._isAnimationSheetEnabled) {
  62103. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  62104. offset += 1;
  62105. if (this.spriteRandomStartCell) {
  62106. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  62107. offset += 1;
  62108. }
  62109. }
  62110. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  62111. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  62112. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  62113. this._engine.bindArrayBuffer(null);
  62114. return vao;
  62115. };
  62116. GPUParticleSystem.prototype._initialize = function (force) {
  62117. if (force === void 0) { force = false; }
  62118. if (this._buffer0 && !force) {
  62119. return;
  62120. }
  62121. var engine = this._scene.getEngine();
  62122. var data = new Array();
  62123. if (!this.isBillboardBased) {
  62124. this._attributesStrideSize += 3;
  62125. }
  62126. if (this._colorGradientsTexture) {
  62127. this._attributesStrideSize -= 4;
  62128. }
  62129. if (this._angularSpeedGradientsTexture) {
  62130. this._attributesStrideSize -= 1;
  62131. }
  62132. if (this._isAnimationSheetEnabled) {
  62133. this._attributesStrideSize += 1;
  62134. if (this.spriteRandomStartCell) {
  62135. this._attributesStrideSize += 1;
  62136. }
  62137. }
  62138. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  62139. // position
  62140. data.push(0.0);
  62141. data.push(0.0);
  62142. data.push(0.0);
  62143. // Age and life
  62144. data.push(0.0); // create the particle as a dead one to create a new one at start
  62145. data.push(0.0);
  62146. // Seed
  62147. data.push(Math.random());
  62148. data.push(Math.random());
  62149. data.push(Math.random());
  62150. data.push(Math.random());
  62151. // Size
  62152. data.push(0.0);
  62153. data.push(0.0);
  62154. data.push(0.0);
  62155. if (!this._colorGradientsTexture) {
  62156. // color
  62157. data.push(0.0);
  62158. data.push(0.0);
  62159. data.push(0.0);
  62160. data.push(0.0);
  62161. }
  62162. // direction
  62163. data.push(0.0);
  62164. data.push(0.0);
  62165. data.push(0.0);
  62166. if (!this.isBillboardBased) {
  62167. // initialDirection
  62168. data.push(0.0);
  62169. data.push(0.0);
  62170. data.push(0.0);
  62171. }
  62172. // angle
  62173. data.push(0.0);
  62174. if (!this._angularSpeedGradientsTexture) {
  62175. data.push(0.0);
  62176. }
  62177. if (this._isAnimationSheetEnabled) {
  62178. data.push(0.0);
  62179. if (this.spriteRandomStartCell) {
  62180. data.push(0.0);
  62181. }
  62182. }
  62183. }
  62184. // Sprite data
  62185. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  62186. -0.5, 0.5, 0, 1,
  62187. -0.5, -0.5, 0, 0,
  62188. 0.5, -0.5, 1, 0]);
  62189. // Buffers
  62190. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62191. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62192. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  62193. // Update VAO
  62194. this._updateVAO = [];
  62195. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  62196. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  62197. // Render VAO
  62198. this._renderVAO = [];
  62199. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  62200. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  62201. // Links
  62202. this._sourceBuffer = this._buffer0;
  62203. this._targetBuffer = this._buffer1;
  62204. };
  62205. /** @hidden */
  62206. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  62207. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  62208. if (this._isBillboardBased) {
  62209. defines += "\n#define BILLBOARD";
  62210. }
  62211. if (this._colorGradientsTexture) {
  62212. defines += "\n#define COLORGRADIENTS";
  62213. }
  62214. if (this._sizeGradientsTexture) {
  62215. defines += "\n#define SIZEGRADIENTS";
  62216. }
  62217. if (this._angularSpeedGradientsTexture) {
  62218. defines += "\n#define ANGULARSPEEDGRADIENTS";
  62219. }
  62220. if (this._velocityGradientsTexture) {
  62221. defines += "\n#define VELOCITYGRADIENTS";
  62222. }
  62223. if (this._limitVelocityGradientsTexture) {
  62224. defines += "\n#define LIMITVELOCITYGRADIENTS";
  62225. }
  62226. if (this._dragGradientsTexture) {
  62227. defines += "\n#define DRAGGRADIENTS";
  62228. }
  62229. if (this.isAnimationSheetEnabled) {
  62230. defines += "\n#define ANIMATESHEET";
  62231. if (this.spriteRandomStartCell) {
  62232. defines += "\n#define ANIMATESHEETRANDOMSTART";
  62233. }
  62234. }
  62235. if (this.noiseTexture) {
  62236. defines += "\n#define NOISE";
  62237. }
  62238. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  62239. return;
  62240. }
  62241. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  62242. if (!this._colorGradientsTexture) {
  62243. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  62244. }
  62245. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  62246. if (!this._isBillboardBased) {
  62247. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  62248. }
  62249. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  62250. if (this.isAnimationSheetEnabled) {
  62251. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  62252. if (this.spriteRandomStartCell) {
  62253. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  62254. }
  62255. }
  62256. this._updateEffectOptions.defines = defines;
  62257. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  62258. };
  62259. /** @hidden */
  62260. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  62261. var defines = "";
  62262. if (this._scene.clipPlane) {
  62263. defines = "\n#define CLIPPLANE";
  62264. }
  62265. if (this._scene.clipPlane2) {
  62266. defines = "\n#define CLIPPLANE2";
  62267. }
  62268. if (this._scene.clipPlane3) {
  62269. defines = "\n#define CLIPPLANE3";
  62270. }
  62271. if (this._scene.clipPlane4) {
  62272. defines = "\n#define CLIPPLANE4";
  62273. }
  62274. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  62275. defines = "\n#define BLENDMULTIPLYMODE";
  62276. }
  62277. if (this._isBillboardBased) {
  62278. defines += "\n#define BILLBOARD";
  62279. switch (this.billboardMode) {
  62280. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  62281. defines += "\n#define BILLBOARDY";
  62282. break;
  62283. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  62284. default:
  62285. break;
  62286. }
  62287. }
  62288. if (this._colorGradientsTexture) {
  62289. defines += "\n#define COLORGRADIENTS";
  62290. }
  62291. if (this.isAnimationSheetEnabled) {
  62292. defines += "\n#define ANIMATESHEET";
  62293. }
  62294. if (this._imageProcessingConfiguration) {
  62295. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62296. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  62297. }
  62298. if (this._renderEffect && this._renderEffect.defines === defines) {
  62299. return;
  62300. }
  62301. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  62302. var samplers = ["textureSampler", "colorGradientSampler"];
  62303. if (BABYLON.ImageProcessingConfiguration) {
  62304. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  62305. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62306. }
  62307. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  62308. };
  62309. /**
  62310. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62311. * @param preWarm defines if we are in the pre-warmimg phase
  62312. */
  62313. GPUParticleSystem.prototype.animate = function (preWarm) {
  62314. if (preWarm === void 0) { preWarm = false; }
  62315. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62316. this._actualFrame += this._timeDelta;
  62317. if (!this._stopped) {
  62318. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62319. this.stop();
  62320. }
  62321. }
  62322. };
  62323. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  62324. var texture = this[textureName];
  62325. if (!factorGradients || !factorGradients.length || texture) {
  62326. return;
  62327. }
  62328. var data = new Float32Array(this._rawTextureWidth);
  62329. for (var x = 0; x < this._rawTextureWidth; x++) {
  62330. var ratio = x / this._rawTextureWidth;
  62331. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  62332. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  62333. });
  62334. }
  62335. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62336. };
  62337. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  62338. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  62339. };
  62340. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  62341. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  62342. };
  62343. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  62344. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  62345. };
  62346. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  62347. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  62348. };
  62349. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  62350. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  62351. };
  62352. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  62353. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  62354. return;
  62355. }
  62356. var data = new Uint8Array(this._rawTextureWidth * 4);
  62357. var tmpColor = BABYLON.Tmp.Color4[0];
  62358. for (var x = 0; x < this._rawTextureWidth; x++) {
  62359. var ratio = x / this._rawTextureWidth;
  62360. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  62361. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  62362. data[x * 4] = tmpColor.r * 255;
  62363. data[x * 4 + 1] = tmpColor.g * 255;
  62364. data[x * 4 + 2] = tmpColor.b * 255;
  62365. data[x * 4 + 3] = tmpColor.a * 255;
  62366. });
  62367. }
  62368. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62369. };
  62370. /**
  62371. * Renders the particle system in its current state
  62372. * @param preWarm defines if the system should only update the particles but not render them
  62373. * @returns the current number of particles
  62374. */
  62375. GPUParticleSystem.prototype.render = function (preWarm) {
  62376. if (preWarm === void 0) { preWarm = false; }
  62377. if (!this._started) {
  62378. return 0;
  62379. }
  62380. this._createColorGradientTexture();
  62381. this._createSizeGradientTexture();
  62382. this._createAngularSpeedGradientTexture();
  62383. this._createVelocityGradientTexture();
  62384. this._createLimitVelocityGradientTexture();
  62385. this._createDragGradientTexture();
  62386. this._recreateUpdateEffect();
  62387. this._recreateRenderEffect();
  62388. if (!this.isReady()) {
  62389. return 0;
  62390. }
  62391. if (!preWarm) {
  62392. if (!this._preWarmDone && this.preWarmCycles) {
  62393. for (var index = 0; index < this.preWarmCycles; index++) {
  62394. this.animate(true);
  62395. this.render(true);
  62396. }
  62397. this._preWarmDone = true;
  62398. }
  62399. if (this._currentRenderId === this._scene.getRenderId()) {
  62400. return 0;
  62401. }
  62402. this._currentRenderId = this._scene.getRenderId();
  62403. }
  62404. // Get everything ready to render
  62405. this._initialize();
  62406. this._accumulatedCount += this.emitRate * this._timeDelta;
  62407. if (this._accumulatedCount > 1) {
  62408. var intPart = this._accumulatedCount | 0;
  62409. this._accumulatedCount -= intPart;
  62410. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  62411. }
  62412. if (!this._currentActiveCount) {
  62413. return 0;
  62414. }
  62415. // Enable update effect
  62416. this._engine.enableEffect(this._updateEffect);
  62417. this._engine.setState(false);
  62418. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  62419. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  62420. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  62421. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  62422. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  62423. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  62424. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  62425. if (!this._colorGradientsTexture) {
  62426. this._updateEffect.setDirectColor4("color1", this.color1);
  62427. this._updateEffect.setDirectColor4("color2", this.color2);
  62428. }
  62429. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  62430. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  62431. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  62432. this._updateEffect.setVector3("gravity", this.gravity);
  62433. if (this._sizeGradientsTexture) {
  62434. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  62435. }
  62436. if (this._angularSpeedGradientsTexture) {
  62437. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  62438. }
  62439. if (this._velocityGradientsTexture) {
  62440. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  62441. }
  62442. if (this._limitVelocityGradientsTexture) {
  62443. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  62444. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  62445. }
  62446. if (this._dragGradientsTexture) {
  62447. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62448. }
  62449. if (this.particleEmitterType) {
  62450. this.particleEmitterType.applyToShader(this._updateEffect);
  62451. }
  62452. if (this._isAnimationSheetEnabled) {
  62453. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62454. }
  62455. if (this.noiseTexture) {
  62456. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62457. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62458. }
  62459. var emitterWM;
  62460. if (this.emitter.position) {
  62461. var emitterMesh = this.emitter;
  62462. emitterWM = emitterMesh.getWorldMatrix();
  62463. }
  62464. else {
  62465. var emitterPosition = this.emitter;
  62466. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62467. }
  62468. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62469. // Bind source VAO
  62470. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62471. // Update
  62472. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62473. this._engine.setRasterizerState(false);
  62474. this._engine.beginTransformFeedback(true);
  62475. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62476. this._engine.endTransformFeedback();
  62477. this._engine.setRasterizerState(true);
  62478. this._engine.bindTransformFeedbackBuffer(null);
  62479. if (!preWarm) {
  62480. // Enable render effect
  62481. this._engine.enableEffect(this._renderEffect);
  62482. var viewMatrix = this._scene.getViewMatrix();
  62483. this._renderEffect.setMatrix("view", viewMatrix);
  62484. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62485. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62486. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62487. if (this._colorGradientsTexture) {
  62488. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62489. }
  62490. else {
  62491. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62492. }
  62493. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62494. var baseSize = this.particleTexture.getBaseSize();
  62495. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62496. }
  62497. if (this._isBillboardBased) {
  62498. var camera = this._scene.activeCamera;
  62499. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62500. }
  62501. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62502. var invView = viewMatrix.clone();
  62503. invView.invert();
  62504. this._renderEffect.setMatrix("invView", invView);
  62505. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62506. }
  62507. // image processing
  62508. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62509. this._imageProcessingConfiguration.bind(this._renderEffect);
  62510. }
  62511. // Draw order
  62512. switch (this.blendMode) {
  62513. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62514. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62515. break;
  62516. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62517. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62518. break;
  62519. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62520. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62521. break;
  62522. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62523. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62524. break;
  62525. }
  62526. if (this.forceDepthWrite) {
  62527. this._engine.setDepthWrite(true);
  62528. }
  62529. // Bind source VAO
  62530. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62531. // Render
  62532. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62533. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62534. }
  62535. // Switch VAOs
  62536. this._targetIndex++;
  62537. if (this._targetIndex === 2) {
  62538. this._targetIndex = 0;
  62539. }
  62540. // Switch buffers
  62541. var tmpBuffer = this._sourceBuffer;
  62542. this._sourceBuffer = this._targetBuffer;
  62543. this._targetBuffer = tmpBuffer;
  62544. return this._currentActiveCount;
  62545. };
  62546. /**
  62547. * Rebuilds the particle system
  62548. */
  62549. GPUParticleSystem.prototype.rebuild = function () {
  62550. this._initialize(true);
  62551. };
  62552. GPUParticleSystem.prototype._releaseBuffers = function () {
  62553. if (this._buffer0) {
  62554. this._buffer0.dispose();
  62555. this._buffer0 = null;
  62556. }
  62557. if (this._buffer1) {
  62558. this._buffer1.dispose();
  62559. this._buffer1 = null;
  62560. }
  62561. if (this._spriteBuffer) {
  62562. this._spriteBuffer.dispose();
  62563. this._spriteBuffer = null;
  62564. }
  62565. };
  62566. GPUParticleSystem.prototype._releaseVAOs = function () {
  62567. if (!this._updateVAO) {
  62568. return;
  62569. }
  62570. for (var index = 0; index < this._updateVAO.length; index++) {
  62571. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62572. }
  62573. this._updateVAO = [];
  62574. for (var index = 0; index < this._renderVAO.length; index++) {
  62575. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62576. }
  62577. this._renderVAO = [];
  62578. };
  62579. /**
  62580. * Disposes the particle system and free the associated resources
  62581. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62582. */
  62583. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62584. if (disposeTexture === void 0) { disposeTexture = true; }
  62585. var index = this._scene.particleSystems.indexOf(this);
  62586. if (index > -1) {
  62587. this._scene.particleSystems.splice(index, 1);
  62588. }
  62589. this._releaseBuffers();
  62590. this._releaseVAOs();
  62591. if (this._colorGradientsTexture) {
  62592. this._colorGradientsTexture.dispose();
  62593. this._colorGradientsTexture = null;
  62594. }
  62595. if (this._sizeGradientsTexture) {
  62596. this._sizeGradientsTexture.dispose();
  62597. this._sizeGradientsTexture = null;
  62598. }
  62599. if (this._angularSpeedGradientsTexture) {
  62600. this._angularSpeedGradientsTexture.dispose();
  62601. this._angularSpeedGradientsTexture = null;
  62602. }
  62603. if (this._velocityGradientsTexture) {
  62604. this._velocityGradientsTexture.dispose();
  62605. this._velocityGradientsTexture = null;
  62606. }
  62607. if (this._limitVelocityGradientsTexture) {
  62608. this._limitVelocityGradientsTexture.dispose();
  62609. this._limitVelocityGradientsTexture = null;
  62610. }
  62611. if (this._dragGradientsTexture) {
  62612. this._dragGradientsTexture.dispose();
  62613. this._dragGradientsTexture = null;
  62614. }
  62615. if (this._randomTexture) {
  62616. this._randomTexture.dispose();
  62617. this._randomTexture = null;
  62618. }
  62619. if (this._randomTexture2) {
  62620. this._randomTexture2.dispose();
  62621. this._randomTexture2 = null;
  62622. }
  62623. if (disposeTexture && this.particleTexture) {
  62624. this.particleTexture.dispose();
  62625. this.particleTexture = null;
  62626. }
  62627. if (disposeTexture && this.noiseTexture) {
  62628. this.noiseTexture.dispose();
  62629. this.noiseTexture = null;
  62630. }
  62631. // Callback
  62632. this.onDisposeObservable.notifyObservers(this);
  62633. this.onDisposeObservable.clear();
  62634. };
  62635. /**
  62636. * Clones the particle system.
  62637. * @param name The name of the cloned object
  62638. * @param newEmitter The new emitter to use
  62639. * @returns the cloned particle system
  62640. */
  62641. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62642. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62643. BABYLON.Tools.DeepCopy(this, result);
  62644. if (newEmitter === undefined) {
  62645. newEmitter = this.emitter;
  62646. }
  62647. result.emitter = newEmitter;
  62648. if (this.particleTexture) {
  62649. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62650. }
  62651. return result;
  62652. };
  62653. /**
  62654. * Serializes the particle system to a JSON object.
  62655. * @returns the JSON object
  62656. */
  62657. GPUParticleSystem.prototype.serialize = function () {
  62658. var serializationObject = {};
  62659. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62660. serializationObject.activeParticleCount = this.activeParticleCount;
  62661. return serializationObject;
  62662. };
  62663. /**
  62664. * Parses a JSON object to create a GPU particle system.
  62665. * @param parsedParticleSystem The JSON object to parse
  62666. * @param scene The scene to create the particle system in
  62667. * @param rootUrl The root url to use to load external dependencies like texture
  62668. * @returns the parsed GPU particle system
  62669. */
  62670. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62671. var name = parsedParticleSystem.name;
  62672. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62673. if (parsedParticleSystem.activeParticleCount) {
  62674. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62675. }
  62676. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62677. return particleSystem;
  62678. };
  62679. return GPUParticleSystem;
  62680. }(BABYLON.BaseParticleSystem));
  62681. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62682. })(BABYLON || (BABYLON = {}));
  62683. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62684. var BABYLON;
  62685. (function (BABYLON) {
  62686. /**
  62687. * Represents one particle of a solid particle system.
  62688. */
  62689. var SolidParticle = /** @class */ (function () {
  62690. /**
  62691. * Creates a Solid Particle object.
  62692. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62693. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62694. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62695. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62696. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62697. * @param shapeId (integer) is the model shape identifier in the SPS.
  62698. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62699. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62700. */
  62701. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62702. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62703. /**
  62704. * particle global index
  62705. */
  62706. this.idx = 0;
  62707. /**
  62708. * The color of the particle
  62709. */
  62710. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62711. /**
  62712. * The world space position of the particle.
  62713. */
  62714. this.position = BABYLON.Vector3.Zero();
  62715. /**
  62716. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62717. */
  62718. this.rotation = BABYLON.Vector3.Zero();
  62719. /**
  62720. * The scaling of the particle.
  62721. */
  62722. this.scaling = BABYLON.Vector3.One();
  62723. /**
  62724. * The uvs of the particle.
  62725. */
  62726. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62727. /**
  62728. * The current speed of the particle.
  62729. */
  62730. this.velocity = BABYLON.Vector3.Zero();
  62731. /**
  62732. * The pivot point in the particle local space.
  62733. */
  62734. this.pivot = BABYLON.Vector3.Zero();
  62735. /**
  62736. * Must the particle be translated from its pivot point in its local space ?
  62737. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62738. * Default : false
  62739. */
  62740. this.translateFromPivot = false;
  62741. /**
  62742. * Is the particle active or not ?
  62743. */
  62744. this.alive = true;
  62745. /**
  62746. * Is the particle visible or not ?
  62747. */
  62748. this.isVisible = true;
  62749. /**
  62750. * Index of this particle in the global "positions" array (Internal use)
  62751. * @hidden
  62752. */
  62753. this._pos = 0;
  62754. /**
  62755. * @hidden Index of this particle in the global "indices" array (Internal use)
  62756. */
  62757. this._ind = 0;
  62758. /**
  62759. * ModelShape id of this particle
  62760. */
  62761. this.shapeId = 0;
  62762. /**
  62763. * Index of the particle in its shape id (Internal use)
  62764. */
  62765. this.idxInShape = 0;
  62766. /**
  62767. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62768. */
  62769. this._stillInvisible = false;
  62770. /**
  62771. * @hidden Last computed particle rotation matrix
  62772. */
  62773. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62774. /**
  62775. * Parent particle Id, if any.
  62776. * Default null.
  62777. */
  62778. this.parentId = null;
  62779. /**
  62780. * @hidden Internal global position in the SPS.
  62781. */
  62782. this._globalPosition = BABYLON.Vector3.Zero();
  62783. this.idx = particleIndex;
  62784. this._pos = positionIndex;
  62785. this._ind = indiceIndex;
  62786. this._model = model;
  62787. this.shapeId = shapeId;
  62788. this.idxInShape = idxInShape;
  62789. this._sps = sps;
  62790. if (modelBoundingInfo) {
  62791. this._modelBoundingInfo = modelBoundingInfo;
  62792. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62793. }
  62794. }
  62795. Object.defineProperty(SolidParticle.prototype, "scale", {
  62796. /**
  62797. * Legacy support, changed scale to scaling
  62798. */
  62799. get: function () {
  62800. return this.scaling;
  62801. },
  62802. /**
  62803. * Legacy support, changed scale to scaling
  62804. */
  62805. set: function (scale) {
  62806. this.scaling = scale;
  62807. },
  62808. enumerable: true,
  62809. configurable: true
  62810. });
  62811. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62812. /**
  62813. * Legacy support, changed quaternion to rotationQuaternion
  62814. */
  62815. get: function () {
  62816. return this.rotationQuaternion;
  62817. },
  62818. /**
  62819. * Legacy support, changed quaternion to rotationQuaternion
  62820. */
  62821. set: function (q) {
  62822. this.rotationQuaternion = q;
  62823. },
  62824. enumerable: true,
  62825. configurable: true
  62826. });
  62827. /**
  62828. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62829. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62830. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62831. * @returns true if it intersects
  62832. */
  62833. SolidParticle.prototype.intersectsMesh = function (target) {
  62834. if (!this._boundingInfo || !target._boundingInfo) {
  62835. return false;
  62836. }
  62837. if (this._sps._bSphereOnly) {
  62838. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62839. }
  62840. return this._boundingInfo.intersects(target._boundingInfo, false);
  62841. };
  62842. return SolidParticle;
  62843. }());
  62844. BABYLON.SolidParticle = SolidParticle;
  62845. /**
  62846. * Represents the shape of the model used by one particle of a solid particle system.
  62847. * SPS internal tool, don't use it manually.
  62848. */
  62849. var ModelShape = /** @class */ (function () {
  62850. /**
  62851. * 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.
  62852. * SPS internal tool, don't use it manually.
  62853. * @hidden
  62854. */
  62855. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62856. /**
  62857. * length of the shape in the model indices array (internal use)
  62858. * @hidden
  62859. */
  62860. this._indicesLength = 0;
  62861. this.shapeID = id;
  62862. this._shape = shape;
  62863. this._indicesLength = indicesLength;
  62864. this._shapeUV = shapeUV;
  62865. this._positionFunction = posFunction;
  62866. this._vertexFunction = vtxFunction;
  62867. }
  62868. return ModelShape;
  62869. }());
  62870. BABYLON.ModelShape = ModelShape;
  62871. /**
  62872. * Represents a Depth Sorted Particle in the solid particle system.
  62873. */
  62874. var DepthSortedParticle = /** @class */ (function () {
  62875. function DepthSortedParticle() {
  62876. /**
  62877. * Index of the particle in the "indices" array
  62878. */
  62879. this.ind = 0;
  62880. /**
  62881. * Length of the particle shape in the "indices" array
  62882. */
  62883. this.indicesLength = 0;
  62884. /**
  62885. * Squared distance from the particle to the camera
  62886. */
  62887. this.sqDistance = 0.0;
  62888. }
  62889. return DepthSortedParticle;
  62890. }());
  62891. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62892. })(BABYLON || (BABYLON = {}));
  62893. //# sourceMappingURL=babylon.solidParticle.js.map
  62894. var BABYLON;
  62895. (function (BABYLON) {
  62896. /**
  62897. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62898. *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.
  62899. * The SPS is also a particle system. It provides some methods to manage the particles.
  62900. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62901. *
  62902. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62903. */
  62904. var SolidParticleSystem = /** @class */ (function () {
  62905. /**
  62906. * Creates a SPS (Solid Particle System) object.
  62907. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62908. * @param scene (Scene) is the scene in which the SPS is added.
  62909. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62910. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62911. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62912. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62913. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62914. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62915. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62916. */
  62917. function SolidParticleSystem(name, scene, options) {
  62918. /**
  62919. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62920. * Example : var p = SPS.particles[i];
  62921. */
  62922. this.particles = new Array();
  62923. /**
  62924. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62925. */
  62926. this.nbParticles = 0;
  62927. /**
  62928. * If the particles must ever face the camera (default false). Useful for planar particles.
  62929. */
  62930. this.billboard = false;
  62931. /**
  62932. * Recompute normals when adding a shape
  62933. */
  62934. this.recomputeNormals = true;
  62935. /**
  62936. * This a counter ofr your own usage. It's not set by any SPS functions.
  62937. */
  62938. this.counter = 0;
  62939. /**
  62940. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62941. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62942. */
  62943. this.vars = {};
  62944. /**
  62945. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62946. * @hidden
  62947. */
  62948. this._bSphereOnly = false;
  62949. /**
  62950. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62951. * @hidden
  62952. */
  62953. this._bSphereRadiusFactor = 1.0;
  62954. this._positions = new Array();
  62955. this._indices = new Array();
  62956. this._normals = new Array();
  62957. this._colors = new Array();
  62958. this._uvs = new Array();
  62959. this._index = 0; // indices index
  62960. this._updatable = true;
  62961. this._pickable = false;
  62962. this._isVisibilityBoxLocked = false;
  62963. this._alwaysVisible = false;
  62964. this._depthSort = false;
  62965. this._shapeCounter = 0;
  62966. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62967. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62968. this._computeParticleColor = true;
  62969. this._computeParticleTexture = true;
  62970. this._computeParticleRotation = true;
  62971. this._computeParticleVertex = false;
  62972. this._computeBoundingBox = false;
  62973. this._depthSortParticles = true;
  62974. this._cam_axisZ = BABYLON.Vector3.Zero();
  62975. this._cam_axisY = BABYLON.Vector3.Zero();
  62976. this._cam_axisX = BABYLON.Vector3.Zero();
  62977. this._axisZ = BABYLON.Axis.Z;
  62978. this._camDir = BABYLON.Vector3.Zero();
  62979. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62980. this._rotMatrix = new BABYLON.Matrix();
  62981. this._invertMatrix = new BABYLON.Matrix();
  62982. this._rotated = BABYLON.Vector3.Zero();
  62983. this._quaternion = new BABYLON.Quaternion();
  62984. this._vertex = BABYLON.Vector3.Zero();
  62985. this._normal = BABYLON.Vector3.Zero();
  62986. this._yaw = 0.0;
  62987. this._pitch = 0.0;
  62988. this._roll = 0.0;
  62989. this._halfroll = 0.0;
  62990. this._halfpitch = 0.0;
  62991. this._halfyaw = 0.0;
  62992. this._sinRoll = 0.0;
  62993. this._cosRoll = 0.0;
  62994. this._sinPitch = 0.0;
  62995. this._cosPitch = 0.0;
  62996. this._sinYaw = 0.0;
  62997. this._cosYaw = 0.0;
  62998. this._mustUnrotateFixedNormals = false;
  62999. this._minimum = BABYLON.Vector3.Zero();
  63000. this._maximum = BABYLON.Vector3.Zero();
  63001. this._minBbox = BABYLON.Vector3.Zero();
  63002. this._maxBbox = BABYLON.Vector3.Zero();
  63003. this._particlesIntersect = false;
  63004. this._depthSortFunction = function (p1, p2) {
  63005. return (p2.sqDistance - p1.sqDistance);
  63006. };
  63007. this._needs32Bits = false;
  63008. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  63009. this._scaledPivot = BABYLON.Vector3.Zero();
  63010. this._particleHasParent = false;
  63011. this.name = name;
  63012. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63013. this._camera = scene.activeCamera;
  63014. this._pickable = options ? options.isPickable : false;
  63015. this._depthSort = options ? options.enableDepthSort : false;
  63016. this._particlesIntersect = options ? options.particleIntersection : false;
  63017. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  63018. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  63019. if (options && options.updatable !== undefined) {
  63020. this._updatable = options.updatable;
  63021. }
  63022. else {
  63023. this._updatable = true;
  63024. }
  63025. if (this._pickable) {
  63026. this.pickedParticles = [];
  63027. }
  63028. if (this._depthSort) {
  63029. this.depthSortedParticles = [];
  63030. }
  63031. }
  63032. /**
  63033. * Builds the SPS underlying mesh. Returns a standard Mesh.
  63034. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  63035. * @returns the created mesh
  63036. */
  63037. SolidParticleSystem.prototype.buildMesh = function () {
  63038. if (this.nbParticles === 0) {
  63039. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  63040. this.addShape(triangle, 1);
  63041. triangle.dispose();
  63042. }
  63043. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  63044. this._positions32 = new Float32Array(this._positions);
  63045. this._uvs32 = new Float32Array(this._uvs);
  63046. this._colors32 = new Float32Array(this._colors);
  63047. if (this.recomputeNormals) {
  63048. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  63049. }
  63050. this._normals32 = new Float32Array(this._normals);
  63051. this._fixedNormal32 = new Float32Array(this._normals);
  63052. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  63053. this._unrotateFixedNormals();
  63054. }
  63055. var vertexData = new BABYLON.VertexData();
  63056. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  63057. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  63058. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  63059. if (this._uvs32.length > 0) {
  63060. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  63061. }
  63062. if (this._colors32.length > 0) {
  63063. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  63064. }
  63065. var mesh = new BABYLON.Mesh(this.name, this._scene);
  63066. vertexData.applyToMesh(mesh, this._updatable);
  63067. this.mesh = mesh;
  63068. this.mesh.isPickable = this._pickable;
  63069. // free memory
  63070. if (!this._depthSort) {
  63071. this._indices = null;
  63072. }
  63073. this._positions = null;
  63074. this._normals = null;
  63075. this._uvs = null;
  63076. this._colors = null;
  63077. if (!this._updatable) {
  63078. this.particles.length = 0;
  63079. }
  63080. return mesh;
  63081. };
  63082. /**
  63083. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  63084. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  63085. * Thus the particles generated from `digest()` have their property `position` set yet.
  63086. * @param mesh ( Mesh ) is the mesh to be digested
  63087. * @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
  63088. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  63089. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  63090. * @returns the current SPS
  63091. */
  63092. SolidParticleSystem.prototype.digest = function (mesh, options) {
  63093. var size = (options && options.facetNb) || 1;
  63094. var number = (options && options.number) || 0;
  63095. var delta = (options && options.delta) || 0;
  63096. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63097. var meshInd = mesh.getIndices();
  63098. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63099. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63100. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63101. var f = 0; // facet counter
  63102. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  63103. // compute size from number
  63104. if (number) {
  63105. number = (number > totalFacets) ? totalFacets : number;
  63106. size = Math.round(totalFacets / number);
  63107. delta = 0;
  63108. }
  63109. else {
  63110. size = (size > totalFacets) ? totalFacets : size;
  63111. }
  63112. var facetPos = []; // submesh positions
  63113. var facetInd = []; // submesh indices
  63114. var facetUV = []; // submesh UV
  63115. var facetCol = []; // submesh colors
  63116. var barycenter = BABYLON.Vector3.Zero();
  63117. var sizeO = size;
  63118. while (f < totalFacets) {
  63119. size = sizeO + Math.floor((1 + delta) * Math.random());
  63120. if (f > totalFacets - size) {
  63121. size = totalFacets - f;
  63122. }
  63123. // reset temp arrays
  63124. facetPos.length = 0;
  63125. facetInd.length = 0;
  63126. facetUV.length = 0;
  63127. facetCol.length = 0;
  63128. // iterate over "size" facets
  63129. var fi = 0;
  63130. for (var j = f * 3; j < (f + size) * 3; j++) {
  63131. facetInd.push(fi);
  63132. var i = meshInd[j];
  63133. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  63134. if (meshUV) {
  63135. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  63136. }
  63137. if (meshCol) {
  63138. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  63139. }
  63140. fi++;
  63141. }
  63142. // create a model shape for each single particle
  63143. var idx = this.nbParticles;
  63144. var shape = this._posToShape(facetPos);
  63145. var shapeUV = this._uvsToShapeUV(facetUV);
  63146. // compute the barycenter of the shape
  63147. var v;
  63148. for (v = 0; v < shape.length; v++) {
  63149. barycenter.addInPlace(shape[v]);
  63150. }
  63151. barycenter.scaleInPlace(1 / shape.length);
  63152. // shift the shape from its barycenter to the origin
  63153. for (v = 0; v < shape.length; v++) {
  63154. shape[v].subtractInPlace(barycenter);
  63155. }
  63156. var bInfo;
  63157. if (this._particlesIntersect) {
  63158. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  63159. }
  63160. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  63161. // add the particle in the SPS
  63162. var currentPos = this._positions.length;
  63163. var currentInd = this._indices.length;
  63164. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  63165. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  63166. // initialize the particle position
  63167. this.particles[this.nbParticles].position.addInPlace(barycenter);
  63168. this._index += shape.length;
  63169. idx++;
  63170. this.nbParticles++;
  63171. this._shapeCounter++;
  63172. f += size;
  63173. }
  63174. return this;
  63175. };
  63176. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  63177. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  63178. var index = 0;
  63179. var idx = 0;
  63180. for (var p = 0; p < this.particles.length; p++) {
  63181. this._particle = this.particles[p];
  63182. this._shape = this._particle._model._shape;
  63183. if (this._particle.rotationQuaternion) {
  63184. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63185. }
  63186. else {
  63187. this._yaw = this._particle.rotation.y;
  63188. this._pitch = this._particle.rotation.x;
  63189. this._roll = this._particle.rotation.z;
  63190. this._quaternionRotationYPR();
  63191. }
  63192. this._quaternionToRotationMatrix();
  63193. this._rotMatrix.invertToRef(this._invertMatrix);
  63194. for (var pt = 0; pt < this._shape.length; pt++) {
  63195. idx = index + pt * 3;
  63196. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  63197. this._fixedNormal32[idx] = this._normal.x;
  63198. this._fixedNormal32[idx + 1] = this._normal.y;
  63199. this._fixedNormal32[idx + 2] = this._normal.z;
  63200. }
  63201. index = idx + 3;
  63202. }
  63203. };
  63204. //reset copy
  63205. SolidParticleSystem.prototype._resetCopy = function () {
  63206. this._copy.position.x = 0;
  63207. this._copy.position.y = 0;
  63208. this._copy.position.z = 0;
  63209. this._copy.rotation.x = 0;
  63210. this._copy.rotation.y = 0;
  63211. this._copy.rotation.z = 0;
  63212. this._copy.rotationQuaternion = null;
  63213. this._copy.scaling.x = 1.0;
  63214. this._copy.scaling.y = 1.0;
  63215. this._copy.scaling.z = 1.0;
  63216. this._copy.uvs.x = 0;
  63217. this._copy.uvs.y = 0;
  63218. this._copy.uvs.z = 1.0;
  63219. this._copy.uvs.w = 1.0;
  63220. this._copy.color = null;
  63221. this._copy.translateFromPivot = false;
  63222. };
  63223. // _meshBuilder : inserts the shape model in the global SPS mesh
  63224. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  63225. var i;
  63226. var u = 0;
  63227. var c = 0;
  63228. var n = 0;
  63229. this._resetCopy();
  63230. if (options && options.positionFunction) { // call to custom positionFunction
  63231. options.positionFunction(this._copy, idx, idxInShape);
  63232. this._mustUnrotateFixedNormals = true;
  63233. }
  63234. if (this._copy.rotationQuaternion) {
  63235. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63236. }
  63237. else {
  63238. this._yaw = this._copy.rotation.y;
  63239. this._pitch = this._copy.rotation.x;
  63240. this._roll = this._copy.rotation.z;
  63241. this._quaternionRotationYPR();
  63242. }
  63243. this._quaternionToRotationMatrix();
  63244. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  63245. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  63246. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  63247. if (this._copy.translateFromPivot) {
  63248. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63249. }
  63250. else {
  63251. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63252. }
  63253. for (i = 0; i < shape.length; i++) {
  63254. this._vertex.x = shape[i].x;
  63255. this._vertex.y = shape[i].y;
  63256. this._vertex.z = shape[i].z;
  63257. if (options && options.vertexFunction) {
  63258. options.vertexFunction(this._copy, this._vertex, i);
  63259. }
  63260. this._vertex.x *= this._copy.scaling.x;
  63261. this._vertex.y *= this._copy.scaling.y;
  63262. this._vertex.z *= this._copy.scaling.z;
  63263. this._vertex.x -= this._scaledPivot.x;
  63264. this._vertex.y -= this._scaledPivot.y;
  63265. this._vertex.z -= this._scaledPivot.z;
  63266. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63267. this._rotated.addInPlace(this._pivotBackTranslation);
  63268. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  63269. if (meshUV) {
  63270. 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);
  63271. u += 2;
  63272. }
  63273. if (this._copy.color) {
  63274. this._color = this._copy.color;
  63275. }
  63276. else if (meshCol && meshCol[c] !== undefined) {
  63277. this._color.r = meshCol[c];
  63278. this._color.g = meshCol[c + 1];
  63279. this._color.b = meshCol[c + 2];
  63280. this._color.a = meshCol[c + 3];
  63281. }
  63282. else {
  63283. this._color.r = 1.0;
  63284. this._color.g = 1.0;
  63285. this._color.b = 1.0;
  63286. this._color.a = 1.0;
  63287. }
  63288. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  63289. c += 4;
  63290. if (!this.recomputeNormals && meshNor) {
  63291. this._normal.x = meshNor[n];
  63292. this._normal.y = meshNor[n + 1];
  63293. this._normal.z = meshNor[n + 2];
  63294. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  63295. normals.push(this._normal.x, this._normal.y, this._normal.z);
  63296. n += 3;
  63297. }
  63298. }
  63299. for (i = 0; i < meshInd.length; i++) {
  63300. var current_ind = p + meshInd[i];
  63301. indices.push(current_ind);
  63302. if (current_ind > 65535) {
  63303. this._needs32Bits = true;
  63304. }
  63305. }
  63306. if (this._pickable) {
  63307. var nbfaces = meshInd.length / 3;
  63308. for (i = 0; i < nbfaces; i++) {
  63309. this.pickedParticles.push({ idx: idx, faceId: i });
  63310. }
  63311. }
  63312. if (this._depthSort) {
  63313. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  63314. }
  63315. return this._copy;
  63316. };
  63317. // returns a shape array from positions array
  63318. SolidParticleSystem.prototype._posToShape = function (positions) {
  63319. var shape = [];
  63320. for (var i = 0; i < positions.length; i += 3) {
  63321. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  63322. }
  63323. return shape;
  63324. };
  63325. // returns a shapeUV array from a Vector4 uvs
  63326. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  63327. var shapeUV = [];
  63328. if (uvs) {
  63329. for (var i = 0; i < uvs.length; i++)
  63330. shapeUV.push(uvs[i]);
  63331. }
  63332. return shapeUV;
  63333. };
  63334. // adds a new particle object in the particles array
  63335. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  63336. if (bInfo === void 0) { bInfo = null; }
  63337. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  63338. this.particles.push(sp);
  63339. return sp;
  63340. };
  63341. /**
  63342. * Adds some particles to the SPS from the model shape. Returns the shape id.
  63343. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  63344. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  63345. * @param nb (positive integer) the number of particles to be created from this model
  63346. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  63347. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  63348. * @returns the number of shapes in the system
  63349. */
  63350. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  63351. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63352. var meshInd = mesh.getIndices();
  63353. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63354. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63355. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63356. var bbInfo;
  63357. if (this._particlesIntersect) {
  63358. bbInfo = mesh.getBoundingInfo();
  63359. }
  63360. var shape = this._posToShape(meshPos);
  63361. var shapeUV = this._uvsToShapeUV(meshUV);
  63362. var posfunc = options ? options.positionFunction : null;
  63363. var vtxfunc = options ? options.vertexFunction : null;
  63364. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  63365. // particles
  63366. var sp;
  63367. var currentCopy;
  63368. var idx = this.nbParticles;
  63369. for (var i = 0; i < nb; i++) {
  63370. var currentPos = this._positions.length;
  63371. var currentInd = this._indices.length;
  63372. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  63373. if (this._updatable) {
  63374. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  63375. sp.position.copyFrom(currentCopy.position);
  63376. sp.rotation.copyFrom(currentCopy.rotation);
  63377. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  63378. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  63379. }
  63380. if (currentCopy.color && sp.color) {
  63381. sp.color.copyFrom(currentCopy.color);
  63382. }
  63383. sp.scaling.copyFrom(currentCopy.scaling);
  63384. sp.uvs.copyFrom(currentCopy.uvs);
  63385. }
  63386. this._index += shape.length;
  63387. idx++;
  63388. }
  63389. this.nbParticles += nb;
  63390. this._shapeCounter++;
  63391. return this._shapeCounter - 1;
  63392. };
  63393. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  63394. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  63395. this._resetCopy();
  63396. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  63397. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  63398. }
  63399. if (this._copy.rotationQuaternion) {
  63400. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63401. }
  63402. else {
  63403. this._yaw = this._copy.rotation.y;
  63404. this._pitch = this._copy.rotation.x;
  63405. this._roll = this._copy.rotation.z;
  63406. this._quaternionRotationYPR();
  63407. }
  63408. this._quaternionToRotationMatrix();
  63409. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63410. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63411. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63412. if (this._copy.translateFromPivot) {
  63413. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63414. }
  63415. else {
  63416. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63417. }
  63418. this._shape = particle._model._shape;
  63419. for (var pt = 0; pt < this._shape.length; pt++) {
  63420. this._vertex.x = this._shape[pt].x;
  63421. this._vertex.y = this._shape[pt].y;
  63422. this._vertex.z = this._shape[pt].z;
  63423. if (particle._model._vertexFunction) {
  63424. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  63425. }
  63426. this._vertex.x *= this._copy.scaling.x;
  63427. this._vertex.y *= this._copy.scaling.y;
  63428. this._vertex.z *= this._copy.scaling.z;
  63429. this._vertex.x -= this._scaledPivot.x;
  63430. this._vertex.y -= this._scaledPivot.y;
  63431. this._vertex.z -= this._scaledPivot.z;
  63432. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63433. this._rotated.addInPlace(this._pivotBackTranslation);
  63434. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  63435. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  63436. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  63437. }
  63438. particle.position.x = 0.0;
  63439. particle.position.y = 0.0;
  63440. particle.position.z = 0.0;
  63441. particle.rotation.x = 0.0;
  63442. particle.rotation.y = 0.0;
  63443. particle.rotation.z = 0.0;
  63444. particle.rotationQuaternion = null;
  63445. particle.scaling.x = 1.0;
  63446. particle.scaling.y = 1.0;
  63447. particle.scaling.z = 1.0;
  63448. particle.uvs.x = 0.0;
  63449. particle.uvs.y = 0.0;
  63450. particle.uvs.z = 1.0;
  63451. particle.uvs.w = 1.0;
  63452. particle.pivot.x = 0.0;
  63453. particle.pivot.y = 0.0;
  63454. particle.pivot.z = 0.0;
  63455. particle.translateFromPivot = false;
  63456. particle.parentId = null;
  63457. };
  63458. /**
  63459. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63460. * @returns the SPS.
  63461. */
  63462. SolidParticleSystem.prototype.rebuildMesh = function () {
  63463. for (var p = 0; p < this.particles.length; p++) {
  63464. this._rebuildParticle(this.particles[p]);
  63465. }
  63466. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63467. return this;
  63468. };
  63469. /**
  63470. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63471. * This method calls `updateParticle()` for each particle of the SPS.
  63472. * For an animated SPS, it is usually called within the render loop.
  63473. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63474. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63475. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63476. * @returns the SPS.
  63477. */
  63478. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63479. if (start === void 0) { start = 0; }
  63480. if (end === void 0) { end = this.nbParticles - 1; }
  63481. if (update === void 0) { update = true; }
  63482. if (!this._updatable) {
  63483. return this;
  63484. }
  63485. // custom beforeUpdate
  63486. this.beforeUpdateParticles(start, end, update);
  63487. this._cam_axisX.x = 1.0;
  63488. this._cam_axisX.y = 0.0;
  63489. this._cam_axisX.z = 0.0;
  63490. this._cam_axisY.x = 0.0;
  63491. this._cam_axisY.y = 1.0;
  63492. this._cam_axisY.z = 0.0;
  63493. this._cam_axisZ.x = 0.0;
  63494. this._cam_axisZ.y = 0.0;
  63495. this._cam_axisZ.z = 1.0;
  63496. // cases when the World Matrix is to be computed first
  63497. if (this.billboard || this._depthSort) {
  63498. this.mesh.computeWorldMatrix(true);
  63499. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63500. }
  63501. // if the particles will always face the camera
  63502. if (this.billboard) {
  63503. // compute the camera position and un-rotate it by the current mesh rotation
  63504. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63505. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63506. this._cam_axisZ.normalize();
  63507. // same for camera up vector extracted from the cam view matrix
  63508. var view = this._camera.getViewMatrix(true);
  63509. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63510. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63511. this._cam_axisY.normalize();
  63512. this._cam_axisX.normalize();
  63513. }
  63514. // if depthSort, compute the camera global position in the mesh local system
  63515. if (this._depthSort) {
  63516. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63517. }
  63518. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63519. var idx = 0; // current position index in the global array positions32
  63520. var index = 0; // position start index in the global array positions32 of the current particle
  63521. var colidx = 0; // current color index in the global array colors32
  63522. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63523. var uvidx = 0; // current uv index in the global array uvs32
  63524. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63525. var pt = 0; // current index in the particle model shape
  63526. if (this.mesh.isFacetDataEnabled) {
  63527. this._computeBoundingBox = true;
  63528. }
  63529. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63530. if (this._computeBoundingBox) {
  63531. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63532. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63533. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63534. }
  63535. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63536. if (this.mesh._boundingInfo) {
  63537. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63538. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63539. }
  63540. }
  63541. }
  63542. // particle loop
  63543. index = this.particles[start]._pos;
  63544. var vpos = (index / 3) | 0;
  63545. colorIndex = vpos * 4;
  63546. uvIndex = vpos * 2;
  63547. for (var p = start; p <= end; p++) {
  63548. this._particle = this.particles[p];
  63549. this._shape = this._particle._model._shape;
  63550. this._shapeUV = this._particle._model._shapeUV;
  63551. // call to custom user function to update the particle properties
  63552. this.updateParticle(this._particle);
  63553. // camera-particle distance for depth sorting
  63554. if (this._depthSort && this._depthSortParticles) {
  63555. var dsp = this.depthSortedParticles[p];
  63556. dsp.ind = this._particle._ind;
  63557. dsp.indicesLength = this._particle._model._indicesLength;
  63558. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63559. }
  63560. // skip the computations for inactive or already invisible particles
  63561. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63562. // increment indexes for the next particle
  63563. pt = this._shape.length;
  63564. index += pt * 3;
  63565. colorIndex += pt * 4;
  63566. uvIndex += pt * 2;
  63567. continue;
  63568. }
  63569. if (this._particle.isVisible) {
  63570. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63571. this._particleHasParent = (this._particle.parentId !== null);
  63572. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63573. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63574. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63575. // particle rotation matrix
  63576. if (this.billboard) {
  63577. this._particle.rotation.x = 0.0;
  63578. this._particle.rotation.y = 0.0;
  63579. }
  63580. if (this._computeParticleRotation || this.billboard) {
  63581. if (this._particle.rotationQuaternion) {
  63582. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63583. }
  63584. else {
  63585. this._yaw = this._particle.rotation.y;
  63586. this._pitch = this._particle.rotation.x;
  63587. this._roll = this._particle.rotation.z;
  63588. this._quaternionRotationYPR();
  63589. }
  63590. this._quaternionToRotationMatrix();
  63591. }
  63592. if (this._particleHasParent) {
  63593. this._parent = this.particles[this._particle.parentId];
  63594. 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];
  63595. 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];
  63596. 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];
  63597. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63598. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63599. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63600. if (this._computeParticleRotation || this.billboard) {
  63601. 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];
  63602. 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];
  63603. 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];
  63604. 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];
  63605. 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];
  63606. 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];
  63607. 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];
  63608. 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];
  63609. 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];
  63610. }
  63611. }
  63612. else {
  63613. this._particle._globalPosition.x = this._particle.position.x;
  63614. this._particle._globalPosition.y = this._particle.position.y;
  63615. this._particle._globalPosition.z = this._particle.position.z;
  63616. if (this._computeParticleRotation || this.billboard) {
  63617. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63618. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63619. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63620. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63621. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63622. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63623. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63624. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63625. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63626. }
  63627. }
  63628. if (this._particle.translateFromPivot) {
  63629. this._pivotBackTranslation.x = 0.0;
  63630. this._pivotBackTranslation.y = 0.0;
  63631. this._pivotBackTranslation.z = 0.0;
  63632. }
  63633. else {
  63634. this._pivotBackTranslation.x = this._scaledPivot.x;
  63635. this._pivotBackTranslation.y = this._scaledPivot.y;
  63636. this._pivotBackTranslation.z = this._scaledPivot.z;
  63637. }
  63638. // particle vertex loop
  63639. for (pt = 0; pt < this._shape.length; pt++) {
  63640. idx = index + pt * 3;
  63641. colidx = colorIndex + pt * 4;
  63642. uvidx = uvIndex + pt * 2;
  63643. this._vertex.x = this._shape[pt].x;
  63644. this._vertex.y = this._shape[pt].y;
  63645. this._vertex.z = this._shape[pt].z;
  63646. if (this._computeParticleVertex) {
  63647. this.updateParticleVertex(this._particle, this._vertex, pt);
  63648. }
  63649. // positions
  63650. this._vertex.x *= this._particle.scaling.x;
  63651. this._vertex.y *= this._particle.scaling.y;
  63652. this._vertex.z *= this._particle.scaling.z;
  63653. this._vertex.x -= this._scaledPivot.x;
  63654. this._vertex.y -= this._scaledPivot.y;
  63655. this._vertex.z -= this._scaledPivot.z;
  63656. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63657. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63658. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63659. this._rotated.x += this._pivotBackTranslation.x;
  63660. this._rotated.y += this._pivotBackTranslation.y;
  63661. this._rotated.z += this._pivotBackTranslation.z;
  63662. 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;
  63663. 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;
  63664. 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;
  63665. if (this._computeBoundingBox) {
  63666. if (this._positions32[idx] < this._minimum.x) {
  63667. this._minimum.x = this._positions32[idx];
  63668. }
  63669. if (this._positions32[idx] > this._maximum.x) {
  63670. this._maximum.x = this._positions32[idx];
  63671. }
  63672. if (this._positions32[idx + 1] < this._minimum.y) {
  63673. this._minimum.y = this._positions32[idx + 1];
  63674. }
  63675. if (this._positions32[idx + 1] > this._maximum.y) {
  63676. this._maximum.y = this._positions32[idx + 1];
  63677. }
  63678. if (this._positions32[idx + 2] < this._minimum.z) {
  63679. this._minimum.z = this._positions32[idx + 2];
  63680. }
  63681. if (this._positions32[idx + 2] > this._maximum.z) {
  63682. this._maximum.z = this._positions32[idx + 2];
  63683. }
  63684. }
  63685. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63686. if (!this._computeParticleVertex) {
  63687. this._normal.x = this._fixedNormal32[idx];
  63688. this._normal.y = this._fixedNormal32[idx + 1];
  63689. this._normal.z = this._fixedNormal32[idx + 2];
  63690. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63691. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63692. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63693. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63694. 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;
  63695. 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;
  63696. }
  63697. if (this._computeParticleColor && this._particle.color) {
  63698. this._colors32[colidx] = this._particle.color.r;
  63699. this._colors32[colidx + 1] = this._particle.color.g;
  63700. this._colors32[colidx + 2] = this._particle.color.b;
  63701. this._colors32[colidx + 3] = this._particle.color.a;
  63702. }
  63703. if (this._computeParticleTexture) {
  63704. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63705. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63706. }
  63707. }
  63708. }
  63709. // particle just set invisible : scaled to zero and positioned at the origin
  63710. else {
  63711. this._particle._stillInvisible = true; // mark the particle as invisible
  63712. for (pt = 0; pt < this._shape.length; pt++) {
  63713. idx = index + pt * 3;
  63714. colidx = colorIndex + pt * 4;
  63715. uvidx = uvIndex + pt * 2;
  63716. this._positions32[idx] = 0.0;
  63717. this._positions32[idx + 1] = 0.0;
  63718. this._positions32[idx + 2] = 0.0;
  63719. this._normals32[idx] = 0.0;
  63720. this._normals32[idx + 1] = 0.0;
  63721. this._normals32[idx + 2] = 0.0;
  63722. if (this._computeParticleColor && this._particle.color) {
  63723. this._colors32[colidx] = this._particle.color.r;
  63724. this._colors32[colidx + 1] = this._particle.color.g;
  63725. this._colors32[colidx + 2] = this._particle.color.b;
  63726. this._colors32[colidx + 3] = this._particle.color.a;
  63727. }
  63728. if (this._computeParticleTexture) {
  63729. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63730. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63731. }
  63732. }
  63733. }
  63734. // if the particle intersections must be computed : update the bbInfo
  63735. if (this._particlesIntersect) {
  63736. var bInfo = this._particle._boundingInfo;
  63737. var bBox = bInfo.boundingBox;
  63738. var bSphere = bInfo.boundingSphere;
  63739. if (!this._bSphereOnly) {
  63740. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63741. for (var b = 0; b < bBox.vectors.length; b++) {
  63742. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63743. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63744. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63745. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63746. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63747. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63748. 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;
  63749. 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;
  63750. 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;
  63751. }
  63752. bBox._update(this.mesh._worldMatrix);
  63753. }
  63754. // place and scale the particle bouding sphere in the SPS local system, then update it
  63755. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63756. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63757. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63758. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63759. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63760. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63761. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63762. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63763. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63764. 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));
  63765. bSphere._update(this.mesh._worldMatrix);
  63766. }
  63767. // increment indexes for the next particle
  63768. index = idx + 3;
  63769. colorIndex = colidx + 4;
  63770. uvIndex = uvidx + 2;
  63771. }
  63772. // if the VBO must be updated
  63773. if (update) {
  63774. if (this._computeParticleColor) {
  63775. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63776. }
  63777. if (this._computeParticleTexture) {
  63778. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63779. }
  63780. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63781. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63782. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63783. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63784. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63785. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63786. for (var i = 0; i < this._normals32.length; i++) {
  63787. this._fixedNormal32[i] = this._normals32[i];
  63788. }
  63789. }
  63790. if (!this.mesh.areNormalsFrozen) {
  63791. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63792. }
  63793. }
  63794. if (this._depthSort && this._depthSortParticles) {
  63795. this.depthSortedParticles.sort(this._depthSortFunction);
  63796. var dspl = this.depthSortedParticles.length;
  63797. var sorted = 0;
  63798. var lind = 0;
  63799. var sind = 0;
  63800. var sid = 0;
  63801. for (sorted = 0; sorted < dspl; sorted++) {
  63802. lind = this.depthSortedParticles[sorted].indicesLength;
  63803. sind = this.depthSortedParticles[sorted].ind;
  63804. for (var i = 0; i < lind; i++) {
  63805. this._indices32[sid] = this._indices[sind + i];
  63806. sid++;
  63807. }
  63808. }
  63809. this.mesh.updateIndices(this._indices32);
  63810. }
  63811. }
  63812. if (this._computeBoundingBox) {
  63813. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63814. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63815. }
  63816. this.afterUpdateParticles(start, end, update);
  63817. return this;
  63818. };
  63819. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63820. this._halfroll = this._roll * 0.5;
  63821. this._halfpitch = this._pitch * 0.5;
  63822. this._halfyaw = this._yaw * 0.5;
  63823. this._sinRoll = Math.sin(this._halfroll);
  63824. this._cosRoll = Math.cos(this._halfroll);
  63825. this._sinPitch = Math.sin(this._halfpitch);
  63826. this._cosPitch = Math.cos(this._halfpitch);
  63827. this._sinYaw = Math.sin(this._halfyaw);
  63828. this._cosYaw = Math.cos(this._halfyaw);
  63829. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63830. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63831. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63832. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63833. };
  63834. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63835. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63836. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63837. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63838. this._rotMatrix.m[3] = 0;
  63839. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63840. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63841. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63842. this._rotMatrix.m[7] = 0;
  63843. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63844. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63845. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63846. this._rotMatrix.m[11] = 0;
  63847. this._rotMatrix.m[12] = 0;
  63848. this._rotMatrix.m[13] = 0;
  63849. this._rotMatrix.m[14] = 0;
  63850. this._rotMatrix.m[15] = 1.0;
  63851. };
  63852. /**
  63853. * Disposes the SPS.
  63854. */
  63855. SolidParticleSystem.prototype.dispose = function () {
  63856. this.mesh.dispose();
  63857. this.vars = null;
  63858. // drop references to internal big arrays for the GC
  63859. this._positions = null;
  63860. this._indices = null;
  63861. this._normals = null;
  63862. this._uvs = null;
  63863. this._colors = null;
  63864. this._indices32 = null;
  63865. this._positions32 = null;
  63866. this._normals32 = null;
  63867. this._fixedNormal32 = null;
  63868. this._uvs32 = null;
  63869. this._colors32 = null;
  63870. this.pickedParticles = null;
  63871. };
  63872. /**
  63873. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63874. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63875. * @returns the SPS.
  63876. */
  63877. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63878. if (!this._isVisibilityBoxLocked) {
  63879. this.mesh.refreshBoundingInfo();
  63880. }
  63881. return this;
  63882. };
  63883. /**
  63884. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63885. * @param size the size (float) of the visibility box
  63886. * note : this doesn't lock the SPS mesh bounding box.
  63887. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63888. */
  63889. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63890. var vis = size / 2;
  63891. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63892. };
  63893. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63894. /**
  63895. * Gets whether the SPS as always visible or not
  63896. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63897. */
  63898. get: function () {
  63899. return this._alwaysVisible;
  63900. },
  63901. /**
  63902. * Sets the SPS as always visible or not
  63903. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63904. */
  63905. set: function (val) {
  63906. this._alwaysVisible = val;
  63907. this.mesh.alwaysSelectAsActiveMesh = val;
  63908. },
  63909. enumerable: true,
  63910. configurable: true
  63911. });
  63912. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63913. /**
  63914. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63915. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63916. */
  63917. get: function () {
  63918. return this._isVisibilityBoxLocked;
  63919. },
  63920. /**
  63921. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63922. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63923. */
  63924. set: function (val) {
  63925. this._isVisibilityBoxLocked = val;
  63926. var boundingInfo = this.mesh.getBoundingInfo();
  63927. boundingInfo.isLocked = val;
  63928. },
  63929. enumerable: true,
  63930. configurable: true
  63931. });
  63932. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63933. /**
  63934. * Gets if `setParticles()` computes the particle rotations or not.
  63935. * Default value : true. The SPS is faster when it's set to false.
  63936. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63937. */
  63938. get: function () {
  63939. return this._computeParticleRotation;
  63940. },
  63941. /**
  63942. * Tells to `setParticles()` to compute the particle rotations or not.
  63943. * Default value : true. The SPS is faster when it's set to false.
  63944. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63945. */
  63946. set: function (val) {
  63947. this._computeParticleRotation = val;
  63948. },
  63949. enumerable: true,
  63950. configurable: true
  63951. });
  63952. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63953. /**
  63954. * Gets if `setParticles()` computes the particle colors or not.
  63955. * Default value : true. The SPS is faster when it's set to false.
  63956. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63957. */
  63958. get: function () {
  63959. return this._computeParticleColor;
  63960. },
  63961. /**
  63962. * Tells to `setParticles()` to compute the particle colors or not.
  63963. * Default value : true. The SPS is faster when it's set to false.
  63964. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63965. */
  63966. set: function (val) {
  63967. this._computeParticleColor = val;
  63968. },
  63969. enumerable: true,
  63970. configurable: true
  63971. });
  63972. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63973. /**
  63974. * Gets if `setParticles()` computes the particle textures or not.
  63975. * Default value : true. The SPS is faster when it's set to false.
  63976. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63977. */
  63978. get: function () {
  63979. return this._computeParticleTexture;
  63980. },
  63981. set: function (val) {
  63982. this._computeParticleTexture = val;
  63983. },
  63984. enumerable: true,
  63985. configurable: true
  63986. });
  63987. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63988. /**
  63989. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63990. * Default value : false. The SPS is faster when it's set to false.
  63991. * Note : the particle custom vertex positions aren't stored values.
  63992. */
  63993. get: function () {
  63994. return this._computeParticleVertex;
  63995. },
  63996. /**
  63997. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63998. * Default value : false. The SPS is faster when it's set to false.
  63999. * Note : the particle custom vertex positions aren't stored values.
  64000. */
  64001. set: function (val) {
  64002. this._computeParticleVertex = val;
  64003. },
  64004. enumerable: true,
  64005. configurable: true
  64006. });
  64007. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  64008. /**
  64009. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  64010. */
  64011. get: function () {
  64012. return this._computeBoundingBox;
  64013. },
  64014. /**
  64015. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  64016. */
  64017. set: function (val) {
  64018. this._computeBoundingBox = val;
  64019. },
  64020. enumerable: true,
  64021. configurable: true
  64022. });
  64023. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  64024. /**
  64025. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  64026. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64027. * Default : `true`
  64028. */
  64029. get: function () {
  64030. return this._depthSortParticles;
  64031. },
  64032. /**
  64033. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  64034. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64035. * Default : `true`
  64036. */
  64037. set: function (val) {
  64038. this._depthSortParticles = val;
  64039. },
  64040. enumerable: true,
  64041. configurable: true
  64042. });
  64043. // =======================================================================
  64044. // Particle behavior logic
  64045. // these following methods may be overwritten by the user to fit his needs
  64046. /**
  64047. * This function does nothing. It may be overwritten to set all the particle first values.
  64048. * The SPS doesn't call this function, you may have to call it by your own.
  64049. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64050. */
  64051. SolidParticleSystem.prototype.initParticles = function () {
  64052. };
  64053. /**
  64054. * This function does nothing. It may be overwritten to recycle a particle.
  64055. * The SPS doesn't call this function, you may have to call it by your own.
  64056. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64057. * @param particle The particle to recycle
  64058. * @returns the recycled particle
  64059. */
  64060. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  64061. return particle;
  64062. };
  64063. /**
  64064. * Updates a particle : this function should be overwritten by the user.
  64065. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  64066. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64067. * @example : just set a particle position or velocity and recycle conditions
  64068. * @param particle The particle to update
  64069. * @returns the updated particle
  64070. */
  64071. SolidParticleSystem.prototype.updateParticle = function (particle) {
  64072. return particle;
  64073. };
  64074. /**
  64075. * Updates a vertex of a particle : it can be overwritten by the user.
  64076. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  64077. * @param particle the current particle
  64078. * @param vertex the current index of the current particle
  64079. * @param pt the index of the current vertex in the particle shape
  64080. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  64081. * @example : just set a vertex particle position
  64082. * @returns the updated vertex
  64083. */
  64084. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  64085. return vertex;
  64086. };
  64087. /**
  64088. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  64089. * This does nothing and may be overwritten by the user.
  64090. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64091. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64092. * @param update the boolean update value actually passed to setParticles()
  64093. */
  64094. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  64095. };
  64096. /**
  64097. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  64098. * This will be passed three parameters.
  64099. * This does nothing and may be overwritten by the user.
  64100. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64101. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64102. * @param update the boolean update value actually passed to setParticles()
  64103. */
  64104. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  64105. };
  64106. return SolidParticleSystem;
  64107. }());
  64108. BABYLON.SolidParticleSystem = SolidParticleSystem;
  64109. })(BABYLON || (BABYLON = {}));
  64110. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  64111. var BABYLON;
  64112. (function (BABYLON) {
  64113. /**
  64114. * Class containing static functions to help procedurally build meshes
  64115. */
  64116. var MeshBuilder = /** @class */ (function () {
  64117. function MeshBuilder() {
  64118. }
  64119. MeshBuilder.updateSideOrientation = function (orientation) {
  64120. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  64121. return BABYLON.Mesh.DOUBLESIDE;
  64122. }
  64123. if (orientation === undefined || orientation === null) {
  64124. return BABYLON.Mesh.FRONTSIDE;
  64125. }
  64126. return orientation;
  64127. };
  64128. /**
  64129. * Creates a box mesh
  64130. * * The parameter `size` sets the size (float) of each box side (default 1)
  64131. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  64132. * * 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)
  64133. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64134. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64135. * * 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
  64136. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64137. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  64138. * @param name defines the name of the mesh
  64139. * @param options defines the options used to create the mesh
  64140. * @param scene defines the hosting scene
  64141. * @returns the box mesh
  64142. */
  64143. MeshBuilder.CreateBox = function (name, options, scene) {
  64144. if (scene === void 0) { scene = null; }
  64145. var box = new BABYLON.Mesh(name, scene);
  64146. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64147. box._originalBuilderSideOrientation = options.sideOrientation;
  64148. var vertexData = BABYLON.VertexData.CreateBox(options);
  64149. vertexData.applyToMesh(box, options.updatable);
  64150. return box;
  64151. };
  64152. /**
  64153. * Creates a sphere mesh
  64154. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  64155. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  64156. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  64157. * * 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
  64158. * * 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)
  64159. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64160. * * 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
  64161. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64162. * @param name defines the name of the mesh
  64163. * @param options defines the options used to create the mesh
  64164. * @param scene defines the hosting scene
  64165. * @returns the sphere mesh
  64166. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  64167. */
  64168. MeshBuilder.CreateSphere = function (name, options, scene) {
  64169. var sphere = new BABYLON.Mesh(name, scene);
  64170. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64171. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64172. var vertexData = BABYLON.VertexData.CreateSphere(options);
  64173. vertexData.applyToMesh(sphere, options.updatable);
  64174. return sphere;
  64175. };
  64176. /**
  64177. * Creates a plane polygonal mesh. By default, this is a disc
  64178. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  64179. * * 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
  64180. * * 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
  64181. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64182. * * 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
  64183. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64184. * @param name defines the name of the mesh
  64185. * @param options defines the options used to create the mesh
  64186. * @param scene defines the hosting scene
  64187. * @returns the plane polygonal mesh
  64188. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  64189. */
  64190. MeshBuilder.CreateDisc = function (name, options, scene) {
  64191. if (scene === void 0) { scene = null; }
  64192. var disc = new BABYLON.Mesh(name, scene);
  64193. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64194. disc._originalBuilderSideOrientation = options.sideOrientation;
  64195. var vertexData = BABYLON.VertexData.CreateDisc(options);
  64196. vertexData.applyToMesh(disc, options.updatable);
  64197. return disc;
  64198. };
  64199. /**
  64200. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  64201. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  64202. * * 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`)
  64203. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  64204. * * 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
  64205. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64206. * * 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
  64207. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64208. * @param name defines the name of the mesh
  64209. * @param options defines the options used to create the mesh
  64210. * @param scene defines the hosting scene
  64211. * @returns the icosahedron mesh
  64212. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  64213. */
  64214. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  64215. var sphere = new BABYLON.Mesh(name, scene);
  64216. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64217. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64218. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  64219. vertexData.applyToMesh(sphere, options.updatable);
  64220. return sphere;
  64221. };
  64222. ;
  64223. /**
  64224. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64225. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  64226. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  64227. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  64228. * * 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
  64229. * * 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
  64230. * * 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
  64231. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64232. * * 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
  64233. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64234. * * 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
  64235. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  64236. * * 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
  64237. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  64238. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64239. * @param name defines the name of the mesh
  64240. * @param options defines the options used to create the mesh
  64241. * @param scene defines the hosting scene
  64242. * @returns the ribbon mesh
  64243. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  64244. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64245. */
  64246. MeshBuilder.CreateRibbon = function (name, options, scene) {
  64247. if (scene === void 0) { scene = null; }
  64248. var pathArray = options.pathArray;
  64249. var closeArray = options.closeArray;
  64250. var closePath = options.closePath;
  64251. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64252. var instance = options.instance;
  64253. var updatable = options.updatable;
  64254. if (instance) { // existing ribbon instance update
  64255. // positionFunction : ribbon case
  64256. // only pathArray and sideOrientation parameters are taken into account for positions update
  64257. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  64258. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  64259. var positionFunction = function (positions) {
  64260. var minlg = pathArray[0].length;
  64261. var i = 0;
  64262. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  64263. for (var si = 1; si <= ns; si++) {
  64264. for (var p = 0; p < pathArray.length; p++) {
  64265. var path = pathArray[p];
  64266. var l = path.length;
  64267. minlg = (minlg < l) ? minlg : l;
  64268. var j = 0;
  64269. while (j < minlg) {
  64270. positions[i] = path[j].x;
  64271. positions[i + 1] = path[j].y;
  64272. positions[i + 2] = path[j].z;
  64273. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  64274. BABYLON.Tmp.Vector3[0].x = path[j].x;
  64275. }
  64276. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  64277. BABYLON.Tmp.Vector3[1].x = path[j].x;
  64278. }
  64279. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  64280. BABYLON.Tmp.Vector3[0].y = path[j].y;
  64281. }
  64282. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  64283. BABYLON.Tmp.Vector3[1].y = path[j].y;
  64284. }
  64285. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  64286. BABYLON.Tmp.Vector3[0].z = path[j].z;
  64287. }
  64288. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  64289. BABYLON.Tmp.Vector3[1].z = path[j].z;
  64290. }
  64291. j++;
  64292. i += 3;
  64293. }
  64294. if (instance._closePath) {
  64295. positions[i] = path[0].x;
  64296. positions[i + 1] = path[0].y;
  64297. positions[i + 2] = path[0].z;
  64298. i += 3;
  64299. }
  64300. }
  64301. }
  64302. };
  64303. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64304. positionFunction(positions);
  64305. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  64306. instance._boundingInfo.update(instance._worldMatrix);
  64307. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64308. if (options.colors) {
  64309. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64310. for (var c = 0; c < options.colors.length; c++) {
  64311. colors[c * 4] = options.colors[c].r;
  64312. colors[c * 4 + 1] = options.colors[c].g;
  64313. colors[c * 4 + 2] = options.colors[c].b;
  64314. colors[c * 4 + 3] = options.colors[c].a;
  64315. }
  64316. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  64317. }
  64318. if (options.uvs) {
  64319. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64320. for (var i = 0; i < options.uvs.length; i++) {
  64321. uvs[i * 2] = options.uvs[i].x;
  64322. uvs[i * 2 + 1] = options.uvs[i].y;
  64323. }
  64324. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  64325. }
  64326. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  64327. var indices = instance.getIndices();
  64328. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64329. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  64330. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  64331. if (instance._closePath) {
  64332. var indexFirst = 0;
  64333. var indexLast = 0;
  64334. for (var p = 0; p < pathArray.length; p++) {
  64335. indexFirst = instance._idx[p] * 3;
  64336. if (p + 1 < pathArray.length) {
  64337. indexLast = (instance._idx[p + 1] - 1) * 3;
  64338. }
  64339. else {
  64340. indexLast = normals.length - 3;
  64341. }
  64342. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  64343. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  64344. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  64345. normals[indexLast] = normals[indexFirst];
  64346. normals[indexLast + 1] = normals[indexFirst + 1];
  64347. normals[indexLast + 2] = normals[indexFirst + 2];
  64348. }
  64349. }
  64350. if (!(instance.areNormalsFrozen)) {
  64351. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  64352. }
  64353. }
  64354. return instance;
  64355. }
  64356. else { // new ribbon creation
  64357. var ribbon = new BABYLON.Mesh(name, scene);
  64358. ribbon._originalBuilderSideOrientation = sideOrientation;
  64359. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  64360. if (closePath) {
  64361. ribbon._idx = vertexData._idx;
  64362. }
  64363. ribbon._closePath = closePath;
  64364. ribbon._closeArray = closeArray;
  64365. vertexData.applyToMesh(ribbon, updatable);
  64366. return ribbon;
  64367. }
  64368. };
  64369. /**
  64370. * Creates a cylinder or a cone mesh
  64371. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  64372. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  64373. * * 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.
  64374. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  64375. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  64376. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  64377. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  64378. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  64379. * * 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).
  64380. * * 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
  64381. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  64382. * * 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
  64383. * * 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.
  64384. * * If `enclose` is false, a ring surface is one element.
  64385. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  64386. * * 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
  64387. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64388. * * 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
  64389. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64390. * @param name defines the name of the mesh
  64391. * @param options defines the options used to create the mesh
  64392. * @param scene defines the hosting scene
  64393. * @returns the cylinder mesh
  64394. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  64395. */
  64396. MeshBuilder.CreateCylinder = function (name, options, scene) {
  64397. var cylinder = new BABYLON.Mesh(name, scene);
  64398. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64399. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  64400. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  64401. vertexData.applyToMesh(cylinder, options.updatable);
  64402. return cylinder;
  64403. };
  64404. /**
  64405. * Creates a torus mesh
  64406. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  64407. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  64408. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  64409. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64410. * * 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
  64411. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64412. * @param name defines the name of the mesh
  64413. * @param options defines the options used to create the mesh
  64414. * @param scene defines the hosting scene
  64415. * @returns the torus mesh
  64416. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  64417. */
  64418. MeshBuilder.CreateTorus = function (name, options, scene) {
  64419. var torus = new BABYLON.Mesh(name, scene);
  64420. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64421. torus._originalBuilderSideOrientation = options.sideOrientation;
  64422. var vertexData = BABYLON.VertexData.CreateTorus(options);
  64423. vertexData.applyToMesh(torus, options.updatable);
  64424. return torus;
  64425. };
  64426. /**
  64427. * Creates a torus knot mesh
  64428. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  64429. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  64430. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  64431. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  64432. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64433. * * 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
  64434. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64435. * @param name defines the name of the mesh
  64436. * @param options defines the options used to create the mesh
  64437. * @param scene defines the hosting scene
  64438. * @returns the torus knot mesh
  64439. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  64440. */
  64441. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  64442. var torusKnot = new BABYLON.Mesh(name, scene);
  64443. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64444. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  64445. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  64446. vertexData.applyToMesh(torusKnot, options.updatable);
  64447. return torusKnot;
  64448. };
  64449. /**
  64450. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64451. * * 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
  64452. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64453. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64454. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64455. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64456. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64457. * * 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
  64458. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64459. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64460. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64461. * @param name defines the name of the new line system
  64462. * @param options defines the options used to create the line system
  64463. * @param scene defines the hosting scene
  64464. * @returns a new line system mesh
  64465. */
  64466. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64467. var instance = options.instance;
  64468. var lines = options.lines;
  64469. var colors = options.colors;
  64470. if (instance) { // lines update
  64471. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64472. var vertexColor;
  64473. var lineColors;
  64474. if (colors) {
  64475. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64476. }
  64477. var i = 0;
  64478. var c = 0;
  64479. for (var l = 0; l < lines.length; l++) {
  64480. var points = lines[l];
  64481. for (var p = 0; p < points.length; p++) {
  64482. positions[i] = points[p].x;
  64483. positions[i + 1] = points[p].y;
  64484. positions[i + 2] = points[p].z;
  64485. if (colors && vertexColor) {
  64486. lineColors = colors[l];
  64487. vertexColor[c] = lineColors[p].r;
  64488. vertexColor[c + 1] = lineColors[p].g;
  64489. vertexColor[c + 2] = lineColors[p].b;
  64490. vertexColor[c + 3] = lineColors[p].a;
  64491. c += 4;
  64492. }
  64493. i += 3;
  64494. }
  64495. }
  64496. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64497. if (colors && vertexColor) {
  64498. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64499. }
  64500. return instance;
  64501. }
  64502. // line system creation
  64503. var useVertexColor = (colors) ? true : false;
  64504. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64505. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64506. vertexData.applyToMesh(lineSystem, options.updatable);
  64507. return lineSystem;
  64508. };
  64509. /**
  64510. * Creates a line mesh
  64511. * 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
  64512. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64513. * * The parameter `points` is an array successive Vector3
  64514. * * 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
  64515. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64516. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64517. * * When updating an instance, remember that only point positions can change, not the number of points
  64518. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64519. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64520. * @param name defines the name of the new line system
  64521. * @param options defines the options used to create the line system
  64522. * @param scene defines the hosting scene
  64523. * @returns a new line mesh
  64524. */
  64525. MeshBuilder.CreateLines = function (name, options, scene) {
  64526. if (scene === void 0) { scene = null; }
  64527. var colors = (options.colors) ? [options.colors] : null;
  64528. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64529. return lines;
  64530. };
  64531. /**
  64532. * Creates a dashed line mesh
  64533. * * 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
  64534. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64535. * * The parameter `points` is an array successive Vector3
  64536. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64537. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64538. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64539. * * 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
  64540. * * When updating an instance, remember that only point positions can change, not the number of points
  64541. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64542. * @param name defines the name of the mesh
  64543. * @param options defines the options used to create the mesh
  64544. * @param scene defines the hosting scene
  64545. * @returns the dashed line mesh
  64546. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64547. */
  64548. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64549. if (scene === void 0) { scene = null; }
  64550. var points = options.points;
  64551. var instance = options.instance;
  64552. var gapSize = options.gapSize || 1;
  64553. var dashSize = options.dashSize || 3;
  64554. if (instance) { // dashed lines update
  64555. var positionFunction = function (positions) {
  64556. var curvect = BABYLON.Vector3.Zero();
  64557. var nbSeg = positions.length / 6;
  64558. var lg = 0;
  64559. var nb = 0;
  64560. var shft = 0;
  64561. var dashshft = 0;
  64562. var curshft = 0;
  64563. var p = 0;
  64564. var i = 0;
  64565. var j = 0;
  64566. for (i = 0; i < points.length - 1; i++) {
  64567. points[i + 1].subtractToRef(points[i], curvect);
  64568. lg += curvect.length();
  64569. }
  64570. shft = lg / nbSeg;
  64571. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64572. for (i = 0; i < points.length - 1; i++) {
  64573. points[i + 1].subtractToRef(points[i], curvect);
  64574. nb = Math.floor(curvect.length() / shft);
  64575. curvect.normalize();
  64576. j = 0;
  64577. while (j < nb && p < positions.length) {
  64578. curshft = shft * j;
  64579. positions[p] = points[i].x + curshft * curvect.x;
  64580. positions[p + 1] = points[i].y + curshft * curvect.y;
  64581. positions[p + 2] = points[i].z + curshft * curvect.z;
  64582. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64583. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64584. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64585. p += 6;
  64586. j++;
  64587. }
  64588. }
  64589. while (p < positions.length) {
  64590. positions[p] = points[i].x;
  64591. positions[p + 1] = points[i].y;
  64592. positions[p + 2] = points[i].z;
  64593. p += 3;
  64594. }
  64595. };
  64596. instance.updateMeshPositions(positionFunction, false);
  64597. return instance;
  64598. }
  64599. // dashed lines creation
  64600. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64601. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64602. vertexData.applyToMesh(dashedLines, options.updatable);
  64603. dashedLines.dashSize = dashSize;
  64604. dashedLines.gapSize = gapSize;
  64605. return dashedLines;
  64606. };
  64607. /**
  64608. * 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.
  64609. * * 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.
  64610. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64611. * * 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.
  64612. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64613. * * 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
  64614. * * 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
  64615. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64616. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64617. * * 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
  64618. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64619. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64620. * @param name defines the name of the mesh
  64621. * @param options defines the options used to create the mesh
  64622. * @param scene defines the hosting scene
  64623. * @returns the extruded shape mesh
  64624. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64625. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64626. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64627. */
  64628. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64629. if (scene === void 0) { scene = null; }
  64630. var path = options.path;
  64631. var shape = options.shape;
  64632. var scale = options.scale || 1;
  64633. var rotation = options.rotation || 0;
  64634. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64635. var updatable = options.updatable;
  64636. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64637. var instance = options.instance || null;
  64638. var invertUV = options.invertUV || false;
  64639. 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);
  64640. };
  64641. /**
  64642. * Creates an custom extruded shape mesh.
  64643. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64644. * * 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.
  64645. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64646. * * 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
  64647. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64648. * * 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
  64649. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64650. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64651. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64652. * * 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
  64653. * * 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
  64654. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64655. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64656. * * 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
  64657. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64658. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64659. * @param name defines the name of the mesh
  64660. * @param options defines the options used to create the mesh
  64661. * @param scene defines the hosting scene
  64662. * @returns the custom extruded shape mesh
  64663. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64664. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64665. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64666. */
  64667. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64668. var path = options.path;
  64669. var shape = options.shape;
  64670. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64671. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64672. var ribbonCloseArray = options.ribbonCloseArray || false;
  64673. var ribbonClosePath = options.ribbonClosePath || false;
  64674. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64675. var updatable = options.updatable;
  64676. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64677. var instance = options.instance;
  64678. var invertUV = options.invertUV || false;
  64679. 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);
  64680. };
  64681. /**
  64682. * Creates lathe mesh.
  64683. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64684. * * 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
  64685. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64686. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64687. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64688. * * 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
  64689. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64690. * * 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
  64691. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64692. * * 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
  64693. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64694. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64695. * @param name defines the name of the mesh
  64696. * @param options defines the options used to create the mesh
  64697. * @param scene defines the hosting scene
  64698. * @returns the lathe mesh
  64699. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64700. */
  64701. MeshBuilder.CreateLathe = function (name, options, scene) {
  64702. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64703. var closed = (options.closed === undefined) ? true : options.closed;
  64704. var shape = options.shape;
  64705. var radius = options.radius || 1;
  64706. var tessellation = options.tessellation || 64;
  64707. var clip = options.clip || 0;
  64708. var updatable = options.updatable;
  64709. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64710. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64711. var pi2 = Math.PI * 2;
  64712. var paths = new Array();
  64713. var invertUV = options.invertUV || false;
  64714. var i = 0;
  64715. var p = 0;
  64716. var step = pi2 / tessellation * arc;
  64717. var rotated;
  64718. var path = new Array();
  64719. for (i = 0; i <= tessellation - clip; i++) {
  64720. var path = [];
  64721. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64722. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64723. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64724. }
  64725. for (p = 0; p < shape.length; p++) {
  64726. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64727. path.push(rotated);
  64728. }
  64729. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64730. 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));
  64731. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64732. }
  64733. paths.push(path);
  64734. }
  64735. // lathe ribbon
  64736. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64737. return lathe;
  64738. };
  64739. /**
  64740. * Creates a plane mesh
  64741. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64742. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64743. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64744. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64745. * * 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
  64746. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64747. * @param name defines the name of the mesh
  64748. * @param options defines the options used to create the mesh
  64749. * @param scene defines the hosting scene
  64750. * @returns the plane mesh
  64751. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64752. */
  64753. MeshBuilder.CreatePlane = function (name, options, scene) {
  64754. var plane = new BABYLON.Mesh(name, scene);
  64755. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64756. plane._originalBuilderSideOrientation = options.sideOrientation;
  64757. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64758. vertexData.applyToMesh(plane, options.updatable);
  64759. if (options.sourcePlane) {
  64760. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64761. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64762. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64763. plane.rotate(vectorProduct, product);
  64764. }
  64765. return plane;
  64766. };
  64767. /**
  64768. * Creates a ground mesh
  64769. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64770. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64771. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64772. * @param name defines the name of the mesh
  64773. * @param options defines the options used to create the mesh
  64774. * @param scene defines the hosting scene
  64775. * @returns the ground mesh
  64776. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64777. */
  64778. MeshBuilder.CreateGround = function (name, options, scene) {
  64779. var ground = new BABYLON.GroundMesh(name, scene);
  64780. ground._setReady(false);
  64781. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64782. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64783. ground._width = options.width || 1;
  64784. ground._height = options.height || 1;
  64785. ground._maxX = ground._width / 2;
  64786. ground._maxZ = ground._height / 2;
  64787. ground._minX = -ground._maxX;
  64788. ground._minZ = -ground._maxZ;
  64789. var vertexData = BABYLON.VertexData.CreateGround(options);
  64790. vertexData.applyToMesh(ground, options.updatable);
  64791. ground._setReady(true);
  64792. return ground;
  64793. };
  64794. /**
  64795. * Creates a tiled ground mesh
  64796. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64797. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64798. * * 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
  64799. * * 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
  64800. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64801. * @param name defines the name of the mesh
  64802. * @param options defines the options used to create the mesh
  64803. * @param scene defines the hosting scene
  64804. * @returns the tiled ground mesh
  64805. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64806. */
  64807. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64808. var tiledGround = new BABYLON.Mesh(name, scene);
  64809. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64810. vertexData.applyToMesh(tiledGround, options.updatable);
  64811. return tiledGround;
  64812. };
  64813. /**
  64814. * Creates a ground mesh from a height map
  64815. * * The parameter `url` sets the URL of the height map image resource.
  64816. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64817. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64818. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64819. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64820. * * 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.
  64821. * * 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).
  64822. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64823. * @param name defines the name of the mesh
  64824. * @param url defines the url to the height map
  64825. * @param options defines the options used to create the mesh
  64826. * @param scene defines the hosting scene
  64827. * @returns the ground mesh
  64828. * @see http://doc.babylonjs.com/babylon101/height_map
  64829. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64830. */
  64831. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64832. var width = options.width || 10.0;
  64833. var height = options.height || 10.0;
  64834. var subdivisions = options.subdivisions || 1 | 0;
  64835. var minHeight = options.minHeight || 0.0;
  64836. var maxHeight = options.maxHeight || 1.0;
  64837. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64838. var updatable = options.updatable;
  64839. var onReady = options.onReady;
  64840. var ground = new BABYLON.GroundMesh(name, scene);
  64841. ground._subdivisionsX = subdivisions;
  64842. ground._subdivisionsY = subdivisions;
  64843. ground._width = width;
  64844. ground._height = height;
  64845. ground._maxX = ground._width / 2.0;
  64846. ground._maxZ = ground._height / 2.0;
  64847. ground._minX = -ground._maxX;
  64848. ground._minZ = -ground._maxZ;
  64849. ground._setReady(false);
  64850. var onload = function (img) {
  64851. // Getting height map data
  64852. var canvas = document.createElement("canvas");
  64853. var context = canvas.getContext("2d");
  64854. if (!context) {
  64855. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64856. }
  64857. if (scene.isDisposed) {
  64858. return;
  64859. }
  64860. var bufferWidth = img.width;
  64861. var bufferHeight = img.height;
  64862. canvas.width = bufferWidth;
  64863. canvas.height = bufferHeight;
  64864. context.drawImage(img, 0, 0);
  64865. // Create VertexData from map data
  64866. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64867. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64868. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64869. width: width, height: height,
  64870. subdivisions: subdivisions,
  64871. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64872. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  64873. });
  64874. vertexData.applyToMesh(ground, updatable);
  64875. //execute ready callback, if set
  64876. if (onReady) {
  64877. onReady(ground);
  64878. }
  64879. ground._setReady(true);
  64880. };
  64881. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64882. return ground;
  64883. };
  64884. /**
  64885. * Creates a polygon mesh
  64886. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64887. * * 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
  64888. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64889. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64890. * * 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)
  64891. * * Remember you can only change the shape positions, not their number when updating a polygon
  64892. * @param name defines the name of the mesh
  64893. * @param options defines the options used to create the mesh
  64894. * @param scene defines the hosting scene
  64895. * @returns the polygon mesh
  64896. */
  64897. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64898. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64899. var shape = options.shape;
  64900. var holes = options.holes || [];
  64901. var depth = options.depth || 0;
  64902. var contours = [];
  64903. var hole = [];
  64904. for (var i = 0; i < shape.length; i++) {
  64905. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64906. }
  64907. var epsilon = 0.00000001;
  64908. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64909. contours.pop();
  64910. }
  64911. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64912. for (var hNb = 0; hNb < holes.length; hNb++) {
  64913. hole = [];
  64914. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64915. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64916. }
  64917. polygonTriangulation.addHole(hole);
  64918. }
  64919. var polygon = polygonTriangulation.build(options.updatable, depth);
  64920. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64921. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64922. vertexData.applyToMesh(polygon, options.updatable);
  64923. return polygon;
  64924. };
  64925. ;
  64926. /**
  64927. * Creates an extruded polygon mesh, with depth in the Y direction.
  64928. * * 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)
  64929. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64930. * @param name defines the name of the mesh
  64931. * @param options defines the options used to create the mesh
  64932. * @param scene defines the hosting scene
  64933. * @returns the polygon mesh
  64934. */
  64935. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64936. return MeshBuilder.CreatePolygon(name, options, scene);
  64937. };
  64938. ;
  64939. /**
  64940. * Creates a tube mesh.
  64941. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64942. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64943. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64944. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64945. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64946. * * 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)
  64947. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64948. * * 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
  64949. * * 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
  64950. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64951. * * 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
  64952. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64953. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64954. * @param name defines the name of the mesh
  64955. * @param options defines the options used to create the mesh
  64956. * @param scene defines the hosting scene
  64957. * @returns the tube mesh
  64958. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64959. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64960. */
  64961. MeshBuilder.CreateTube = function (name, options, scene) {
  64962. var path = options.path;
  64963. var instance = options.instance;
  64964. var radius = 1.0;
  64965. if (instance) {
  64966. radius = instance.radius;
  64967. }
  64968. if (options.radius !== undefined) {
  64969. radius = options.radius;
  64970. }
  64971. ;
  64972. var tessellation = options.tessellation || 64 | 0;
  64973. var radiusFunction = options.radiusFunction || null;
  64974. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64975. var invertUV = options.invertUV || false;
  64976. var updatable = options.updatable;
  64977. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64978. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64979. // tube geometry
  64980. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64981. var tangents = path3D.getTangents();
  64982. var normals = path3D.getNormals();
  64983. var distances = path3D.getDistances();
  64984. var pi2 = Math.PI * 2;
  64985. var step = pi2 / tessellation * arc;
  64986. var returnRadius = function () { return radius; };
  64987. var radiusFunctionFinal = radiusFunction || returnRadius;
  64988. var circlePath;
  64989. var rad;
  64990. var normal;
  64991. var rotated;
  64992. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64993. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64994. for (var i = 0; i < path.length; i++) {
  64995. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64996. circlePath = Array(); // current circle array
  64997. normal = normals[i]; // current normal
  64998. for (var t = 0; t < tessellation; t++) {
  64999. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  65000. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  65001. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  65002. rotated.scaleInPlace(rad).addInPlace(path[i]);
  65003. circlePath[t] = rotated;
  65004. }
  65005. circlePaths[index] = circlePath;
  65006. index++;
  65007. }
  65008. // cap
  65009. var capPath = function (nbPoints, pathIndex) {
  65010. var pointCap = Array();
  65011. for (var i = 0; i < nbPoints; i++) {
  65012. pointCap.push(path[pathIndex]);
  65013. }
  65014. return pointCap;
  65015. };
  65016. switch (cap) {
  65017. case BABYLON.Mesh.NO_CAP:
  65018. break;
  65019. case BABYLON.Mesh.CAP_START:
  65020. circlePaths[0] = capPath(tessellation, 0);
  65021. circlePaths[1] = circlePaths[2].slice(0);
  65022. break;
  65023. case BABYLON.Mesh.CAP_END:
  65024. circlePaths[index] = circlePaths[index - 1].slice(0);
  65025. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65026. break;
  65027. case BABYLON.Mesh.CAP_ALL:
  65028. circlePaths[0] = capPath(tessellation, 0);
  65029. circlePaths[1] = circlePaths[2].slice(0);
  65030. circlePaths[index] = circlePaths[index - 1].slice(0);
  65031. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65032. break;
  65033. default:
  65034. break;
  65035. }
  65036. return circlePaths;
  65037. };
  65038. var path3D;
  65039. var pathArray;
  65040. if (instance) { // tube update
  65041. var arc = options.arc || instance.arc;
  65042. path3D = (instance.path3D).update(path);
  65043. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  65044. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  65045. instance.path3D = path3D;
  65046. instance.pathArray = pathArray;
  65047. instance.arc = arc;
  65048. instance.radius = radius;
  65049. return instance;
  65050. }
  65051. // tube creation
  65052. path3D = new BABYLON.Path3D(path);
  65053. var newPathArray = new Array();
  65054. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65055. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  65056. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  65057. tube.pathArray = pathArray;
  65058. tube.path3D = path3D;
  65059. tube.tessellation = tessellation;
  65060. tube.cap = cap;
  65061. tube.arc = options.arc;
  65062. tube.radius = radius;
  65063. return tube;
  65064. };
  65065. /**
  65066. * Creates a polyhedron mesh
  65067. * * 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
  65068. * * The parameter `size` (positive float, default 1) sets the polygon size
  65069. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  65070. * * 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`
  65071. * * 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
  65072. * * 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)`)
  65073. * * 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
  65074. * * 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
  65075. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65076. * * 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
  65077. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65078. * @param name defines the name of the mesh
  65079. * @param options defines the options used to create the mesh
  65080. * @param scene defines the hosting scene
  65081. * @returns the polyhedron mesh
  65082. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  65083. */
  65084. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  65085. var polyhedron = new BABYLON.Mesh(name, scene);
  65086. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65087. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  65088. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  65089. vertexData.applyToMesh(polyhedron, options.updatable);
  65090. return polyhedron;
  65091. };
  65092. /**
  65093. * Creates a decal mesh.
  65094. * 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
  65095. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  65096. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  65097. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  65098. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  65099. * @param name defines the name of the mesh
  65100. * @param sourceMesh defines the mesh where the decal must be applied
  65101. * @param options defines the options used to create the mesh
  65102. * @param scene defines the hosting scene
  65103. * @returns the decal mesh
  65104. * @see http://doc.babylonjs.com/how_to/decals
  65105. */
  65106. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  65107. var indices = sourceMesh.getIndices();
  65108. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65109. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65110. var position = options.position || BABYLON.Vector3.Zero();
  65111. var normal = options.normal || BABYLON.Vector3.Up();
  65112. var size = options.size || BABYLON.Vector3.One();
  65113. var angle = options.angle || 0;
  65114. // Getting correct rotation
  65115. if (!normal) {
  65116. var target = new BABYLON.Vector3(0, 0, 1);
  65117. var camera = sourceMesh.getScene().activeCamera;
  65118. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  65119. normal = camera.globalPosition.subtract(cameraWorldTarget);
  65120. }
  65121. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  65122. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  65123. var pitch = Math.atan2(normal.y, len);
  65124. // Matrix
  65125. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  65126. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  65127. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  65128. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  65129. var vertexData = new BABYLON.VertexData();
  65130. vertexData.indices = [];
  65131. vertexData.positions = [];
  65132. vertexData.normals = [];
  65133. vertexData.uvs = [];
  65134. var currentVertexDataIndex = 0;
  65135. var extractDecalVector3 = function (indexId) {
  65136. var result = new BABYLON.PositionNormalVertex();
  65137. if (!indices || !positions || !normals) {
  65138. return result;
  65139. }
  65140. var vertexId = indices[indexId];
  65141. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  65142. // Send vector to decal local world
  65143. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  65144. // Get normal
  65145. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  65146. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  65147. return result;
  65148. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  65149. var clip = function (vertices, axis) {
  65150. if (vertices.length === 0) {
  65151. return vertices;
  65152. }
  65153. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  65154. var clipVertices = function (v0, v1) {
  65155. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  65156. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  65157. };
  65158. var result = new Array();
  65159. for (var index = 0; index < vertices.length; index += 3) {
  65160. var v1Out;
  65161. var v2Out;
  65162. var v3Out;
  65163. var total = 0;
  65164. var nV1 = null;
  65165. var nV2 = null;
  65166. var nV3 = null;
  65167. var nV4 = null;
  65168. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  65169. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  65170. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  65171. v1Out = d1 > 0;
  65172. v2Out = d2 > 0;
  65173. v3Out = d3 > 0;
  65174. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  65175. switch (total) {
  65176. case 0:
  65177. result.push(vertices[index]);
  65178. result.push(vertices[index + 1]);
  65179. result.push(vertices[index + 2]);
  65180. break;
  65181. case 1:
  65182. if (v1Out) {
  65183. nV1 = vertices[index + 1];
  65184. nV2 = vertices[index + 2];
  65185. nV3 = clipVertices(vertices[index], nV1);
  65186. nV4 = clipVertices(vertices[index], nV2);
  65187. }
  65188. if (v2Out) {
  65189. nV1 = vertices[index];
  65190. nV2 = vertices[index + 2];
  65191. nV3 = clipVertices(vertices[index + 1], nV1);
  65192. nV4 = clipVertices(vertices[index + 1], nV2);
  65193. result.push(nV3);
  65194. result.push(nV2.clone());
  65195. result.push(nV1.clone());
  65196. result.push(nV2.clone());
  65197. result.push(nV3.clone());
  65198. result.push(nV4);
  65199. break;
  65200. }
  65201. if (v3Out) {
  65202. nV1 = vertices[index];
  65203. nV2 = vertices[index + 1];
  65204. nV3 = clipVertices(vertices[index + 2], nV1);
  65205. nV4 = clipVertices(vertices[index + 2], nV2);
  65206. }
  65207. if (nV1 && nV2 && nV3 && nV4) {
  65208. result.push(nV1.clone());
  65209. result.push(nV2.clone());
  65210. result.push(nV3);
  65211. result.push(nV4);
  65212. result.push(nV3.clone());
  65213. result.push(nV2.clone());
  65214. }
  65215. break;
  65216. case 2:
  65217. if (!v1Out) {
  65218. nV1 = vertices[index].clone();
  65219. nV2 = clipVertices(nV1, vertices[index + 1]);
  65220. nV3 = clipVertices(nV1, vertices[index + 2]);
  65221. result.push(nV1);
  65222. result.push(nV2);
  65223. result.push(nV3);
  65224. }
  65225. if (!v2Out) {
  65226. nV1 = vertices[index + 1].clone();
  65227. nV2 = clipVertices(nV1, vertices[index + 2]);
  65228. nV3 = clipVertices(nV1, vertices[index]);
  65229. result.push(nV1);
  65230. result.push(nV2);
  65231. result.push(nV3);
  65232. }
  65233. if (!v3Out) {
  65234. nV1 = vertices[index + 2].clone();
  65235. nV2 = clipVertices(nV1, vertices[index]);
  65236. nV3 = clipVertices(nV1, vertices[index + 1]);
  65237. result.push(nV1);
  65238. result.push(nV2);
  65239. result.push(nV3);
  65240. }
  65241. break;
  65242. case 3:
  65243. break;
  65244. }
  65245. }
  65246. return result;
  65247. };
  65248. for (var index = 0; index < indices.length; index += 3) {
  65249. var faceVertices = new Array();
  65250. faceVertices.push(extractDecalVector3(index));
  65251. faceVertices.push(extractDecalVector3(index + 1));
  65252. faceVertices.push(extractDecalVector3(index + 2));
  65253. // Clip
  65254. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  65255. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  65256. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  65257. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  65258. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  65259. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  65260. if (faceVertices.length === 0) {
  65261. continue;
  65262. }
  65263. // Add UVs and get back to world
  65264. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  65265. var vertex = faceVertices[vIndex];
  65266. //TODO check for Int32Array | Uint32Array | Uint16Array
  65267. vertexData.indices.push(currentVertexDataIndex);
  65268. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  65269. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  65270. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  65271. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  65272. currentVertexDataIndex++;
  65273. }
  65274. }
  65275. // Return mesh
  65276. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  65277. vertexData.applyToMesh(decal);
  65278. decal.position = position.clone();
  65279. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  65280. return decal;
  65281. };
  65282. // Privates
  65283. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  65284. // extrusion geometry
  65285. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  65286. var tangents = path3D.getTangents();
  65287. var normals = path3D.getNormals();
  65288. var binormals = path3D.getBinormals();
  65289. var distances = path3D.getDistances();
  65290. var angle = 0;
  65291. var returnScale = function () { return scale !== null ? scale : 1; };
  65292. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  65293. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  65294. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  65295. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65296. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65297. for (var i = 0; i < curve.length; i++) {
  65298. var shapePath = new Array();
  65299. var angleStep = rotate(i, distances[i]);
  65300. var scaleRatio = scl(i, distances[i]);
  65301. for (var p = 0; p < shape.length; p++) {
  65302. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  65303. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  65304. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  65305. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  65306. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  65307. shapePath[p] = rotated;
  65308. }
  65309. shapePaths[index] = shapePath;
  65310. angle += angleStep;
  65311. index++;
  65312. }
  65313. // cap
  65314. var capPath = function (shapePath) {
  65315. var pointCap = Array();
  65316. var barycenter = BABYLON.Vector3.Zero();
  65317. var i;
  65318. for (i = 0; i < shapePath.length; i++) {
  65319. barycenter.addInPlace(shapePath[i]);
  65320. }
  65321. barycenter.scaleInPlace(1.0 / shapePath.length);
  65322. for (i = 0; i < shapePath.length; i++) {
  65323. pointCap.push(barycenter);
  65324. }
  65325. return pointCap;
  65326. };
  65327. switch (cap) {
  65328. case BABYLON.Mesh.NO_CAP:
  65329. break;
  65330. case BABYLON.Mesh.CAP_START:
  65331. shapePaths[0] = capPath(shapePaths[2]);
  65332. shapePaths[1] = shapePaths[2];
  65333. break;
  65334. case BABYLON.Mesh.CAP_END:
  65335. shapePaths[index] = shapePaths[index - 1];
  65336. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65337. break;
  65338. case BABYLON.Mesh.CAP_ALL:
  65339. shapePaths[0] = capPath(shapePaths[2]);
  65340. shapePaths[1] = shapePaths[2];
  65341. shapePaths[index] = shapePaths[index - 1];
  65342. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65343. break;
  65344. default:
  65345. break;
  65346. }
  65347. return shapePaths;
  65348. };
  65349. var path3D;
  65350. var pathArray;
  65351. if (instance) { // instance update
  65352. path3D = (instance.path3D).update(curve);
  65353. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  65354. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  65355. return instance;
  65356. }
  65357. // extruded shape creation
  65358. path3D = new BABYLON.Path3D(curve);
  65359. var newShapePaths = new Array();
  65360. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65361. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  65362. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  65363. extrudedGeneric.pathArray = pathArray;
  65364. extrudedGeneric.path3D = path3D;
  65365. extrudedGeneric.cap = cap;
  65366. return extrudedGeneric;
  65367. };
  65368. return MeshBuilder;
  65369. }());
  65370. BABYLON.MeshBuilder = MeshBuilder;
  65371. })(BABYLON || (BABYLON = {}));
  65372. //# sourceMappingURL=babylon.meshBuilder.js.map
  65373. var BABYLON;
  65374. (function (BABYLON) {
  65375. /**
  65376. * Draco compression (https://google.github.io/draco/)
  65377. *
  65378. * This class wraps the Draco module.
  65379. *
  65380. * **Encoder**
  65381. *
  65382. * The encoder is not currently implemented.
  65383. *
  65384. * **Decoder**
  65385. *
  65386. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  65387. *
  65388. * To update the configuration, use the following code:
  65389. * ```javascript
  65390. * BABYLON.DracoCompression.Configuration = {
  65391. * decoder: {
  65392. * wasmUrl: "<url to the WebAssembly library>",
  65393. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  65394. * fallbackUrl: "<url to the fallback JavaScript library>",
  65395. * }
  65396. * };
  65397. * ```
  65398. *
  65399. * 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.
  65400. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  65401. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  65402. *
  65403. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  65404. * ```javascript
  65405. * var dracoCompression = new BABYLON.DracoCompression();
  65406. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  65407. * [BABYLON.VertexBuffer.PositionKind]: 0
  65408. * });
  65409. * ```
  65410. *
  65411. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  65412. */
  65413. var DracoCompression = /** @class */ (function () {
  65414. /**
  65415. * Constructor
  65416. */
  65417. function DracoCompression() {
  65418. }
  65419. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  65420. /**
  65421. * Returns true if the decoder is available.
  65422. */
  65423. get: function () {
  65424. if (typeof DracoDecoderModule !== "undefined") {
  65425. return true;
  65426. }
  65427. var decoder = DracoCompression.Configuration.decoder;
  65428. if (decoder) {
  65429. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65430. return true;
  65431. }
  65432. if (decoder.fallbackUrl) {
  65433. return true;
  65434. }
  65435. }
  65436. return false;
  65437. },
  65438. enumerable: true,
  65439. configurable: true
  65440. });
  65441. /**
  65442. * Stop all async operations and release resources.
  65443. */
  65444. DracoCompression.prototype.dispose = function () {
  65445. };
  65446. /**
  65447. * Decode Draco compressed mesh data to vertex data.
  65448. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65449. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65450. * @returns A promise that resolves with the decoded vertex data
  65451. */
  65452. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65453. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65454. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65455. var module = wrappedModule.module;
  65456. var vertexData = new BABYLON.VertexData();
  65457. var buffer = new module.DecoderBuffer();
  65458. buffer.Init(dataView, dataView.byteLength);
  65459. var decoder = new module.Decoder();
  65460. var geometry;
  65461. var status;
  65462. try {
  65463. var type = decoder.GetEncodedGeometryType(buffer);
  65464. switch (type) {
  65465. case module.TRIANGULAR_MESH:
  65466. geometry = new module.Mesh();
  65467. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65468. break;
  65469. case module.POINT_CLOUD:
  65470. geometry = new module.PointCloud();
  65471. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65472. break;
  65473. default:
  65474. throw new Error("Invalid geometry type " + type);
  65475. }
  65476. if (!status.ok() || !geometry.ptr) {
  65477. throw new Error(status.error_msg());
  65478. }
  65479. var numPoints = geometry.num_points();
  65480. if (type === module.TRIANGULAR_MESH) {
  65481. var numFaces = geometry.num_faces();
  65482. var faceIndices = new module.DracoInt32Array();
  65483. try {
  65484. var indices = new Uint32Array(numFaces * 3);
  65485. for (var i = 0; i < numFaces; i++) {
  65486. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65487. var offset = i * 3;
  65488. indices[offset + 0] = faceIndices.GetValue(0);
  65489. indices[offset + 1] = faceIndices.GetValue(1);
  65490. indices[offset + 2] = faceIndices.GetValue(2);
  65491. }
  65492. vertexData.indices = indices;
  65493. }
  65494. finally {
  65495. module.destroy(faceIndices);
  65496. }
  65497. }
  65498. for (var kind in attributes) {
  65499. var uniqueId = attributes[kind];
  65500. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65501. var dracoData = new module.DracoFloat32Array();
  65502. try {
  65503. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65504. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65505. for (var i = 0; i < babylonData.length; i++) {
  65506. babylonData[i] = dracoData.GetValue(i);
  65507. }
  65508. vertexData.set(babylonData, kind);
  65509. }
  65510. finally {
  65511. module.destroy(dracoData);
  65512. }
  65513. }
  65514. }
  65515. finally {
  65516. if (geometry) {
  65517. module.destroy(geometry);
  65518. }
  65519. module.destroy(decoder);
  65520. module.destroy(buffer);
  65521. }
  65522. return vertexData;
  65523. });
  65524. };
  65525. DracoCompression._GetDecoderModule = function () {
  65526. if (!DracoCompression._DecoderModulePromise) {
  65527. var promise = null;
  65528. var config_1 = {};
  65529. if (typeof DracoDecoderModule !== "undefined") {
  65530. promise = Promise.resolve();
  65531. }
  65532. else {
  65533. var decoder = DracoCompression.Configuration.decoder;
  65534. if (decoder) {
  65535. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65536. promise = Promise.all([
  65537. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65538. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65539. config_1.wasmBinary = data;
  65540. })
  65541. ]);
  65542. }
  65543. else if (decoder.fallbackUrl) {
  65544. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65545. }
  65546. }
  65547. }
  65548. if (!promise) {
  65549. throw new Error("Draco decoder module is not available");
  65550. }
  65551. DracoCompression._DecoderModulePromise = promise.then(function () {
  65552. return new Promise(function (resolve) {
  65553. config_1.onModuleLoaded = function (decoderModule) {
  65554. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65555. resolve({ module: decoderModule });
  65556. };
  65557. DracoDecoderModule(config_1);
  65558. });
  65559. });
  65560. }
  65561. return DracoCompression._DecoderModulePromise;
  65562. };
  65563. DracoCompression._LoadScriptAsync = function (url) {
  65564. return new Promise(function (resolve, reject) {
  65565. BABYLON.Tools.LoadScript(url, function () {
  65566. resolve();
  65567. }, function (message) {
  65568. reject(new Error(message));
  65569. });
  65570. });
  65571. };
  65572. DracoCompression._LoadFileAsync = function (url) {
  65573. return new Promise(function (resolve, reject) {
  65574. BABYLON.Tools.LoadFile(url, function (data) {
  65575. resolve(data);
  65576. }, undefined, undefined, true, function (request, exception) {
  65577. reject(exception);
  65578. });
  65579. });
  65580. };
  65581. /**
  65582. * The configuration. Defaults to the following urls:
  65583. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65584. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65585. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65586. */
  65587. DracoCompression.Configuration = {
  65588. decoder: {
  65589. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65590. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65591. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65592. }
  65593. };
  65594. return DracoCompression;
  65595. }());
  65596. BABYLON.DracoCompression = DracoCompression;
  65597. })(BABYLON || (BABYLON = {}));
  65598. //# sourceMappingURL=babylon.dracoCompression.js.map
  65599. var BABYLON;
  65600. (function (BABYLON) {
  65601. var AudioEngine = /** @class */ (function () {
  65602. function AudioEngine() {
  65603. this._audioContext = null;
  65604. this._audioContextInitialized = false;
  65605. this.canUseWebAudio = false;
  65606. this.WarnedWebAudioUnsupported = false;
  65607. this.unlocked = false;
  65608. this.isMP3supported = false;
  65609. this.isOGGsupported = false;
  65610. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65611. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65612. this.canUseWebAudio = true;
  65613. }
  65614. var audioElem = document.createElement('audio');
  65615. try {
  65616. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65617. this.isMP3supported = true;
  65618. }
  65619. }
  65620. catch (e) {
  65621. // protect error during capability check.
  65622. }
  65623. try {
  65624. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65625. this.isOGGsupported = true;
  65626. }
  65627. }
  65628. catch (e) {
  65629. // protect error during capability check.
  65630. }
  65631. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65632. this._unlockiOSaudio();
  65633. }
  65634. else {
  65635. this.unlocked = true;
  65636. }
  65637. }
  65638. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65639. get: function () {
  65640. if (!this._audioContextInitialized) {
  65641. this._initializeAudioContext();
  65642. }
  65643. return this._audioContext;
  65644. },
  65645. enumerable: true,
  65646. configurable: true
  65647. });
  65648. AudioEngine.prototype._unlockiOSaudio = function () {
  65649. var _this = this;
  65650. var unlockaudio = function () {
  65651. if (!_this.audioContext) {
  65652. return;
  65653. }
  65654. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65655. var source = _this.audioContext.createBufferSource();
  65656. source.buffer = buffer;
  65657. source.connect(_this.audioContext.destination);
  65658. source.start(0);
  65659. setTimeout(function () {
  65660. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65661. _this.unlocked = true;
  65662. window.removeEventListener('touchend', unlockaudio, false);
  65663. if (_this.onAudioUnlocked) {
  65664. _this.onAudioUnlocked();
  65665. }
  65666. }
  65667. }, 0);
  65668. };
  65669. window.addEventListener('touchend', unlockaudio, false);
  65670. };
  65671. AudioEngine.prototype._initializeAudioContext = function () {
  65672. try {
  65673. if (this.canUseWebAudio) {
  65674. this._audioContext = new AudioContext();
  65675. // create a global volume gain node
  65676. this.masterGain = this._audioContext.createGain();
  65677. this.masterGain.gain.value = 1;
  65678. this.masterGain.connect(this._audioContext.destination);
  65679. this._audioContextInitialized = true;
  65680. }
  65681. }
  65682. catch (e) {
  65683. this.canUseWebAudio = false;
  65684. BABYLON.Tools.Error("Web Audio: " + e.message);
  65685. }
  65686. };
  65687. AudioEngine.prototype.dispose = function () {
  65688. if (this.canUseWebAudio && this._audioContextInitialized) {
  65689. if (this._connectedAnalyser && this._audioContext) {
  65690. this._connectedAnalyser.stopDebugCanvas();
  65691. this._connectedAnalyser.dispose();
  65692. this.masterGain.disconnect();
  65693. this.masterGain.connect(this._audioContext.destination);
  65694. this._connectedAnalyser = null;
  65695. }
  65696. this.masterGain.gain.value = 1;
  65697. }
  65698. this.WarnedWebAudioUnsupported = false;
  65699. };
  65700. AudioEngine.prototype.getGlobalVolume = function () {
  65701. if (this.canUseWebAudio && this._audioContextInitialized) {
  65702. return this.masterGain.gain.value;
  65703. }
  65704. else {
  65705. return -1;
  65706. }
  65707. };
  65708. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65709. if (this.canUseWebAudio && this._audioContextInitialized) {
  65710. this.masterGain.gain.value = newVolume;
  65711. }
  65712. };
  65713. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65714. if (this._connectedAnalyser) {
  65715. this._connectedAnalyser.stopDebugCanvas();
  65716. }
  65717. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65718. this._connectedAnalyser = analyser;
  65719. this.masterGain.disconnect();
  65720. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65721. }
  65722. };
  65723. return AudioEngine;
  65724. }());
  65725. BABYLON.AudioEngine = AudioEngine;
  65726. })(BABYLON || (BABYLON = {}));
  65727. //# sourceMappingURL=babylon.audioEngine.js.map
  65728. var BABYLON;
  65729. (function (BABYLON) {
  65730. var Sound = /** @class */ (function () {
  65731. /**
  65732. * Create a sound and attach it to a scene
  65733. * @param name Name of your sound
  65734. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65735. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65736. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65737. */
  65738. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65739. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65740. var _this = this;
  65741. this.autoplay = false;
  65742. this.loop = false;
  65743. this.useCustomAttenuation = false;
  65744. this.spatialSound = false;
  65745. this.refDistance = 1;
  65746. this.rolloffFactor = 1;
  65747. this.maxDistance = 100;
  65748. this.distanceModel = "linear";
  65749. this._panningModel = "equalpower";
  65750. /**
  65751. * Observable event when the current playing sound finishes.
  65752. */
  65753. this.onEndedObservable = new BABYLON.Observable();
  65754. this._playbackRate = 1;
  65755. this._streaming = false;
  65756. this._startTime = 0;
  65757. this._startOffset = 0;
  65758. this._position = BABYLON.Vector3.Zero();
  65759. /** @hidden */
  65760. this._positionInEmitterSpace = false;
  65761. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65762. this._volume = 1;
  65763. this._isReadyToPlay = false;
  65764. this.isPlaying = false;
  65765. this.isPaused = false;
  65766. this._isDirectional = false;
  65767. // Used if you'd like to create a directional sound.
  65768. // If not set, the sound will be omnidirectional
  65769. this._coneInnerAngle = 360;
  65770. this._coneOuterAngle = 360;
  65771. this._coneOuterGain = 0;
  65772. this._isOutputConnected = false;
  65773. this._urlType = "Unknown";
  65774. this.name = name;
  65775. this._scene = scene;
  65776. this._readyToPlayCallback = readyToPlayCallback;
  65777. // Default custom attenuation function is a linear attenuation
  65778. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65779. if (currentDistance < maxDistance) {
  65780. return currentVolume * (1 - currentDistance / maxDistance);
  65781. }
  65782. else {
  65783. return 0;
  65784. }
  65785. };
  65786. if (options) {
  65787. this.autoplay = options.autoplay || false;
  65788. this.loop = options.loop || false;
  65789. // if volume === 0, we need another way to check this option
  65790. if (options.volume !== undefined) {
  65791. this._volume = options.volume;
  65792. }
  65793. this.spatialSound = options.spatialSound || false;
  65794. this.maxDistance = options.maxDistance || 100;
  65795. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65796. this.rolloffFactor = options.rolloffFactor || 1;
  65797. this.refDistance = options.refDistance || 1;
  65798. this.distanceModel = options.distanceModel || "linear";
  65799. this._playbackRate = options.playbackRate || 1;
  65800. this._streaming = options.streaming || false;
  65801. }
  65802. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65803. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65804. this._soundGain.gain.value = this._volume;
  65805. this._inputAudioNode = this._soundGain;
  65806. this._outputAudioNode = this._soundGain;
  65807. if (this.spatialSound) {
  65808. this._createSpatialParameters();
  65809. }
  65810. this._scene.mainSoundTrack.AddSound(this);
  65811. var validParameter = true;
  65812. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65813. if (urlOrArrayBuffer) {
  65814. try {
  65815. if (typeof (urlOrArrayBuffer) === "string") {
  65816. this._urlType = "String";
  65817. }
  65818. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65819. this._urlType = "ArrayBuffer";
  65820. }
  65821. else if (urlOrArrayBuffer instanceof MediaStream) {
  65822. this._urlType = "MediaStream";
  65823. }
  65824. else if (Array.isArray(urlOrArrayBuffer)) {
  65825. this._urlType = "Array";
  65826. }
  65827. var urls = [];
  65828. var codecSupportedFound = false;
  65829. switch (this._urlType) {
  65830. case "MediaStream":
  65831. this._streaming = true;
  65832. this._isReadyToPlay = true;
  65833. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65834. if (this.autoplay) {
  65835. this.play();
  65836. }
  65837. if (this._readyToPlayCallback) {
  65838. this._readyToPlayCallback();
  65839. }
  65840. break;
  65841. case "ArrayBuffer":
  65842. if (urlOrArrayBuffer.byteLength > 0) {
  65843. codecSupportedFound = true;
  65844. this._soundLoaded(urlOrArrayBuffer);
  65845. }
  65846. break;
  65847. case "String":
  65848. urls.push(urlOrArrayBuffer);
  65849. case "Array":
  65850. if (urls.length === 0)
  65851. urls = urlOrArrayBuffer;
  65852. // If we found a supported format, we load it immediately and stop the loop
  65853. for (var i = 0; i < urls.length; i++) {
  65854. var url = urls[i];
  65855. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65856. codecSupportedFound = true;
  65857. }
  65858. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65859. codecSupportedFound = true;
  65860. }
  65861. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65862. codecSupportedFound = true;
  65863. }
  65864. if (url.indexOf("blob:") !== -1) {
  65865. codecSupportedFound = true;
  65866. }
  65867. if (codecSupportedFound) {
  65868. // Loading sound using XHR2
  65869. if (!this._streaming) {
  65870. this._scene._loadFile(url, function (data) {
  65871. _this._soundLoaded(data);
  65872. }, undefined, true, true, function (exception) {
  65873. if (exception) {
  65874. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65875. }
  65876. BABYLON.Tools.Error("Sound creation aborted.");
  65877. _this._scene.mainSoundTrack.RemoveSound(_this);
  65878. });
  65879. }
  65880. // Streaming sound using HTML5 Audio tag
  65881. else {
  65882. this._htmlAudioElement = new Audio(url);
  65883. this._htmlAudioElement.controls = false;
  65884. this._htmlAudioElement.loop = this.loop;
  65885. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65886. this._htmlAudioElement.preload = "auto";
  65887. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65888. _this._isReadyToPlay = true;
  65889. if (_this.autoplay) {
  65890. _this.play();
  65891. }
  65892. if (_this._readyToPlayCallback) {
  65893. _this._readyToPlayCallback();
  65894. }
  65895. });
  65896. document.body.appendChild(this._htmlAudioElement);
  65897. }
  65898. break;
  65899. }
  65900. }
  65901. break;
  65902. default:
  65903. validParameter = false;
  65904. break;
  65905. }
  65906. if (!validParameter) {
  65907. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65908. }
  65909. else {
  65910. if (!codecSupportedFound) {
  65911. this._isReadyToPlay = true;
  65912. // Simulating a ready to play event to avoid breaking code path
  65913. if (this._readyToPlayCallback) {
  65914. window.setTimeout(function () {
  65915. if (_this._readyToPlayCallback) {
  65916. _this._readyToPlayCallback();
  65917. }
  65918. }, 1000);
  65919. }
  65920. }
  65921. }
  65922. }
  65923. catch (ex) {
  65924. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65925. this._scene.mainSoundTrack.RemoveSound(this);
  65926. }
  65927. }
  65928. }
  65929. else {
  65930. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65931. this._scene.mainSoundTrack.AddSound(this);
  65932. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65933. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65934. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65935. }
  65936. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65937. if (this._readyToPlayCallback) {
  65938. window.setTimeout(function () {
  65939. if (_this._readyToPlayCallback) {
  65940. _this._readyToPlayCallback();
  65941. }
  65942. }, 1000);
  65943. }
  65944. }
  65945. }
  65946. Sound.prototype.dispose = function () {
  65947. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65948. if (this.isPlaying) {
  65949. this.stop();
  65950. }
  65951. this._isReadyToPlay = false;
  65952. if (this.soundTrackId === -1) {
  65953. this._scene.mainSoundTrack.RemoveSound(this);
  65954. }
  65955. else {
  65956. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65957. }
  65958. if (this._soundGain) {
  65959. this._soundGain.disconnect();
  65960. this._soundGain = null;
  65961. }
  65962. if (this._soundPanner) {
  65963. this._soundPanner.disconnect();
  65964. this._soundPanner = null;
  65965. }
  65966. if (this._soundSource) {
  65967. this._soundSource.disconnect();
  65968. this._soundSource = null;
  65969. }
  65970. this._audioBuffer = null;
  65971. if (this._htmlAudioElement) {
  65972. this._htmlAudioElement.pause();
  65973. this._htmlAudioElement.src = "";
  65974. document.body.removeChild(this._htmlAudioElement);
  65975. }
  65976. if (this._streamingSource) {
  65977. this._streamingSource.disconnect();
  65978. }
  65979. if (this._connectedMesh && this._registerFunc) {
  65980. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65981. this._connectedMesh = null;
  65982. }
  65983. }
  65984. };
  65985. Sound.prototype.isReady = function () {
  65986. return this._isReadyToPlay;
  65987. };
  65988. Sound.prototype._soundLoaded = function (audioData) {
  65989. var _this = this;
  65990. if (!BABYLON.Engine.audioEngine.audioContext) {
  65991. return;
  65992. }
  65993. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65994. _this._audioBuffer = buffer;
  65995. _this._isReadyToPlay = true;
  65996. if (_this.autoplay) {
  65997. _this.play();
  65998. }
  65999. if (_this._readyToPlayCallback) {
  66000. _this._readyToPlayCallback();
  66001. }
  66002. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  66003. };
  66004. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  66005. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66006. this._audioBuffer = audioBuffer;
  66007. this._isReadyToPlay = true;
  66008. }
  66009. };
  66010. Sound.prototype.updateOptions = function (options) {
  66011. if (options) {
  66012. this.loop = options.loop || this.loop;
  66013. this.maxDistance = options.maxDistance || this.maxDistance;
  66014. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  66015. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  66016. this.refDistance = options.refDistance || this.refDistance;
  66017. this.distanceModel = options.distanceModel || this.distanceModel;
  66018. this._playbackRate = options.playbackRate || this._playbackRate;
  66019. this._updateSpatialParameters();
  66020. if (this.isPlaying) {
  66021. if (this._streaming && this._htmlAudioElement) {
  66022. this._htmlAudioElement.playbackRate = this._playbackRate;
  66023. }
  66024. else {
  66025. if (this._soundSource) {
  66026. this._soundSource.playbackRate.value = this._playbackRate;
  66027. }
  66028. }
  66029. }
  66030. }
  66031. };
  66032. Sound.prototype._createSpatialParameters = function () {
  66033. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66034. if (this._scene.headphone) {
  66035. this._panningModel = "HRTF";
  66036. }
  66037. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  66038. this._updateSpatialParameters();
  66039. this._soundPanner.connect(this._outputAudioNode);
  66040. this._inputAudioNode = this._soundPanner;
  66041. }
  66042. };
  66043. Sound.prototype._updateSpatialParameters = function () {
  66044. if (this.spatialSound && this._soundPanner) {
  66045. if (this.useCustomAttenuation) {
  66046. // Tricks to disable in a way embedded Web Audio attenuation
  66047. this._soundPanner.distanceModel = "linear";
  66048. this._soundPanner.maxDistance = Number.MAX_VALUE;
  66049. this._soundPanner.refDistance = 1;
  66050. this._soundPanner.rolloffFactor = 1;
  66051. this._soundPanner.panningModel = this._panningModel;
  66052. }
  66053. else {
  66054. this._soundPanner.distanceModel = this.distanceModel;
  66055. this._soundPanner.maxDistance = this.maxDistance;
  66056. this._soundPanner.refDistance = this.refDistance;
  66057. this._soundPanner.rolloffFactor = this.rolloffFactor;
  66058. this._soundPanner.panningModel = this._panningModel;
  66059. }
  66060. }
  66061. };
  66062. Sound.prototype.switchPanningModelToHRTF = function () {
  66063. this._panningModel = "HRTF";
  66064. this._switchPanningModel();
  66065. };
  66066. Sound.prototype.switchPanningModelToEqualPower = function () {
  66067. this._panningModel = "equalpower";
  66068. this._switchPanningModel();
  66069. };
  66070. Sound.prototype._switchPanningModel = function () {
  66071. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66072. this._soundPanner.panningModel = this._panningModel;
  66073. }
  66074. };
  66075. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  66076. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66077. if (this._isOutputConnected) {
  66078. this._outputAudioNode.disconnect();
  66079. }
  66080. this._outputAudioNode.connect(soundTrackAudioNode);
  66081. this._isOutputConnected = true;
  66082. }
  66083. };
  66084. /**
  66085. * Transform this sound into a directional source
  66086. * @param coneInnerAngle Size of the inner cone in degree
  66087. * @param coneOuterAngle Size of the outer cone in degree
  66088. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  66089. */
  66090. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  66091. if (coneOuterAngle < coneInnerAngle) {
  66092. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  66093. return;
  66094. }
  66095. this._coneInnerAngle = coneInnerAngle;
  66096. this._coneOuterAngle = coneOuterAngle;
  66097. this._coneOuterGain = coneOuterGain;
  66098. this._isDirectional = true;
  66099. if (this.isPlaying && this.loop) {
  66100. this.stop();
  66101. this.play();
  66102. }
  66103. };
  66104. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  66105. /**
  66106. * Gets or sets the inner angle for the directional cone.
  66107. */
  66108. get: function () {
  66109. return this._coneInnerAngle;
  66110. },
  66111. /**
  66112. * Gets or sets the inner angle for the directional cone.
  66113. */
  66114. set: function (value) {
  66115. if (value != this._coneInnerAngle) {
  66116. if (this._coneOuterAngle < value) {
  66117. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66118. return;
  66119. }
  66120. this._coneInnerAngle = value;
  66121. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66122. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66123. }
  66124. }
  66125. },
  66126. enumerable: true,
  66127. configurable: true
  66128. });
  66129. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  66130. /**
  66131. * Gets or sets the outer angle for the directional cone.
  66132. */
  66133. get: function () {
  66134. return this._coneOuterAngle;
  66135. },
  66136. /**
  66137. * Gets or sets the outer angle for the directional cone.
  66138. */
  66139. set: function (value) {
  66140. if (value != this._coneOuterAngle) {
  66141. if (value < this._coneInnerAngle) {
  66142. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66143. return;
  66144. }
  66145. this._coneOuterAngle = value;
  66146. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66147. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66148. }
  66149. }
  66150. },
  66151. enumerable: true,
  66152. configurable: true
  66153. });
  66154. Sound.prototype.setPosition = function (newPosition) {
  66155. this._position = newPosition;
  66156. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66157. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66158. }
  66159. };
  66160. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  66161. this._localDirection = newLocalDirection;
  66162. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  66163. this._updateDirection();
  66164. }
  66165. };
  66166. Sound.prototype._updateDirection = function () {
  66167. if (!this._connectedMesh || !this._soundPanner) {
  66168. return;
  66169. }
  66170. var mat = this._connectedMesh.getWorldMatrix();
  66171. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  66172. direction.normalize();
  66173. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  66174. };
  66175. Sound.prototype.updateDistanceFromListener = function () {
  66176. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  66177. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  66178. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  66179. }
  66180. };
  66181. Sound.prototype.setAttenuationFunction = function (callback) {
  66182. this._customAttenuationFunction = callback;
  66183. };
  66184. /**
  66185. * Play the sound
  66186. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  66187. * @param offset (optional) Start the sound setting it at a specific time
  66188. */
  66189. Sound.prototype.play = function (time, offset) {
  66190. var _this = this;
  66191. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  66192. try {
  66193. if (this._startOffset < 0) {
  66194. time = -this._startOffset;
  66195. this._startOffset = 0;
  66196. }
  66197. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66198. if (!this._soundSource || !this._streamingSource) {
  66199. if (this.spatialSound && this._soundPanner) {
  66200. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66201. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66202. }
  66203. if (this._isDirectional) {
  66204. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66205. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66206. this._soundPanner.coneOuterGain = this._coneOuterGain;
  66207. if (this._connectedMesh) {
  66208. this._updateDirection();
  66209. }
  66210. else {
  66211. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  66212. }
  66213. }
  66214. }
  66215. }
  66216. if (this._streaming) {
  66217. if (!this._streamingSource) {
  66218. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  66219. this._htmlAudioElement.onended = function () { _this._onended(); };
  66220. this._htmlAudioElement.playbackRate = this._playbackRate;
  66221. }
  66222. this._streamingSource.disconnect();
  66223. this._streamingSource.connect(this._inputAudioNode);
  66224. if (this._htmlAudioElement) {
  66225. this._htmlAudioElement.play();
  66226. }
  66227. }
  66228. else {
  66229. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  66230. this._soundSource.buffer = this._audioBuffer;
  66231. this._soundSource.connect(this._inputAudioNode);
  66232. this._soundSource.loop = this.loop;
  66233. this._soundSource.playbackRate.value = this._playbackRate;
  66234. this._soundSource.onended = function () { _this._onended(); };
  66235. if (this._soundSource.buffer) {
  66236. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  66237. }
  66238. }
  66239. this._startTime = startTime;
  66240. this.isPlaying = true;
  66241. this.isPaused = false;
  66242. }
  66243. catch (ex) {
  66244. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  66245. }
  66246. }
  66247. };
  66248. Sound.prototype._onended = function () {
  66249. this.isPlaying = false;
  66250. if (this.onended) {
  66251. this.onended();
  66252. }
  66253. this.onEndedObservable.notifyObservers(this);
  66254. };
  66255. /**
  66256. * Stop the sound
  66257. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  66258. */
  66259. Sound.prototype.stop = function (time) {
  66260. if (this.isPlaying) {
  66261. if (this._streaming) {
  66262. if (this._htmlAudioElement) {
  66263. this._htmlAudioElement.pause();
  66264. // Test needed for Firefox or it will generate an Invalid State Error
  66265. if (this._htmlAudioElement.currentTime > 0) {
  66266. this._htmlAudioElement.currentTime = 0;
  66267. }
  66268. }
  66269. else {
  66270. this._streamingSource.disconnect();
  66271. }
  66272. }
  66273. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  66274. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66275. this._soundSource.stop(stopTime);
  66276. this._soundSource.onended = function () { };
  66277. if (!this.isPaused) {
  66278. this._startOffset = 0;
  66279. }
  66280. }
  66281. this.isPlaying = false;
  66282. }
  66283. };
  66284. Sound.prototype.pause = function () {
  66285. if (this.isPlaying) {
  66286. this.isPaused = true;
  66287. if (this._streaming) {
  66288. if (this._htmlAudioElement) {
  66289. this._htmlAudioElement.pause();
  66290. }
  66291. else {
  66292. this._streamingSource.disconnect();
  66293. }
  66294. }
  66295. else if (BABYLON.Engine.audioEngine.audioContext) {
  66296. this.stop(0);
  66297. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  66298. }
  66299. }
  66300. };
  66301. Sound.prototype.setVolume = function (newVolume, time) {
  66302. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  66303. if (time && BABYLON.Engine.audioEngine.audioContext) {
  66304. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  66305. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  66306. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  66307. }
  66308. else {
  66309. this._soundGain.gain.value = newVolume;
  66310. }
  66311. }
  66312. this._volume = newVolume;
  66313. };
  66314. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  66315. this._playbackRate = newPlaybackRate;
  66316. if (this.isPlaying) {
  66317. if (this._streaming && this._htmlAudioElement) {
  66318. this._htmlAudioElement.playbackRate = this._playbackRate;
  66319. }
  66320. else if (this._soundSource) {
  66321. this._soundSource.playbackRate.value = this._playbackRate;
  66322. }
  66323. }
  66324. };
  66325. Sound.prototype.getVolume = function () {
  66326. return this._volume;
  66327. };
  66328. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  66329. var _this = this;
  66330. if (this._connectedMesh && this._registerFunc) {
  66331. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66332. this._registerFunc = null;
  66333. }
  66334. this._connectedMesh = meshToConnectTo;
  66335. if (!this.spatialSound) {
  66336. this.spatialSound = true;
  66337. this._createSpatialParameters();
  66338. if (this.isPlaying && this.loop) {
  66339. this.stop();
  66340. this.play();
  66341. }
  66342. }
  66343. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  66344. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  66345. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  66346. };
  66347. Sound.prototype.detachFromMesh = function () {
  66348. if (this._connectedMesh && this._registerFunc) {
  66349. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66350. this._registerFunc = null;
  66351. this._connectedMesh = null;
  66352. }
  66353. };
  66354. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  66355. if (!node.getBoundingInfo) {
  66356. return;
  66357. }
  66358. var mesh = node;
  66359. if (this._positionInEmitterSpace) {
  66360. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  66361. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  66362. }
  66363. else {
  66364. var boundingInfo = mesh.getBoundingInfo();
  66365. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  66366. }
  66367. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  66368. this._updateDirection();
  66369. }
  66370. };
  66371. Sound.prototype.clone = function () {
  66372. var _this = this;
  66373. if (!this._streaming) {
  66374. var setBufferAndRun = function () {
  66375. if (_this._isReadyToPlay) {
  66376. clonedSound._audioBuffer = _this.getAudioBuffer();
  66377. clonedSound._isReadyToPlay = true;
  66378. if (clonedSound.autoplay) {
  66379. clonedSound.play();
  66380. }
  66381. }
  66382. else {
  66383. window.setTimeout(setBufferAndRun, 300);
  66384. }
  66385. };
  66386. var currentOptions = {
  66387. autoplay: this.autoplay, loop: this.loop,
  66388. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  66389. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  66390. refDistance: this.refDistance, distanceModel: this.distanceModel
  66391. };
  66392. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  66393. if (this.useCustomAttenuation) {
  66394. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  66395. }
  66396. clonedSound.setPosition(this._position);
  66397. clonedSound.setPlaybackRate(this._playbackRate);
  66398. setBufferAndRun();
  66399. return clonedSound;
  66400. }
  66401. // Can't clone a streaming sound
  66402. else {
  66403. return null;
  66404. }
  66405. };
  66406. Sound.prototype.getAudioBuffer = function () {
  66407. return this._audioBuffer;
  66408. };
  66409. Sound.prototype.serialize = function () {
  66410. var serializationObject = {
  66411. name: this.name,
  66412. url: this.name,
  66413. autoplay: this.autoplay,
  66414. loop: this.loop,
  66415. volume: this._volume,
  66416. spatialSound: this.spatialSound,
  66417. maxDistance: this.maxDistance,
  66418. rolloffFactor: this.rolloffFactor,
  66419. refDistance: this.refDistance,
  66420. distanceModel: this.distanceModel,
  66421. playbackRate: this._playbackRate,
  66422. panningModel: this._panningModel,
  66423. soundTrackId: this.soundTrackId
  66424. };
  66425. if (this.spatialSound) {
  66426. if (this._connectedMesh)
  66427. serializationObject.connectedMeshId = this._connectedMesh.id;
  66428. serializationObject.position = this._position.asArray();
  66429. serializationObject.refDistance = this.refDistance;
  66430. serializationObject.distanceModel = this.distanceModel;
  66431. serializationObject.isDirectional = this._isDirectional;
  66432. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  66433. serializationObject.coneInnerAngle = this._coneInnerAngle;
  66434. serializationObject.coneOuterAngle = this._coneOuterAngle;
  66435. serializationObject.coneOuterGain = this._coneOuterGain;
  66436. }
  66437. return serializationObject;
  66438. };
  66439. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  66440. var soundName = parsedSound.name;
  66441. var soundUrl;
  66442. if (parsedSound.url) {
  66443. soundUrl = rootUrl + parsedSound.url;
  66444. }
  66445. else {
  66446. soundUrl = rootUrl + soundName;
  66447. }
  66448. var options = {
  66449. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66450. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66451. rolloffFactor: parsedSound.rolloffFactor,
  66452. refDistance: parsedSound.refDistance,
  66453. distanceModel: parsedSound.distanceModel,
  66454. playbackRate: parsedSound.playbackRate
  66455. };
  66456. var newSound;
  66457. if (!sourceSound) {
  66458. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66459. scene._addPendingData(newSound);
  66460. }
  66461. else {
  66462. var setBufferAndRun = function () {
  66463. if (sourceSound._isReadyToPlay) {
  66464. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66465. newSound._isReadyToPlay = true;
  66466. if (newSound.autoplay) {
  66467. newSound.play();
  66468. }
  66469. }
  66470. else {
  66471. window.setTimeout(setBufferAndRun, 300);
  66472. }
  66473. };
  66474. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66475. setBufferAndRun();
  66476. }
  66477. if (parsedSound.position) {
  66478. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66479. newSound.setPosition(soundPosition);
  66480. }
  66481. if (parsedSound.isDirectional) {
  66482. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66483. if (parsedSound.localDirectionToMesh) {
  66484. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66485. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66486. }
  66487. }
  66488. if (parsedSound.connectedMeshId) {
  66489. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66490. if (connectedMesh) {
  66491. newSound.attachToMesh(connectedMesh);
  66492. }
  66493. }
  66494. return newSound;
  66495. };
  66496. return Sound;
  66497. }());
  66498. BABYLON.Sound = Sound;
  66499. })(BABYLON || (BABYLON = {}));
  66500. //# sourceMappingURL=babylon.sound.js.map
  66501. var BABYLON;
  66502. (function (BABYLON) {
  66503. var SoundTrack = /** @class */ (function () {
  66504. function SoundTrack(scene, options) {
  66505. this.id = -1;
  66506. this._isMainTrack = false;
  66507. this._isInitialized = false;
  66508. this._scene = scene;
  66509. this.soundCollection = new Array();
  66510. this._options = options;
  66511. if (!this._isMainTrack) {
  66512. this._scene.soundTracks.push(this);
  66513. this.id = this._scene.soundTracks.length - 1;
  66514. }
  66515. }
  66516. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66517. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66518. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66519. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66520. if (this._options) {
  66521. if (this._options.volume) {
  66522. this._outputAudioNode.gain.value = this._options.volume;
  66523. }
  66524. if (this._options.mainTrack) {
  66525. this._isMainTrack = this._options.mainTrack;
  66526. }
  66527. }
  66528. this._isInitialized = true;
  66529. }
  66530. };
  66531. SoundTrack.prototype.dispose = function () {
  66532. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66533. if (this._connectedAnalyser) {
  66534. this._connectedAnalyser.stopDebugCanvas();
  66535. }
  66536. while (this.soundCollection.length) {
  66537. this.soundCollection[0].dispose();
  66538. }
  66539. if (this._outputAudioNode) {
  66540. this._outputAudioNode.disconnect();
  66541. }
  66542. this._outputAudioNode = null;
  66543. }
  66544. };
  66545. SoundTrack.prototype.AddSound = function (sound) {
  66546. if (!this._isInitialized) {
  66547. this._initializeSoundTrackAudioGraph();
  66548. }
  66549. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66550. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66551. }
  66552. if (sound.soundTrackId) {
  66553. if (sound.soundTrackId === -1) {
  66554. this._scene.mainSoundTrack.RemoveSound(sound);
  66555. }
  66556. else {
  66557. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66558. }
  66559. }
  66560. this.soundCollection.push(sound);
  66561. sound.soundTrackId = this.id;
  66562. };
  66563. SoundTrack.prototype.RemoveSound = function (sound) {
  66564. var index = this.soundCollection.indexOf(sound);
  66565. if (index !== -1) {
  66566. this.soundCollection.splice(index, 1);
  66567. }
  66568. };
  66569. SoundTrack.prototype.setVolume = function (newVolume) {
  66570. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66571. this._outputAudioNode.gain.value = newVolume;
  66572. }
  66573. };
  66574. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66575. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66576. for (var i = 0; i < this.soundCollection.length; i++) {
  66577. this.soundCollection[i].switchPanningModelToHRTF();
  66578. }
  66579. }
  66580. };
  66581. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66582. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66583. for (var i = 0; i < this.soundCollection.length; i++) {
  66584. this.soundCollection[i].switchPanningModelToEqualPower();
  66585. }
  66586. }
  66587. };
  66588. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66589. if (this._connectedAnalyser) {
  66590. this._connectedAnalyser.stopDebugCanvas();
  66591. }
  66592. this._connectedAnalyser = analyser;
  66593. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66594. this._outputAudioNode.disconnect();
  66595. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66596. }
  66597. };
  66598. return SoundTrack;
  66599. }());
  66600. BABYLON.SoundTrack = SoundTrack;
  66601. })(BABYLON || (BABYLON = {}));
  66602. //# sourceMappingURL=babylon.soundtrack.js.map
  66603. var BABYLON;
  66604. (function (BABYLON) {
  66605. /**
  66606. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66607. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66608. */
  66609. var Analyser = /** @class */ (function () {
  66610. /**
  66611. * Creates a new analyser
  66612. * @param scene defines hosting scene
  66613. */
  66614. function Analyser(scene) {
  66615. /**
  66616. * Gets or sets the smoothing
  66617. * @ignorenaming
  66618. */
  66619. this.SMOOTHING = 0.75;
  66620. /**
  66621. * Gets or sets the FFT table size
  66622. * @ignorenaming
  66623. */
  66624. this.FFT_SIZE = 512;
  66625. /**
  66626. * Gets or sets the bar graph amplitude
  66627. * @ignorenaming
  66628. */
  66629. this.BARGRAPHAMPLITUDE = 256;
  66630. /**
  66631. * Gets or sets the position of the debug canvas
  66632. * @ignorenaming
  66633. */
  66634. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66635. /**
  66636. * Gets or sets the debug canvas size
  66637. * @ignorenaming
  66638. */
  66639. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66640. this._scene = scene;
  66641. this._audioEngine = BABYLON.Engine.audioEngine;
  66642. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66643. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66644. this._webAudioAnalyser.minDecibels = -140;
  66645. this._webAudioAnalyser.maxDecibels = 0;
  66646. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66647. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66648. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66649. }
  66650. }
  66651. /**
  66652. * Get the number of data values you will have to play with for the visualization
  66653. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66654. * @returns a number
  66655. */
  66656. Analyser.prototype.getFrequencyBinCount = function () {
  66657. if (this._audioEngine.canUseWebAudio) {
  66658. return this._webAudioAnalyser.frequencyBinCount;
  66659. }
  66660. else {
  66661. return 0;
  66662. }
  66663. };
  66664. /**
  66665. * Gets the current frequency data as a byte array
  66666. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66667. * @returns a Uint8Array
  66668. */
  66669. Analyser.prototype.getByteFrequencyData = function () {
  66670. if (this._audioEngine.canUseWebAudio) {
  66671. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66672. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66673. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66674. }
  66675. return this._byteFreqs;
  66676. };
  66677. /**
  66678. * Gets the current waveform as a byte array
  66679. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66680. * @returns a Uint8Array
  66681. */
  66682. Analyser.prototype.getByteTimeDomainData = function () {
  66683. if (this._audioEngine.canUseWebAudio) {
  66684. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66685. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66686. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66687. }
  66688. return this._byteTime;
  66689. };
  66690. /**
  66691. * Gets the current frequency data as a float array
  66692. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66693. * @returns a Float32Array
  66694. */
  66695. Analyser.prototype.getFloatFrequencyData = function () {
  66696. if (this._audioEngine.canUseWebAudio) {
  66697. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66698. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66699. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66700. }
  66701. return this._floatFreqs;
  66702. };
  66703. /**
  66704. * Renders the debug canvas
  66705. */
  66706. Analyser.prototype.drawDebugCanvas = function () {
  66707. var _this = this;
  66708. if (this._audioEngine.canUseWebAudio) {
  66709. if (!this._debugCanvas) {
  66710. this._debugCanvas = document.createElement("canvas");
  66711. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66712. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66713. this._debugCanvas.style.position = "absolute";
  66714. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66715. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66716. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66717. document.body.appendChild(this._debugCanvas);
  66718. this._registerFunc = function () {
  66719. _this.drawDebugCanvas();
  66720. };
  66721. this._scene.registerBeforeRender(this._registerFunc);
  66722. }
  66723. if (this._registerFunc && this._debugCanvasContext) {
  66724. var workingArray = this.getByteFrequencyData();
  66725. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66726. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66727. // Draw the frequency domain chart.
  66728. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66729. var value = workingArray[i];
  66730. var percent = value / this.BARGRAPHAMPLITUDE;
  66731. var height = this.DEBUGCANVASSIZE.height * percent;
  66732. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66733. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66734. var hue = i / this.getFrequencyBinCount() * 360;
  66735. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66736. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66737. }
  66738. }
  66739. }
  66740. };
  66741. /**
  66742. * Stops rendering the debug canvas and removes it
  66743. */
  66744. Analyser.prototype.stopDebugCanvas = function () {
  66745. if (this._debugCanvas) {
  66746. if (this._registerFunc) {
  66747. this._scene.unregisterBeforeRender(this._registerFunc);
  66748. this._registerFunc = null;
  66749. }
  66750. document.body.removeChild(this._debugCanvas);
  66751. this._debugCanvas = null;
  66752. this._debugCanvasContext = null;
  66753. }
  66754. };
  66755. /**
  66756. * Connects two audio nodes
  66757. * @param inputAudioNode defines first node to connect
  66758. * @param outputAudioNode defines second node to connect
  66759. */
  66760. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66761. if (this._audioEngine.canUseWebAudio) {
  66762. inputAudioNode.connect(this._webAudioAnalyser);
  66763. this._webAudioAnalyser.connect(outputAudioNode);
  66764. }
  66765. };
  66766. /**
  66767. * Releases all associated resources
  66768. */
  66769. Analyser.prototype.dispose = function () {
  66770. if (this._audioEngine.canUseWebAudio) {
  66771. this._webAudioAnalyser.disconnect();
  66772. }
  66773. };
  66774. return Analyser;
  66775. }());
  66776. BABYLON.Analyser = Analyser;
  66777. })(BABYLON || (BABYLON = {}));
  66778. //# sourceMappingURL=babylon.analyser.js.map
  66779. var BABYLON;
  66780. (function (BABYLON) {
  66781. /**
  66782. * Wraps one or more Sound objects and selects one with random weight for playback.
  66783. */
  66784. var WeightedSound = /** @class */ (function () {
  66785. /**
  66786. * Creates a new WeightedSound from the list of sounds given.
  66787. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66788. * @param sounds Array of Sounds that will be selected from.
  66789. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66790. */
  66791. function WeightedSound(loop, sounds, weights) {
  66792. var _this = this;
  66793. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66794. this.loop = false;
  66795. this._coneInnerAngle = 360;
  66796. this._coneOuterAngle = 360;
  66797. this._volume = 1;
  66798. /** A Sound is currently playing. */
  66799. this.isPlaying = false;
  66800. /** A Sound is currently paused. */
  66801. this.isPaused = false;
  66802. this._sounds = [];
  66803. this._weights = [];
  66804. if (sounds.length !== weights.length) {
  66805. throw new Error('Sounds length does not equal weights length');
  66806. }
  66807. this.loop = loop;
  66808. this._weights = weights;
  66809. // Normalize the weights
  66810. var weightSum = 0;
  66811. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66812. var weight = weights_1[_i];
  66813. weightSum += weight;
  66814. }
  66815. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66816. for (var i = 0; i < this._weights.length; i++) {
  66817. this._weights[i] *= invWeightSum;
  66818. }
  66819. this._sounds = sounds;
  66820. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66821. var sound = _b[_a];
  66822. sound.onEndedObservable.add(function () { _this._onended(); });
  66823. }
  66824. }
  66825. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66826. /**
  66827. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66828. */
  66829. get: function () {
  66830. return this._coneInnerAngle;
  66831. },
  66832. /**
  66833. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66834. */
  66835. set: function (value) {
  66836. if (value !== this._coneInnerAngle) {
  66837. if (this._coneOuterAngle < value) {
  66838. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66839. return;
  66840. }
  66841. this._coneInnerAngle = value;
  66842. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66843. var sound = _a[_i];
  66844. sound.directionalConeInnerAngle = value;
  66845. }
  66846. }
  66847. },
  66848. enumerable: true,
  66849. configurable: true
  66850. });
  66851. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66852. /**
  66853. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66854. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66855. */
  66856. get: function () {
  66857. return this._coneOuterAngle;
  66858. },
  66859. /**
  66860. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66861. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66862. */
  66863. set: function (value) {
  66864. if (value !== this._coneOuterAngle) {
  66865. if (value < this._coneInnerAngle) {
  66866. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66867. return;
  66868. }
  66869. this._coneOuterAngle = value;
  66870. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66871. var sound = _a[_i];
  66872. sound.directionalConeOuterAngle = value;
  66873. }
  66874. }
  66875. },
  66876. enumerable: true,
  66877. configurable: true
  66878. });
  66879. Object.defineProperty(WeightedSound.prototype, "volume", {
  66880. /**
  66881. * Playback volume.
  66882. */
  66883. get: function () {
  66884. return this._volume;
  66885. },
  66886. /**
  66887. * Playback volume.
  66888. */
  66889. set: function (value) {
  66890. if (value !== this._volume) {
  66891. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66892. var sound = _a[_i];
  66893. sound.setVolume(value);
  66894. }
  66895. }
  66896. },
  66897. enumerable: true,
  66898. configurable: true
  66899. });
  66900. WeightedSound.prototype._onended = function () {
  66901. if (this._currentIndex !== undefined) {
  66902. this._sounds[this._currentIndex].autoplay = false;
  66903. }
  66904. if (this.loop && this.isPlaying) {
  66905. this.play();
  66906. }
  66907. else {
  66908. this.isPlaying = false;
  66909. }
  66910. };
  66911. /**
  66912. * Suspend playback
  66913. */
  66914. WeightedSound.prototype.pause = function () {
  66915. this.isPaused = true;
  66916. if (this._currentIndex !== undefined) {
  66917. this._sounds[this._currentIndex].pause();
  66918. }
  66919. };
  66920. /**
  66921. * Stop playback
  66922. */
  66923. WeightedSound.prototype.stop = function () {
  66924. this.isPlaying = false;
  66925. if (this._currentIndex !== undefined) {
  66926. this._sounds[this._currentIndex].stop();
  66927. }
  66928. };
  66929. /**
  66930. * Start playback.
  66931. * @param startOffset Position the clip head at a specific time in seconds.
  66932. */
  66933. WeightedSound.prototype.play = function (startOffset) {
  66934. if (!this.isPaused) {
  66935. this.stop();
  66936. var randomValue = Math.random();
  66937. var total = 0;
  66938. for (var i = 0; i < this._weights.length; i++) {
  66939. total += this._weights[i];
  66940. if (randomValue <= total) {
  66941. this._currentIndex = i;
  66942. break;
  66943. }
  66944. }
  66945. }
  66946. var sound = this._sounds[this._currentIndex];
  66947. if (sound.isReady()) {
  66948. sound.play(0, this.isPaused ? undefined : startOffset);
  66949. }
  66950. else {
  66951. sound.autoplay = true;
  66952. }
  66953. this.isPlaying = true;
  66954. this.isPaused = false;
  66955. };
  66956. return WeightedSound;
  66957. }());
  66958. BABYLON.WeightedSound = WeightedSound;
  66959. })(BABYLON || (BABYLON = {}));
  66960. //# sourceMappingURL=babylon.weightedsound.js.map
  66961. var BABYLON;
  66962. (function (BABYLON) {
  66963. var CubeTexture = /** @class */ (function (_super) {
  66964. __extends(CubeTexture, _super);
  66965. /**
  66966. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  66967. * as prefiltered data.
  66968. * @param rootUrl defines the url of the texture or the root name of the six images
  66969. * @param scene defines the scene the texture is attached to
  66970. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  66971. * @param noMipmap defines if mipmaps should be created or not
  66972. * @param files defines the six files to load for the different faces
  66973. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  66974. * @param onError defines a callback triggered in case of error during load
  66975. * @param format defines the internal format to use for the texture once loaded
  66976. * @param prefiltered defines whether or not the texture is created from prefiltered data
  66977. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  66978. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66979. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66980. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66981. * @return the cube texture
  66982. */
  66983. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  66984. if (extensions === void 0) { extensions = null; }
  66985. if (noMipmap === void 0) { noMipmap = false; }
  66986. if (files === void 0) { files = null; }
  66987. if (onLoad === void 0) { onLoad = null; }
  66988. if (onError === void 0) { onError = null; }
  66989. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66990. if (prefiltered === void 0) { prefiltered = false; }
  66991. if (forcedExtension === void 0) { forcedExtension = null; }
  66992. if (createPolynomials === void 0) { createPolynomials = false; }
  66993. if (lodScale === void 0) { lodScale = 0.8; }
  66994. if (lodOffset === void 0) { lodOffset = 0; }
  66995. var _this = _super.call(this, scene) || this;
  66996. /**
  66997. * Gets or sets the center of the bounding box associated with the cube texture
  66998. * It must define where the camera used to render the texture was set
  66999. */
  67000. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67001. _this._rotationY = 0;
  67002. /** @hidden */
  67003. _this._prefiltered = false;
  67004. _this.name = rootUrl;
  67005. _this.url = rootUrl;
  67006. _this._noMipmap = noMipmap;
  67007. _this.hasAlpha = false;
  67008. _this._format = format;
  67009. _this.isCube = true;
  67010. _this._textureMatrix = BABYLON.Matrix.Identity();
  67011. _this._createPolynomials = createPolynomials;
  67012. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67013. if (!rootUrl && !files) {
  67014. return _this;
  67015. }
  67016. var lastDot = rootUrl.lastIndexOf(".");
  67017. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  67018. var isDDS = (extension === ".dds");
  67019. var isEnv = (extension === ".env");
  67020. if (isEnv) {
  67021. _this.gammaSpace = false;
  67022. _this._prefiltered = false;
  67023. }
  67024. else {
  67025. _this._prefiltered = prefiltered;
  67026. if (prefiltered) {
  67027. _this.gammaSpace = false;
  67028. }
  67029. }
  67030. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  67031. if (!files) {
  67032. if (!isEnv && !isDDS && !extensions) {
  67033. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  67034. }
  67035. files = [];
  67036. if (extensions) {
  67037. for (var index = 0; index < extensions.length; index++) {
  67038. files.push(rootUrl + extensions[index]);
  67039. }
  67040. }
  67041. }
  67042. _this._files = files;
  67043. if (!_this._texture) {
  67044. if (!scene.useDelayedTextureLoading) {
  67045. if (prefiltered) {
  67046. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  67047. }
  67048. else {
  67049. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  67050. }
  67051. }
  67052. else {
  67053. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67054. }
  67055. }
  67056. else if (onLoad) {
  67057. if (_this._texture.isReady) {
  67058. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  67059. }
  67060. else {
  67061. _this._texture.onLoadedObservable.add(onLoad);
  67062. }
  67063. }
  67064. return _this;
  67065. }
  67066. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  67067. get: function () {
  67068. return this._boundingBoxSize;
  67069. },
  67070. /**
  67071. * Gets or sets the size of the bounding box associated with the cube texture
  67072. * When defined, the cubemap will switch to local mode
  67073. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67074. * @example https://www.babylonjs-playground.com/#RNASML
  67075. */
  67076. set: function (value) {
  67077. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67078. return;
  67079. }
  67080. this._boundingBoxSize = value;
  67081. var scene = this.getScene();
  67082. if (scene) {
  67083. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67084. }
  67085. },
  67086. enumerable: true,
  67087. configurable: true
  67088. });
  67089. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  67090. /**
  67091. * Gets texture matrix rotation angle around Y axis radians.
  67092. */
  67093. get: function () {
  67094. return this._rotationY;
  67095. },
  67096. /**
  67097. * Sets texture matrix rotation angle around Y axis in radians.
  67098. */
  67099. set: function (value) {
  67100. this._rotationY = value;
  67101. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  67102. },
  67103. enumerable: true,
  67104. configurable: true
  67105. });
  67106. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  67107. var rootUrlKey = "";
  67108. files.forEach(function (url) { return rootUrlKey += url; });
  67109. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  67110. };
  67111. /**
  67112. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  67113. * @param url defines the url of the prefiltered texture
  67114. * @param scene defines the scene the texture is attached to
  67115. * @param forcedExtension defines the extension of the file if different from the url
  67116. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67117. * @return the prefiltered texture
  67118. */
  67119. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  67120. if (forcedExtension === void 0) { forcedExtension = null; }
  67121. if (createPolynomials === void 0) { createPolynomials = true; }
  67122. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  67123. };
  67124. // Methods
  67125. CubeTexture.prototype.delayLoad = function () {
  67126. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67127. return;
  67128. }
  67129. var scene = this.getScene();
  67130. if (!scene) {
  67131. return;
  67132. }
  67133. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67134. this._texture = this._getFromCache(this.url, this._noMipmap);
  67135. if (!this._texture) {
  67136. if (this._prefiltered) {
  67137. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  67138. }
  67139. else {
  67140. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  67141. }
  67142. }
  67143. };
  67144. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  67145. return this._textureMatrix;
  67146. };
  67147. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67148. this._textureMatrix = value;
  67149. };
  67150. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67151. var texture = BABYLON.SerializationHelper.Parse(function () {
  67152. var prefiltered = false;
  67153. if (parsedTexture.prefiltered) {
  67154. prefiltered = parsedTexture.prefiltered;
  67155. }
  67156. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  67157. }, parsedTexture, scene);
  67158. // Local Cubemaps
  67159. if (parsedTexture.boundingBoxPosition) {
  67160. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  67161. }
  67162. if (parsedTexture.boundingBoxSize) {
  67163. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  67164. }
  67165. // Animations
  67166. if (parsedTexture.animations) {
  67167. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  67168. var parsedAnimation = parsedTexture.animations[animationIndex];
  67169. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67170. }
  67171. }
  67172. return texture;
  67173. };
  67174. CubeTexture.prototype.clone = function () {
  67175. var _this = this;
  67176. return BABYLON.SerializationHelper.Clone(function () {
  67177. var scene = _this.getScene();
  67178. if (!scene) {
  67179. return _this;
  67180. }
  67181. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  67182. }, this);
  67183. };
  67184. __decorate([
  67185. BABYLON.serialize("rotationY")
  67186. ], CubeTexture.prototype, "rotationY", null);
  67187. return CubeTexture;
  67188. }(BABYLON.BaseTexture));
  67189. BABYLON.CubeTexture = CubeTexture;
  67190. })(BABYLON || (BABYLON = {}));
  67191. //# sourceMappingURL=babylon.cubeTexture.js.map
  67192. var BABYLON;
  67193. (function (BABYLON) {
  67194. /**
  67195. * Raw cube texture where the raw buffers are passed in
  67196. */
  67197. var RawCubeTexture = /** @class */ (function (_super) {
  67198. __extends(RawCubeTexture, _super);
  67199. /**
  67200. * Creates a cube texture where the raw buffers are passed in.
  67201. * @param scene defines the scene the texture is attached to
  67202. * @param data defines the array of data to use to create each face
  67203. * @param size defines the size of the textures
  67204. * @param format defines the format of the data
  67205. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  67206. * @param generateMipMaps defines if the engine should generate the mip levels
  67207. * @param invertY defines if data must be stored with Y axis inverted
  67208. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  67209. * @param compression defines the compression used (null by default)
  67210. */
  67211. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  67212. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67213. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67214. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67215. if (invertY === void 0) { invertY = false; }
  67216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67217. if (compression === void 0) { compression = null; }
  67218. var _this = _super.call(this, "", scene) || this;
  67219. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  67220. return _this;
  67221. }
  67222. /**
  67223. * Updates the raw cube texture.
  67224. * @param data defines the data to store
  67225. * @param format defines the data format
  67226. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  67227. * @param invertY defines if data must be stored with Y axis inverted
  67228. * @param compression defines the compression used (null by default)
  67229. * @param level defines which level of the texture to update
  67230. */
  67231. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  67232. if (compression === void 0) { compression = null; }
  67233. if (level === void 0) { level = 0; }
  67234. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  67235. };
  67236. /**
  67237. * Updates a raw cube texture with RGBD encoded data.
  67238. * @param data defines the array of data [mipmap][face] to use to create each face
  67239. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  67240. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67241. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67242. * @returns a promsie that resolves when the operation is complete
  67243. */
  67244. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  67245. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  67246. if (lodScale === void 0) { lodScale = 0.8; }
  67247. if (lodOffset === void 0) { lodOffset = 0; }
  67248. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  67249. };
  67250. /**
  67251. * Clones the raw cube texture.
  67252. * @return a new cube texture
  67253. */
  67254. RawCubeTexture.prototype.clone = function () {
  67255. var _this = this;
  67256. return BABYLON.SerializationHelper.Clone(function () {
  67257. var scene = _this.getScene();
  67258. var internalTexture = _this._texture;
  67259. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  67260. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  67261. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  67262. }
  67263. return texture;
  67264. }, this);
  67265. };
  67266. /** @hidden */
  67267. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  67268. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  67269. internalTexture._bufferViewArrayArray = data;
  67270. internalTexture._lodGenerationScale = lodScale;
  67271. internalTexture._lodGenerationOffset = lodOffset;
  67272. internalTexture._sphericalPolynomial = sphericalPolynomial;
  67273. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  67274. internalTexture.isReady = true;
  67275. });
  67276. };
  67277. return RawCubeTexture;
  67278. }(BABYLON.CubeTexture));
  67279. BABYLON.RawCubeTexture = RawCubeTexture;
  67280. })(BABYLON || (BABYLON = {}));
  67281. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  67282. var BABYLON;
  67283. (function (BABYLON) {
  67284. var RenderTargetTexture = /** @class */ (function (_super) {
  67285. __extends(RenderTargetTexture, _super);
  67286. /**
  67287. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  67288. * or used a shadow, depth texture...
  67289. * @param name The friendly name of the texture
  67290. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  67291. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  67292. * @param generateMipMaps True if mip maps need to be generated after render.
  67293. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  67294. * @param type The type of the buffer in the RTT (int, half float, float...)
  67295. * @param isCube True if a cube texture needs to be created
  67296. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  67297. * @param generateDepthBuffer True to generate a depth buffer
  67298. * @param generateStencilBuffer True to generate a stencil buffer
  67299. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  67300. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  67301. */
  67302. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  67303. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  67304. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67305. if (isCube === void 0) { isCube = false; }
  67306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67307. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67308. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  67309. if (isMulti === void 0) { isMulti = false; }
  67310. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67311. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67312. _this.isCube = isCube;
  67313. _this.renderParticles = true;
  67314. _this.renderSprites = false;
  67315. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  67316. _this.ignoreCameraViewport = false;
  67317. // Events
  67318. /**
  67319. * An event triggered when the texture is unbind.
  67320. */
  67321. _this.onBeforeBindObservable = new BABYLON.Observable();
  67322. /**
  67323. * An event triggered when the texture is unbind.
  67324. */
  67325. _this.onAfterUnbindObservable = new BABYLON.Observable();
  67326. /**
  67327. * An event triggered before rendering the texture
  67328. */
  67329. _this.onBeforeRenderObservable = new BABYLON.Observable();
  67330. /**
  67331. * An event triggered after rendering the texture
  67332. */
  67333. _this.onAfterRenderObservable = new BABYLON.Observable();
  67334. /**
  67335. * An event triggered after the texture clear
  67336. */
  67337. _this.onClearObservable = new BABYLON.Observable();
  67338. _this._currentRefreshId = -1;
  67339. _this._refreshRate = 1;
  67340. _this._samples = 1;
  67341. /**
  67342. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  67343. * It must define where the camera used to render the texture is set
  67344. */
  67345. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67346. scene = _this.getScene();
  67347. if (!scene) {
  67348. return _this;
  67349. }
  67350. _this.renderList = new Array();
  67351. _this._engine = scene.getEngine();
  67352. _this.name = name;
  67353. _this.isRenderTarget = true;
  67354. _this._initialSizeParameter = size;
  67355. _this._processSizeParameter(size);
  67356. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  67357. });
  67358. _this._generateMipMaps = generateMipMaps ? true : false;
  67359. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  67360. // Rendering groups
  67361. _this._renderingManager = new BABYLON.RenderingManager(scene);
  67362. _this._renderingManager._useSceneAutoClearSetup = true;
  67363. if (isMulti) {
  67364. return _this;
  67365. }
  67366. _this._renderTargetOptions = {
  67367. generateMipMaps: generateMipMaps,
  67368. type: type,
  67369. format: format,
  67370. samplingMode: samplingMode,
  67371. generateDepthBuffer: generateDepthBuffer,
  67372. generateStencilBuffer: generateStencilBuffer
  67373. };
  67374. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  67375. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67376. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67377. }
  67378. if (isCube) {
  67379. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  67380. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  67381. _this._textureMatrix = BABYLON.Matrix.Identity();
  67382. }
  67383. else {
  67384. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  67385. }
  67386. return _this;
  67387. }
  67388. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  67389. get: function () {
  67390. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  67391. },
  67392. enumerable: true,
  67393. configurable: true
  67394. });
  67395. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  67396. get: function () {
  67397. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  67398. },
  67399. enumerable: true,
  67400. configurable: true
  67401. });
  67402. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  67403. get: function () {
  67404. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  67405. },
  67406. enumerable: true,
  67407. configurable: true
  67408. });
  67409. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  67410. /**
  67411. * Use this list to define the list of mesh you want to render.
  67412. */
  67413. get: function () {
  67414. return this._renderList;
  67415. },
  67416. set: function (value) {
  67417. this._renderList = value;
  67418. if (this._renderList) {
  67419. this._hookArray(this._renderList);
  67420. }
  67421. },
  67422. enumerable: true,
  67423. configurable: true
  67424. });
  67425. RenderTargetTexture.prototype._hookArray = function (array) {
  67426. var _this = this;
  67427. var oldPush = array.push;
  67428. array.push = function () {
  67429. var items = [];
  67430. for (var _i = 0; _i < arguments.length; _i++) {
  67431. items[_i] = arguments[_i];
  67432. }
  67433. var result = oldPush.apply(array, items);
  67434. _this.getScene().meshes.forEach(function (mesh) {
  67435. mesh._markSubMeshesAsLightDirty();
  67436. });
  67437. return result;
  67438. };
  67439. var oldSplice = array.splice;
  67440. array.splice = function (index, deleteCount) {
  67441. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67442. _this.getScene().meshes.forEach(function (mesh) {
  67443. mesh._markSubMeshesAsLightDirty();
  67444. });
  67445. return deleted;
  67446. };
  67447. };
  67448. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  67449. set: function (callback) {
  67450. if (this._onAfterUnbindObserver) {
  67451. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  67452. }
  67453. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  67454. },
  67455. enumerable: true,
  67456. configurable: true
  67457. });
  67458. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  67459. set: function (callback) {
  67460. if (this._onBeforeRenderObserver) {
  67461. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67462. }
  67463. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67464. },
  67465. enumerable: true,
  67466. configurable: true
  67467. });
  67468. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  67469. set: function (callback) {
  67470. if (this._onAfterRenderObserver) {
  67471. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67472. }
  67473. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67474. },
  67475. enumerable: true,
  67476. configurable: true
  67477. });
  67478. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  67479. set: function (callback) {
  67480. if (this._onClearObserver) {
  67481. this.onClearObservable.remove(this._onClearObserver);
  67482. }
  67483. this._onClearObserver = this.onClearObservable.add(callback);
  67484. },
  67485. enumerable: true,
  67486. configurable: true
  67487. });
  67488. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  67489. get: function () {
  67490. return this._renderTargetOptions;
  67491. },
  67492. enumerable: true,
  67493. configurable: true
  67494. });
  67495. RenderTargetTexture.prototype._onRatioRescale = function () {
  67496. if (this._sizeRatio) {
  67497. this.resize(this._initialSizeParameter);
  67498. }
  67499. };
  67500. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  67501. get: function () {
  67502. return this._boundingBoxSize;
  67503. },
  67504. /**
  67505. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  67506. * When defined, the cubemap will switch to local mode
  67507. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67508. * @example https://www.babylonjs-playground.com/#RNASML
  67509. */
  67510. set: function (value) {
  67511. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67512. return;
  67513. }
  67514. this._boundingBoxSize = value;
  67515. var scene = this.getScene();
  67516. if (scene) {
  67517. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67518. }
  67519. },
  67520. enumerable: true,
  67521. configurable: true
  67522. });
  67523. /**
  67524. * Creates a depth stencil texture.
  67525. * This is only available in WebGL 2 or with the depth texture extension available.
  67526. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  67527. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  67528. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  67529. */
  67530. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  67531. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  67532. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  67533. if (generateStencil === void 0) { generateStencil = false; }
  67534. if (!this.getScene()) {
  67535. return;
  67536. }
  67537. var engine = this.getScene().getEngine();
  67538. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  67539. bilinearFiltering: bilinearFiltering,
  67540. comparisonFunction: comparisonFunction,
  67541. generateStencil: generateStencil,
  67542. isCube: this.isCube
  67543. });
  67544. engine.setFrameBufferDepthStencilTexture(this);
  67545. };
  67546. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  67547. if (size.ratio) {
  67548. this._sizeRatio = size.ratio;
  67549. this._size = {
  67550. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  67551. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  67552. };
  67553. }
  67554. else {
  67555. this._size = size;
  67556. }
  67557. };
  67558. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  67559. get: function () {
  67560. return this._samples;
  67561. },
  67562. set: function (value) {
  67563. if (this._samples === value) {
  67564. return;
  67565. }
  67566. var scene = this.getScene();
  67567. if (!scene) {
  67568. return;
  67569. }
  67570. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  67571. },
  67572. enumerable: true,
  67573. configurable: true
  67574. });
  67575. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  67576. this._currentRefreshId = -1;
  67577. };
  67578. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  67579. get: function () {
  67580. return this._refreshRate;
  67581. },
  67582. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67583. set: function (value) {
  67584. this._refreshRate = value;
  67585. this.resetRefreshCounter();
  67586. },
  67587. enumerable: true,
  67588. configurable: true
  67589. });
  67590. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  67591. if (!this._postProcessManager) {
  67592. var scene = this.getScene();
  67593. if (!scene) {
  67594. return;
  67595. }
  67596. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  67597. this._postProcesses = new Array();
  67598. }
  67599. this._postProcesses.push(postProcess);
  67600. this._postProcesses[0].autoClear = false;
  67601. };
  67602. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  67603. if (!this._postProcesses) {
  67604. return;
  67605. }
  67606. if (dispose) {
  67607. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  67608. var postProcess = _a[_i];
  67609. postProcess.dispose();
  67610. }
  67611. }
  67612. this._postProcesses = [];
  67613. };
  67614. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  67615. if (!this._postProcesses) {
  67616. return;
  67617. }
  67618. var index = this._postProcesses.indexOf(postProcess);
  67619. if (index === -1) {
  67620. return;
  67621. }
  67622. this._postProcesses.splice(index, 1);
  67623. if (this._postProcesses.length > 0) {
  67624. this._postProcesses[0].autoClear = false;
  67625. }
  67626. };
  67627. /** @hidden */
  67628. RenderTargetTexture.prototype._shouldRender = function () {
  67629. if (this._currentRefreshId === -1) { // At least render once
  67630. this._currentRefreshId = 1;
  67631. return true;
  67632. }
  67633. if (this.refreshRate === this._currentRefreshId) {
  67634. this._currentRefreshId = 1;
  67635. return true;
  67636. }
  67637. this._currentRefreshId++;
  67638. return false;
  67639. };
  67640. RenderTargetTexture.prototype.getRenderSize = function () {
  67641. if (this._size.width) {
  67642. return this._size.width;
  67643. }
  67644. return this._size;
  67645. };
  67646. RenderTargetTexture.prototype.getRenderWidth = function () {
  67647. if (this._size.width) {
  67648. return this._size.width;
  67649. }
  67650. return this._size;
  67651. };
  67652. RenderTargetTexture.prototype.getRenderHeight = function () {
  67653. if (this._size.width) {
  67654. return this._size.height;
  67655. }
  67656. return this._size;
  67657. };
  67658. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  67659. get: function () {
  67660. return true;
  67661. },
  67662. enumerable: true,
  67663. configurable: true
  67664. });
  67665. RenderTargetTexture.prototype.scale = function (ratio) {
  67666. var newSize = this.getRenderSize() * ratio;
  67667. this.resize(newSize);
  67668. };
  67669. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  67670. if (this.isCube) {
  67671. return this._textureMatrix;
  67672. }
  67673. return _super.prototype.getReflectionTextureMatrix.call(this);
  67674. };
  67675. RenderTargetTexture.prototype.resize = function (size) {
  67676. this.releaseInternalTexture();
  67677. var scene = this.getScene();
  67678. if (!scene) {
  67679. return;
  67680. }
  67681. this._processSizeParameter(size);
  67682. if (this.isCube) {
  67683. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  67684. }
  67685. else {
  67686. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  67687. }
  67688. };
  67689. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  67690. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  67691. if (dumpForDebug === void 0) { dumpForDebug = false; }
  67692. var scene = this.getScene();
  67693. if (!scene) {
  67694. return;
  67695. }
  67696. var engine = scene.getEngine();
  67697. if (this.useCameraPostProcesses !== undefined) {
  67698. useCameraPostProcess = this.useCameraPostProcesses;
  67699. }
  67700. if (this._waitingRenderList) {
  67701. this.renderList = [];
  67702. for (var index = 0; index < this._waitingRenderList.length; index++) {
  67703. var id = this._waitingRenderList[index];
  67704. var mesh_1 = scene.getMeshByID(id);
  67705. if (mesh_1) {
  67706. this.renderList.push(mesh_1);
  67707. }
  67708. }
  67709. delete this._waitingRenderList;
  67710. }
  67711. // Is predicate defined?
  67712. if (this.renderListPredicate) {
  67713. if (this.renderList) {
  67714. this.renderList.splice(0); // Clear previous renderList
  67715. }
  67716. else {
  67717. this.renderList = [];
  67718. }
  67719. var scene = this.getScene();
  67720. if (!scene) {
  67721. return;
  67722. }
  67723. var sceneMeshes = scene.meshes;
  67724. for (var index = 0; index < sceneMeshes.length; index++) {
  67725. var mesh = sceneMeshes[index];
  67726. if (this.renderListPredicate(mesh)) {
  67727. this.renderList.push(mesh);
  67728. }
  67729. }
  67730. }
  67731. this.onBeforeBindObservable.notifyObservers(this);
  67732. // Set custom projection.
  67733. // Needs to be before binding to prevent changing the aspect ratio.
  67734. var camera;
  67735. if (this.activeCamera) {
  67736. camera = this.activeCamera;
  67737. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67738. if (this.activeCamera !== scene.activeCamera) {
  67739. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  67740. }
  67741. }
  67742. else {
  67743. camera = scene.activeCamera;
  67744. if (camera) {
  67745. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67746. }
  67747. }
  67748. // Prepare renderingManager
  67749. this._renderingManager.reset();
  67750. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  67751. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  67752. var sceneRenderId = scene.getRenderId();
  67753. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  67754. var mesh = currentRenderList[meshIndex];
  67755. if (mesh) {
  67756. if (!mesh.isReady(this.refreshRate === 0)) {
  67757. this.resetRefreshCounter();
  67758. continue;
  67759. }
  67760. mesh._preActivateForIntermediateRendering(sceneRenderId);
  67761. var isMasked = void 0;
  67762. if (!this.renderList && camera) {
  67763. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  67764. }
  67765. else {
  67766. isMasked = false;
  67767. }
  67768. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  67769. mesh._activate(sceneRenderId);
  67770. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  67771. var subMesh = mesh.subMeshes[subIndex];
  67772. scene._activeIndices.addCount(subMesh.indexCount, false);
  67773. this._renderingManager.dispatch(subMesh, mesh);
  67774. }
  67775. }
  67776. }
  67777. }
  67778. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  67779. var particleSystem = scene.particleSystems[particleIndex];
  67780. var emitter = particleSystem.emitter;
  67781. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  67782. continue;
  67783. }
  67784. if (currentRenderList.indexOf(emitter) >= 0) {
  67785. this._renderingManager.dispatchParticles(particleSystem);
  67786. }
  67787. }
  67788. if (this.isCube) {
  67789. for (var face = 0; face < 6; face++) {
  67790. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67791. scene.incrementRenderId();
  67792. scene.resetCachedMaterial();
  67793. }
  67794. }
  67795. else {
  67796. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67797. }
  67798. this.onAfterUnbindObservable.notifyObservers(this);
  67799. if (scene.activeCamera) {
  67800. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  67801. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  67802. }
  67803. engine.setViewport(scene.activeCamera.viewport);
  67804. }
  67805. scene.resetCachedMaterial();
  67806. };
  67807. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  67808. var minimum = 128;
  67809. var x = renderDimension * scale;
  67810. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  67811. // Ensure we don't exceed the render dimension (while staying POT)
  67812. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  67813. };
  67814. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67815. var _this = this;
  67816. if (!this._texture) {
  67817. return;
  67818. }
  67819. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  67820. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67821. });
  67822. };
  67823. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  67824. var scene = this.getScene();
  67825. if (!scene) {
  67826. return;
  67827. }
  67828. var engine = scene.getEngine();
  67829. if (!this._texture) {
  67830. return;
  67831. }
  67832. // Bind
  67833. if (this._postProcessManager) {
  67834. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  67835. }
  67836. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  67837. if (this._texture) {
  67838. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  67839. }
  67840. }
  67841. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  67842. // Clear
  67843. if (this.onClearObservable.hasObservers()) {
  67844. this.onClearObservable.notifyObservers(engine);
  67845. }
  67846. else {
  67847. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  67848. }
  67849. if (!this._doNotChangeAspectRatio) {
  67850. scene.updateTransformMatrix(true);
  67851. }
  67852. // Render
  67853. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  67854. if (this._postProcessManager) {
  67855. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  67856. }
  67857. else if (useCameraPostProcess) {
  67858. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  67859. }
  67860. if (!this._doNotChangeAspectRatio) {
  67861. scene.updateTransformMatrix(true);
  67862. }
  67863. // Dump ?
  67864. if (dumpForDebug) {
  67865. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  67866. }
  67867. // Unbind
  67868. if (!this.isCube || faceIndex === 5) {
  67869. if (this.isCube) {
  67870. if (faceIndex === 5) {
  67871. engine.generateMipMapsForCubemap(this._texture);
  67872. }
  67873. }
  67874. this.unbindFrameBuffer(engine, faceIndex);
  67875. }
  67876. else {
  67877. this.onAfterRenderObservable.notifyObservers(faceIndex);
  67878. }
  67879. };
  67880. /**
  67881. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  67882. * This allowed control for front to back rendering or reversly depending of the special needs.
  67883. *
  67884. * @param renderingGroupId The rendering group id corresponding to its index
  67885. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  67886. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  67887. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  67888. */
  67889. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  67890. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  67891. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  67892. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  67893. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  67894. };
  67895. /**
  67896. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67897. *
  67898. * @param renderingGroupId The rendering group id corresponding to its index
  67899. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67900. */
  67901. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67902. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67903. this._renderingManager._useSceneAutoClearSetup = false;
  67904. };
  67905. RenderTargetTexture.prototype.clone = function () {
  67906. var textureSize = this.getSize();
  67907. 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);
  67908. // Base texture
  67909. newTexture.hasAlpha = this.hasAlpha;
  67910. newTexture.level = this.level;
  67911. // RenderTarget Texture
  67912. newTexture.coordinatesMode = this.coordinatesMode;
  67913. if (this.renderList) {
  67914. newTexture.renderList = this.renderList.slice(0);
  67915. }
  67916. return newTexture;
  67917. };
  67918. RenderTargetTexture.prototype.serialize = function () {
  67919. if (!this.name) {
  67920. return null;
  67921. }
  67922. var serializationObject = _super.prototype.serialize.call(this);
  67923. serializationObject.renderTargetSize = this.getRenderSize();
  67924. serializationObject.renderList = [];
  67925. if (this.renderList) {
  67926. for (var index = 0; index < this.renderList.length; index++) {
  67927. serializationObject.renderList.push(this.renderList[index].id);
  67928. }
  67929. }
  67930. return serializationObject;
  67931. };
  67932. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  67933. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  67934. var objBuffer = this.getInternalTexture();
  67935. var scene = this.getScene();
  67936. if (objBuffer && scene) {
  67937. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  67938. }
  67939. };
  67940. RenderTargetTexture.prototype.dispose = function () {
  67941. if (this._postProcessManager) {
  67942. this._postProcessManager.dispose();
  67943. this._postProcessManager = null;
  67944. }
  67945. this.clearPostProcesses(true);
  67946. if (this._resizeObserver) {
  67947. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  67948. this._resizeObserver = null;
  67949. }
  67950. this.renderList = null;
  67951. // Remove from custom render targets
  67952. var scene = this.getScene();
  67953. if (!scene) {
  67954. return;
  67955. }
  67956. var index = scene.customRenderTargets.indexOf(this);
  67957. if (index >= 0) {
  67958. scene.customRenderTargets.splice(index, 1);
  67959. }
  67960. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  67961. var camera = _a[_i];
  67962. index = camera.customRenderTargets.indexOf(this);
  67963. if (index >= 0) {
  67964. camera.customRenderTargets.splice(index, 1);
  67965. }
  67966. }
  67967. _super.prototype.dispose.call(this);
  67968. };
  67969. /** @hidden */
  67970. RenderTargetTexture.prototype._rebuild = function () {
  67971. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67972. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67973. }
  67974. if (this._postProcessManager) {
  67975. this._postProcessManager._rebuild();
  67976. }
  67977. };
  67978. /**
  67979. * Clear the info related to rendering groups preventing retention point in material dispose.
  67980. */
  67981. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  67982. if (this._renderingManager) {
  67983. this._renderingManager.freeRenderingGroups();
  67984. }
  67985. };
  67986. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  67987. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  67988. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  67989. return RenderTargetTexture;
  67990. }(BABYLON.Texture));
  67991. BABYLON.RenderTargetTexture = RenderTargetTexture;
  67992. })(BABYLON || (BABYLON = {}));
  67993. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  67994. var BABYLON;
  67995. (function (BABYLON) {
  67996. ;
  67997. var MultiRenderTarget = /** @class */ (function (_super) {
  67998. __extends(MultiRenderTarget, _super);
  67999. function MultiRenderTarget(name, size, count, scene, options) {
  68000. var _this = this;
  68001. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  68002. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  68003. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  68004. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  68005. _this._engine = scene.getEngine();
  68006. if (!_this.isSupported) {
  68007. _this.dispose();
  68008. return;
  68009. }
  68010. var types = [];
  68011. var samplingModes = [];
  68012. for (var i = 0; i < count; i++) {
  68013. if (options && options.types && options.types[i] !== undefined) {
  68014. types.push(options.types[i]);
  68015. }
  68016. else {
  68017. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68018. }
  68019. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  68020. samplingModes.push(options.samplingModes[i]);
  68021. }
  68022. else {
  68023. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68024. }
  68025. }
  68026. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  68027. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  68028. _this._size = size;
  68029. _this._multiRenderTargetOptions = {
  68030. samplingModes: samplingModes,
  68031. generateMipMaps: generateMipMaps,
  68032. generateDepthBuffer: generateDepthBuffer,
  68033. generateStencilBuffer: generateStencilBuffer,
  68034. generateDepthTexture: generateDepthTexture,
  68035. types: types,
  68036. textureCount: count
  68037. };
  68038. _this._createInternalTextures();
  68039. _this._createTextures();
  68040. return _this;
  68041. }
  68042. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  68043. get: function () {
  68044. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  68045. },
  68046. enumerable: true,
  68047. configurable: true
  68048. });
  68049. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  68050. get: function () {
  68051. return this._textures;
  68052. },
  68053. enumerable: true,
  68054. configurable: true
  68055. });
  68056. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  68057. get: function () {
  68058. return this._textures[this._textures.length - 1];
  68059. },
  68060. enumerable: true,
  68061. configurable: true
  68062. });
  68063. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  68064. set: function (wrap) {
  68065. if (this._textures) {
  68066. for (var i = 0; i < this._textures.length; i++) {
  68067. this._textures[i].wrapU = wrap;
  68068. }
  68069. }
  68070. },
  68071. enumerable: true,
  68072. configurable: true
  68073. });
  68074. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  68075. set: function (wrap) {
  68076. if (this._textures) {
  68077. for (var i = 0; i < this._textures.length; i++) {
  68078. this._textures[i].wrapV = wrap;
  68079. }
  68080. }
  68081. },
  68082. enumerable: true,
  68083. configurable: true
  68084. });
  68085. /** @hidden */
  68086. MultiRenderTarget.prototype._rebuild = function () {
  68087. this.releaseInternalTextures();
  68088. this._createInternalTextures();
  68089. for (var i = 0; i < this._internalTextures.length; i++) {
  68090. var texture = this._textures[i];
  68091. texture._texture = this._internalTextures[i];
  68092. }
  68093. // Keeps references to frame buffer and stencil/depth buffer
  68094. this._texture = this._internalTextures[0];
  68095. };
  68096. MultiRenderTarget.prototype._createInternalTextures = function () {
  68097. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  68098. };
  68099. MultiRenderTarget.prototype._createTextures = function () {
  68100. this._textures = [];
  68101. for (var i = 0; i < this._internalTextures.length; i++) {
  68102. var texture = new BABYLON.Texture(null, this.getScene());
  68103. texture._texture = this._internalTextures[i];
  68104. this._textures.push(texture);
  68105. }
  68106. // Keeps references to frame buffer and stencil/depth buffer
  68107. this._texture = this._internalTextures[0];
  68108. };
  68109. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  68110. get: function () {
  68111. return this._samples;
  68112. },
  68113. set: function (value) {
  68114. if (this._samples === value) {
  68115. return;
  68116. }
  68117. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  68118. },
  68119. enumerable: true,
  68120. configurable: true
  68121. });
  68122. MultiRenderTarget.prototype.resize = function (size) {
  68123. this.releaseInternalTextures();
  68124. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  68125. this._createInternalTextures();
  68126. };
  68127. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68128. var _this = this;
  68129. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  68130. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68131. });
  68132. };
  68133. MultiRenderTarget.prototype.dispose = function () {
  68134. this.releaseInternalTextures();
  68135. _super.prototype.dispose.call(this);
  68136. };
  68137. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  68138. if (!this._internalTextures) {
  68139. return;
  68140. }
  68141. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  68142. if (this._internalTextures[i] !== undefined) {
  68143. this._internalTextures[i].dispose();
  68144. this._internalTextures.splice(i, 1);
  68145. }
  68146. }
  68147. };
  68148. return MultiRenderTarget;
  68149. }(BABYLON.RenderTargetTexture));
  68150. BABYLON.MultiRenderTarget = MultiRenderTarget;
  68151. })(BABYLON || (BABYLON = {}));
  68152. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  68153. var BABYLON;
  68154. (function (BABYLON) {
  68155. var MirrorTexture = /** @class */ (function (_super) {
  68156. __extends(MirrorTexture, _super);
  68157. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  68158. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68159. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68160. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  68161. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  68162. _this.scene = scene;
  68163. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  68164. _this._transformMatrix = BABYLON.Matrix.Zero();
  68165. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  68166. _this._adaptiveBlurKernel = 0;
  68167. _this._blurKernelX = 0;
  68168. _this._blurKernelY = 0;
  68169. _this._blurRatio = 1.0;
  68170. _this.ignoreCameraViewport = true;
  68171. _this._updateGammaSpace();
  68172. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  68173. _this._updateGammaSpace;
  68174. });
  68175. _this.onBeforeRenderObservable.add(function () {
  68176. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  68177. _this._savedViewMatrix = scene.getViewMatrix();
  68178. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  68179. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  68180. scene.clipPlane = _this.mirrorPlane;
  68181. scene.getEngine().cullBackFaces = false;
  68182. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  68183. });
  68184. _this.onAfterRenderObservable.add(function () {
  68185. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  68186. scene.getEngine().cullBackFaces = true;
  68187. scene._mirroredCameraPosition = null;
  68188. delete scene.clipPlane;
  68189. });
  68190. return _this;
  68191. }
  68192. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  68193. get: function () {
  68194. return this._blurRatio;
  68195. },
  68196. set: function (value) {
  68197. if (this._blurRatio === value) {
  68198. return;
  68199. }
  68200. this._blurRatio = value;
  68201. this._preparePostProcesses();
  68202. },
  68203. enumerable: true,
  68204. configurable: true
  68205. });
  68206. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  68207. set: function (value) {
  68208. this._adaptiveBlurKernel = value;
  68209. this._autoComputeBlurKernel();
  68210. },
  68211. enumerable: true,
  68212. configurable: true
  68213. });
  68214. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  68215. set: function (value) {
  68216. this.blurKernelX = value;
  68217. this.blurKernelY = value;
  68218. },
  68219. enumerable: true,
  68220. configurable: true
  68221. });
  68222. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  68223. get: function () {
  68224. return this._blurKernelX;
  68225. },
  68226. set: function (value) {
  68227. if (this._blurKernelX === value) {
  68228. return;
  68229. }
  68230. this._blurKernelX = value;
  68231. this._preparePostProcesses();
  68232. },
  68233. enumerable: true,
  68234. configurable: true
  68235. });
  68236. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  68237. get: function () {
  68238. return this._blurKernelY;
  68239. },
  68240. set: function (value) {
  68241. if (this._blurKernelY === value) {
  68242. return;
  68243. }
  68244. this._blurKernelY = value;
  68245. this._preparePostProcesses();
  68246. },
  68247. enumerable: true,
  68248. configurable: true
  68249. });
  68250. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  68251. var engine = this.getScene().getEngine();
  68252. var dw = this.getRenderWidth() / engine.getRenderWidth();
  68253. var dh = this.getRenderHeight() / engine.getRenderHeight();
  68254. this.blurKernelX = this._adaptiveBlurKernel * dw;
  68255. this.blurKernelY = this._adaptiveBlurKernel * dh;
  68256. };
  68257. MirrorTexture.prototype._onRatioRescale = function () {
  68258. if (this._sizeRatio) {
  68259. this.resize(this._initialSizeParameter);
  68260. if (!this._adaptiveBlurKernel) {
  68261. this._preparePostProcesses();
  68262. }
  68263. }
  68264. if (this._adaptiveBlurKernel) {
  68265. this._autoComputeBlurKernel();
  68266. }
  68267. };
  68268. MirrorTexture.prototype._updateGammaSpace = function () {
  68269. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  68270. };
  68271. MirrorTexture.prototype._preparePostProcesses = function () {
  68272. this.clearPostProcesses(true);
  68273. if (this._blurKernelX && this._blurKernelY) {
  68274. var engine = this.getScene().getEngine();
  68275. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68276. 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);
  68277. this._blurX.autoClear = false;
  68278. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  68279. this._blurX.inputTexture = this._texture;
  68280. }
  68281. else {
  68282. this._blurX.alwaysForcePOT = true;
  68283. }
  68284. 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);
  68285. this._blurY.autoClear = false;
  68286. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  68287. this.addPostProcess(this._blurX);
  68288. this.addPostProcess(this._blurY);
  68289. }
  68290. else {
  68291. if (this._blurY) {
  68292. this.removePostProcess(this._blurY);
  68293. this._blurY.dispose();
  68294. this._blurY = null;
  68295. }
  68296. if (this._blurX) {
  68297. this.removePostProcess(this._blurX);
  68298. this._blurX.dispose();
  68299. this._blurX = null;
  68300. }
  68301. }
  68302. };
  68303. MirrorTexture.prototype.clone = function () {
  68304. var scene = this.getScene();
  68305. if (!scene) {
  68306. return this;
  68307. }
  68308. var textureSize = this.getSize();
  68309. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  68310. // Base texture
  68311. newTexture.hasAlpha = this.hasAlpha;
  68312. newTexture.level = this.level;
  68313. // Mirror Texture
  68314. newTexture.mirrorPlane = this.mirrorPlane.clone();
  68315. if (this.renderList) {
  68316. newTexture.renderList = this.renderList.slice(0);
  68317. }
  68318. return newTexture;
  68319. };
  68320. MirrorTexture.prototype.serialize = function () {
  68321. if (!this.name) {
  68322. return null;
  68323. }
  68324. var serializationObject = _super.prototype.serialize.call(this);
  68325. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  68326. return serializationObject;
  68327. };
  68328. MirrorTexture.prototype.dispose = function () {
  68329. _super.prototype.dispose.call(this);
  68330. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  68331. };
  68332. return MirrorTexture;
  68333. }(BABYLON.RenderTargetTexture));
  68334. BABYLON.MirrorTexture = MirrorTexture;
  68335. })(BABYLON || (BABYLON = {}));
  68336. //# sourceMappingURL=babylon.mirrorTexture.js.map
  68337. var BABYLON;
  68338. (function (BABYLON) {
  68339. /**
  68340. * Creates a refraction texture used by refraction channel of the standard material.
  68341. * @param name the texture name
  68342. * @param size size of the underlying texture
  68343. * @param scene root scene
  68344. */
  68345. var RefractionTexture = /** @class */ (function (_super) {
  68346. __extends(RefractionTexture, _super);
  68347. function RefractionTexture(name, size, scene, generateMipMaps) {
  68348. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  68349. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  68350. _this.depth = 2.0;
  68351. _this.onBeforeRenderObservable.add(function () {
  68352. scene.clipPlane = _this.refractionPlane;
  68353. });
  68354. _this.onAfterRenderObservable.add(function () {
  68355. delete scene.clipPlane;
  68356. });
  68357. return _this;
  68358. }
  68359. RefractionTexture.prototype.clone = function () {
  68360. var scene = this.getScene();
  68361. if (!scene) {
  68362. return this;
  68363. }
  68364. var textureSize = this.getSize();
  68365. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  68366. // Base texture
  68367. newTexture.hasAlpha = this.hasAlpha;
  68368. newTexture.level = this.level;
  68369. // Refraction Texture
  68370. newTexture.refractionPlane = this.refractionPlane.clone();
  68371. if (this.renderList) {
  68372. newTexture.renderList = this.renderList.slice(0);
  68373. }
  68374. newTexture.depth = this.depth;
  68375. return newTexture;
  68376. };
  68377. RefractionTexture.prototype.serialize = function () {
  68378. if (!this.name) {
  68379. return null;
  68380. }
  68381. var serializationObject = _super.prototype.serialize.call(this);
  68382. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  68383. serializationObject.depth = this.depth;
  68384. return serializationObject;
  68385. };
  68386. return RefractionTexture;
  68387. }(BABYLON.RenderTargetTexture));
  68388. BABYLON.RefractionTexture = RefractionTexture;
  68389. })(BABYLON || (BABYLON = {}));
  68390. //# sourceMappingURL=babylon.refractionTexture.js.map
  68391. var BABYLON;
  68392. (function (BABYLON) {
  68393. /**
  68394. * A class extending {BABYLON.Texture} allowing drawing on a texture
  68395. * @see http://doc.babylonjs.com/how_to/dynamictexture
  68396. */
  68397. var DynamicTexture = /** @class */ (function (_super) {
  68398. __extends(DynamicTexture, _super);
  68399. /**
  68400. * Creates a {BABYLON.DynamicTexture}
  68401. * @param name defines the name of the texture
  68402. * @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
  68403. * @param scene defines the scene where you want the texture
  68404. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  68405. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  68406. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  68407. */
  68408. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  68409. if (scene === void 0) { scene = null; }
  68410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68411. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68412. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  68413. _this.name = name;
  68414. _this._engine = _this.getScene().getEngine();
  68415. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68416. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68417. _this._generateMipMaps = generateMipMaps;
  68418. if (options.getContext) {
  68419. _this._canvas = options;
  68420. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68421. }
  68422. else {
  68423. _this._canvas = document.createElement("canvas");
  68424. if (options.width || options.width === 0) {
  68425. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68426. }
  68427. else {
  68428. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  68429. }
  68430. }
  68431. var textureSize = _this.getSize();
  68432. _this._canvas.width = textureSize.width;
  68433. _this._canvas.height = textureSize.height;
  68434. _this._context = _this._canvas.getContext("2d");
  68435. return _this;
  68436. }
  68437. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  68438. /**
  68439. * Gets the current state of canRescale
  68440. */
  68441. get: function () {
  68442. return true;
  68443. },
  68444. enumerable: true,
  68445. configurable: true
  68446. });
  68447. DynamicTexture.prototype._recreate = function (textureSize) {
  68448. this._canvas.width = textureSize.width;
  68449. this._canvas.height = textureSize.height;
  68450. this.releaseInternalTexture();
  68451. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  68452. };
  68453. /**
  68454. * Scales the texture
  68455. * @param ratio the scale factor to apply to both width and height
  68456. */
  68457. DynamicTexture.prototype.scale = function (ratio) {
  68458. var textureSize = this.getSize();
  68459. textureSize.width *= ratio;
  68460. textureSize.height *= ratio;
  68461. this._recreate(textureSize);
  68462. };
  68463. /**
  68464. * Resizes the texture
  68465. * @param width the new width
  68466. * @param height the new height
  68467. */
  68468. DynamicTexture.prototype.scaleTo = function (width, height) {
  68469. var textureSize = this.getSize();
  68470. textureSize.width = width;
  68471. textureSize.height = height;
  68472. this._recreate(textureSize);
  68473. };
  68474. /**
  68475. * Gets the context of the canvas used by the texture
  68476. * @returns the canvas context of the dynamic texture
  68477. */
  68478. DynamicTexture.prototype.getContext = function () {
  68479. return this._context;
  68480. };
  68481. /**
  68482. * Clears the texture
  68483. */
  68484. DynamicTexture.prototype.clear = function () {
  68485. var size = this.getSize();
  68486. this._context.fillRect(0, 0, size.width, size.height);
  68487. };
  68488. /**
  68489. * Updates the texture
  68490. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68491. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  68492. */
  68493. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  68494. if (premulAlpha === void 0) { premulAlpha = false; }
  68495. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  68496. };
  68497. /**
  68498. * Draws text onto the texture
  68499. * @param text defines the text to be drawn
  68500. * @param x defines the placement of the text from the left
  68501. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  68502. * @param font defines the font to be used with font-style, font-size, font-name
  68503. * @param color defines the color used for the text
  68504. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  68505. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68506. * @param update defines whether texture is immediately update (default is true)
  68507. */
  68508. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  68509. if (update === void 0) { update = true; }
  68510. var size = this.getSize();
  68511. if (clearColor) {
  68512. this._context.fillStyle = clearColor;
  68513. this._context.fillRect(0, 0, size.width, size.height);
  68514. }
  68515. this._context.font = font;
  68516. if (x === null || x === undefined) {
  68517. var textSize = this._context.measureText(text);
  68518. x = (size.width - textSize.width) / 2;
  68519. }
  68520. if (y === null || y === undefined) {
  68521. var fontSize = parseInt((font.replace(/\D/g, '')));
  68522. y = (size.height / 2) + (fontSize / 3.65);
  68523. }
  68524. this._context.fillStyle = color;
  68525. this._context.fillText(text, x, y);
  68526. if (update) {
  68527. this.update(invertY);
  68528. }
  68529. };
  68530. /**
  68531. * Clones the texture
  68532. * @returns the clone of the texture.
  68533. */
  68534. DynamicTexture.prototype.clone = function () {
  68535. var scene = this.getScene();
  68536. if (!scene) {
  68537. return this;
  68538. }
  68539. var textureSize = this.getSize();
  68540. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  68541. // Base texture
  68542. newTexture.hasAlpha = this.hasAlpha;
  68543. newTexture.level = this.level;
  68544. // Dynamic Texture
  68545. newTexture.wrapU = this.wrapU;
  68546. newTexture.wrapV = this.wrapV;
  68547. return newTexture;
  68548. };
  68549. /**
  68550. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  68551. * @returns a serialized dynamic texture object
  68552. */
  68553. DynamicTexture.prototype.serialize = function () {
  68554. var scene = this.getScene();
  68555. if (scene && !scene.isReady()) {
  68556. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  68557. }
  68558. var serializationObject = _super.prototype.serialize.call(this);
  68559. serializationObject.base64String = this._canvas.toDataURL();
  68560. serializationObject.invertY = this._invertY;
  68561. serializationObject.samplingMode = this.samplingMode;
  68562. return serializationObject;
  68563. };
  68564. /** @hidden */
  68565. DynamicTexture.prototype._rebuild = function () {
  68566. this.update();
  68567. };
  68568. return DynamicTexture;
  68569. }(BABYLON.Texture));
  68570. BABYLON.DynamicTexture = DynamicTexture;
  68571. })(BABYLON || (BABYLON = {}));
  68572. //# sourceMappingURL=babylon.dynamicTexture.js.map
  68573. var BABYLON;
  68574. (function (BABYLON) {
  68575. var VideoTexture = /** @class */ (function (_super) {
  68576. __extends(VideoTexture, _super);
  68577. /**
  68578. * Creates a video texture.
  68579. * Sample : https://doc.babylonjs.com/how_to/video_texture
  68580. * @param {string | null} name optional name, will detect from video source, if not defined
  68581. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  68582. * @param {BABYLON.Scene} scene is obviously the current scene.
  68583. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  68584. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  68585. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  68586. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  68587. */
  68588. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  68589. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68590. if (invertY === void 0) { invertY = false; }
  68591. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68592. if (settings === void 0) { settings = {
  68593. autoPlay: true,
  68594. loop: true,
  68595. autoUpdateTexture: true,
  68596. }; }
  68597. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68598. _this._onUserActionRequestedObservable = null;
  68599. _this._stillImageCaptured = false;
  68600. _this._poster = false;
  68601. _this._createInternalTexture = function () {
  68602. if (_this._texture != null) {
  68603. if (_this._poster) {
  68604. _this._texture.dispose();
  68605. _this._poster = false;
  68606. }
  68607. else {
  68608. return;
  68609. }
  68610. }
  68611. if (!_this._engine.needPOTTextures ||
  68612. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  68613. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68614. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68615. }
  68616. else {
  68617. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68618. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68619. _this._generateMipMaps = false;
  68620. }
  68621. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  68622. if (!_this.video.autoplay) {
  68623. var oldHandler_1 = _this.video.onplaying;
  68624. var error_1 = false;
  68625. _this.video.onplaying = function () {
  68626. _this.video.onplaying = oldHandler_1;
  68627. _this._texture.isReady = true;
  68628. _this._updateInternalTexture();
  68629. if (!error_1) {
  68630. _this.video.pause();
  68631. }
  68632. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68633. _this.onLoadObservable.notifyObservers(_this);
  68634. }
  68635. };
  68636. var playing = _this.video.play();
  68637. if (playing) {
  68638. playing.then(function () {
  68639. // Everything is good.
  68640. })
  68641. .catch(function () {
  68642. error_1 = true;
  68643. // On Chrome for instance, new policies might prevent playing without user interaction.
  68644. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  68645. _this._onUserActionRequestedObservable.notifyObservers(_this);
  68646. }
  68647. });
  68648. }
  68649. else {
  68650. _this.video.onplaying = oldHandler_1;
  68651. _this._texture.isReady = true;
  68652. _this._updateInternalTexture();
  68653. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68654. _this.onLoadObservable.notifyObservers(_this);
  68655. }
  68656. }
  68657. }
  68658. else {
  68659. _this._texture.isReady = true;
  68660. _this._updateInternalTexture();
  68661. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68662. _this.onLoadObservable.notifyObservers(_this);
  68663. }
  68664. }
  68665. };
  68666. _this.reset = function () {
  68667. if (_this._texture == null) {
  68668. return;
  68669. }
  68670. if (!_this._poster) {
  68671. _this._texture.dispose();
  68672. _this._texture = null;
  68673. }
  68674. };
  68675. _this._updateInternalTexture = function (e) {
  68676. if (_this._texture == null || !_this._texture.isReady) {
  68677. return;
  68678. }
  68679. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  68680. return;
  68681. }
  68682. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  68683. };
  68684. _this._engine = _this.getScene().getEngine();
  68685. _this._generateMipMaps = generateMipMaps;
  68686. _this._samplingMode = samplingMode;
  68687. _this.autoUpdateTexture = settings.autoUpdateTexture;
  68688. _this.name = name || _this._getName(src);
  68689. _this.video = _this._getVideo(src);
  68690. if (settings.poster) {
  68691. _this.video.poster = settings.poster;
  68692. }
  68693. if (settings.autoPlay !== undefined) {
  68694. _this.video.autoplay = settings.autoPlay;
  68695. }
  68696. if (settings.loop !== undefined) {
  68697. _this.video.loop = settings.loop;
  68698. }
  68699. _this.video.setAttribute("playsinline", "");
  68700. _this.video.addEventListener("canplay", _this._createInternalTexture);
  68701. _this.video.addEventListener("paused", _this._updateInternalTexture);
  68702. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  68703. _this.video.addEventListener("emptied", _this.reset);
  68704. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  68705. _this._createInternalTexture();
  68706. }
  68707. if (settings.poster) {
  68708. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  68709. _this._poster = true;
  68710. }
  68711. return _this;
  68712. }
  68713. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  68714. get: function () {
  68715. if (!this._onUserActionRequestedObservable) {
  68716. this._onUserActionRequestedObservable = new BABYLON.Observable();
  68717. }
  68718. return this._onUserActionRequestedObservable;
  68719. },
  68720. enumerable: true,
  68721. configurable: true
  68722. });
  68723. VideoTexture.prototype._getName = function (src) {
  68724. if (src instanceof HTMLVideoElement) {
  68725. return src.currentSrc;
  68726. }
  68727. if (typeof src === "object") {
  68728. return src.toString();
  68729. }
  68730. return src;
  68731. };
  68732. ;
  68733. VideoTexture.prototype._getVideo = function (src) {
  68734. if (src instanceof HTMLVideoElement) {
  68735. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  68736. return src;
  68737. }
  68738. var video = document.createElement("video");
  68739. if (typeof src === "string") {
  68740. BABYLON.Tools.SetCorsBehavior(src, video);
  68741. video.src = src;
  68742. }
  68743. else {
  68744. BABYLON.Tools.SetCorsBehavior(src[0], video);
  68745. src.forEach(function (url) {
  68746. var source = document.createElement("source");
  68747. source.src = url;
  68748. video.appendChild(source);
  68749. });
  68750. }
  68751. return video;
  68752. };
  68753. ;
  68754. /**
  68755. * @hidden Internal method to initiate `update`.
  68756. */
  68757. VideoTexture.prototype._rebuild = function () {
  68758. this.update();
  68759. };
  68760. /**
  68761. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  68762. */
  68763. VideoTexture.prototype.update = function () {
  68764. if (!this.autoUpdateTexture) {
  68765. // Expecting user to call `updateTexture` manually
  68766. return;
  68767. }
  68768. this.updateTexture(true);
  68769. };
  68770. /**
  68771. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  68772. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  68773. */
  68774. VideoTexture.prototype.updateTexture = function (isVisible) {
  68775. if (!isVisible) {
  68776. return;
  68777. }
  68778. if (this.video.paused && this._stillImageCaptured) {
  68779. return;
  68780. }
  68781. this._stillImageCaptured = true;
  68782. this._updateInternalTexture();
  68783. };
  68784. /**
  68785. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  68786. * @param url New url.
  68787. */
  68788. VideoTexture.prototype.updateURL = function (url) {
  68789. this.video.src = url;
  68790. };
  68791. VideoTexture.prototype.dispose = function () {
  68792. _super.prototype.dispose.call(this);
  68793. if (this._onUserActionRequestedObservable) {
  68794. this._onUserActionRequestedObservable.clear();
  68795. this._onUserActionRequestedObservable = null;
  68796. }
  68797. this.video.removeEventListener("canplay", this._createInternalTexture);
  68798. this.video.removeEventListener("paused", this._updateInternalTexture);
  68799. this.video.removeEventListener("seeked", this._updateInternalTexture);
  68800. this.video.removeEventListener("emptied", this.reset);
  68801. this.video.pause();
  68802. };
  68803. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  68804. var video = document.createElement("video");
  68805. video.setAttribute('autoplay', '');
  68806. video.setAttribute('muted', '');
  68807. video.setAttribute('playsinline', '');
  68808. var constraintsDeviceId;
  68809. if (constraints && constraints.deviceId) {
  68810. constraintsDeviceId = {
  68811. exact: constraints.deviceId,
  68812. };
  68813. }
  68814. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  68815. if (navigator.mediaDevices) {
  68816. navigator.mediaDevices.getUserMedia({ video: constraints })
  68817. .then(function (stream) {
  68818. if (video.mozSrcObject !== undefined) {
  68819. // hack for Firefox < 19
  68820. video.mozSrcObject = stream;
  68821. }
  68822. else {
  68823. video.srcObject = stream;
  68824. }
  68825. var onPlaying = function () {
  68826. if (onReady) {
  68827. onReady(new VideoTexture("video", video, scene, true, true));
  68828. }
  68829. video.removeEventListener("playing", onPlaying);
  68830. };
  68831. video.addEventListener("playing", onPlaying);
  68832. video.play();
  68833. })
  68834. .catch(function (err) {
  68835. BABYLON.Tools.Error(err.name);
  68836. });
  68837. }
  68838. else {
  68839. navigator.getUserMedia =
  68840. navigator.getUserMedia ||
  68841. navigator.webkitGetUserMedia ||
  68842. navigator.mozGetUserMedia ||
  68843. navigator.msGetUserMedia;
  68844. if (navigator.getUserMedia) {
  68845. navigator.getUserMedia({
  68846. video: {
  68847. deviceId: constraintsDeviceId,
  68848. width: {
  68849. min: (constraints && constraints.minWidth) || 256,
  68850. max: (constraints && constraints.maxWidth) || 640,
  68851. },
  68852. height: {
  68853. min: (constraints && constraints.minHeight) || 256,
  68854. max: (constraints && constraints.maxHeight) || 480,
  68855. },
  68856. },
  68857. }, function (stream) {
  68858. if (video.mozSrcObject !== undefined) {
  68859. // hack for Firefox < 19
  68860. video.mozSrcObject = stream;
  68861. }
  68862. else {
  68863. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  68864. }
  68865. video.play();
  68866. if (onReady) {
  68867. onReady(new VideoTexture("video", video, scene, true, true));
  68868. }
  68869. }, function (e) {
  68870. BABYLON.Tools.Error(e.name);
  68871. });
  68872. }
  68873. }
  68874. };
  68875. return VideoTexture;
  68876. }(BABYLON.Texture));
  68877. BABYLON.VideoTexture = VideoTexture;
  68878. })(BABYLON || (BABYLON = {}));
  68879. //# sourceMappingURL=babylon.videoTexture.js.map
  68880. var BABYLON;
  68881. (function (BABYLON) {
  68882. var RawTexture = /** @class */ (function (_super) {
  68883. __extends(RawTexture, _super);
  68884. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  68885. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68886. if (invertY === void 0) { invertY = false; }
  68887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68888. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68889. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68890. _this.format = format;
  68891. _this._engine = scene.getEngine();
  68892. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  68893. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68894. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68895. return _this;
  68896. }
  68897. RawTexture.prototype.update = function (data) {
  68898. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68899. };
  68900. // Statics
  68901. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68902. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68903. if (invertY === void 0) { invertY = false; }
  68904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68905. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68906. };
  68907. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68908. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68909. if (invertY === void 0) { invertY = false; }
  68910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68911. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68912. };
  68913. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68914. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68915. if (invertY === void 0) { invertY = false; }
  68916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68917. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68918. };
  68919. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68920. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68921. if (invertY === void 0) { invertY = false; }
  68922. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68923. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68924. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  68925. };
  68926. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68927. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68928. if (invertY === void 0) { invertY = false; }
  68929. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68930. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68931. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  68932. };
  68933. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68934. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68935. if (invertY === void 0) { invertY = false; }
  68936. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68937. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68938. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  68939. };
  68940. return RawTexture;
  68941. }(BABYLON.Texture));
  68942. BABYLON.RawTexture = RawTexture;
  68943. })(BABYLON || (BABYLON = {}));
  68944. //# sourceMappingURL=babylon.rawTexture.js.map
  68945. var BABYLON;
  68946. (function (BABYLON) {
  68947. /**
  68948. * Class used to store 3D textures containing user data
  68949. */
  68950. var RawTexture3D = /** @class */ (function (_super) {
  68951. __extends(RawTexture3D, _super);
  68952. /**
  68953. * Create a new RawTexture3D
  68954. * @param data defines the data of the texture
  68955. * @param width defines the width of the texture
  68956. * @param height defines the height of the texture
  68957. * @param depth defines the depth of the texture
  68958. * @param format defines the texture format to use
  68959. * @param scene defines the hosting scene
  68960. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  68961. * @param invertY defines if texture must be stored with Y axis inverted
  68962. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  68963. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68964. */
  68965. function RawTexture3D(data, width, height, depth,
  68966. /** Gets or sets the texture format to use */
  68967. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  68968. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68969. if (invertY === void 0) { invertY = false; }
  68970. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68971. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68972. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68973. _this.format = format;
  68974. _this._engine = scene.getEngine();
  68975. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  68976. _this.is3D = true;
  68977. return _this;
  68978. }
  68979. /**
  68980. * Update the texture with new data
  68981. * @param data defines the data to store in the texture
  68982. */
  68983. RawTexture3D.prototype.update = function (data) {
  68984. if (!this._texture) {
  68985. return;
  68986. }
  68987. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68988. };
  68989. return RawTexture3D;
  68990. }(BABYLON.Texture));
  68991. BABYLON.RawTexture3D = RawTexture3D;
  68992. })(BABYLON || (BABYLON = {}));
  68993. //# sourceMappingURL=babylon.rawTexture3D.js.map
  68994. var BABYLON;
  68995. (function (BABYLON) {
  68996. /**
  68997. * PostProcessManager is used to manage one or more post processes or post process pipelines
  68998. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68999. */
  69000. var PostProcessManager = /** @class */ (function () {
  69001. /**
  69002. * Creates a new instance PostProcess
  69003. * @param scene The scene that the post process is associated with.
  69004. */
  69005. function PostProcessManager(scene) {
  69006. this._vertexBuffers = {};
  69007. this._scene = scene;
  69008. }
  69009. PostProcessManager.prototype._prepareBuffers = function () {
  69010. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  69011. return;
  69012. }
  69013. // VBO
  69014. var vertices = [];
  69015. vertices.push(1, 1);
  69016. vertices.push(-1, 1);
  69017. vertices.push(-1, -1);
  69018. vertices.push(1, -1);
  69019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69020. this._buildIndexBuffer();
  69021. };
  69022. PostProcessManager.prototype._buildIndexBuffer = function () {
  69023. // Indices
  69024. var indices = [];
  69025. indices.push(0);
  69026. indices.push(1);
  69027. indices.push(2);
  69028. indices.push(0);
  69029. indices.push(2);
  69030. indices.push(3);
  69031. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  69032. };
  69033. /**
  69034. * Rebuilds the vertex buffers of the manager.
  69035. * @hidden
  69036. */
  69037. PostProcessManager.prototype._rebuild = function () {
  69038. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69039. if (!vb) {
  69040. return;
  69041. }
  69042. vb._rebuild();
  69043. this._buildIndexBuffer();
  69044. };
  69045. // Methods
  69046. /**
  69047. * Prepares a frame to be run through a post process.
  69048. * @param sourceTexture The input texture to the post procesess. (default: null)
  69049. * @param postProcesses An array of post processes to be run. (default: null)
  69050. * @returns True if the post processes were able to be run.
  69051. * @hidden
  69052. */
  69053. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  69054. if (sourceTexture === void 0) { sourceTexture = null; }
  69055. if (postProcesses === void 0) { postProcesses = null; }
  69056. var camera = this._scene.activeCamera;
  69057. if (!camera) {
  69058. return false;
  69059. }
  69060. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69061. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69062. return false;
  69063. }
  69064. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  69065. return true;
  69066. };
  69067. /**
  69068. * Manually render a set of post processes to a texture.
  69069. * @param postProcesses An array of post processes to be run.
  69070. * @param targetTexture The target texture to render to.
  69071. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  69072. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  69073. * @param lodLevel defines which lod of the texture to render to
  69074. */
  69075. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  69076. if (targetTexture === void 0) { targetTexture = null; }
  69077. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69078. if (faceIndex === void 0) { faceIndex = 0; }
  69079. if (lodLevel === void 0) { lodLevel = 0; }
  69080. var engine = this._scene.getEngine();
  69081. for (var index = 0; index < postProcesses.length; index++) {
  69082. if (index < postProcesses.length - 1) {
  69083. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  69084. }
  69085. else {
  69086. if (targetTexture) {
  69087. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  69088. }
  69089. else {
  69090. engine.restoreDefaultFramebuffer();
  69091. }
  69092. }
  69093. var pp = postProcesses[index];
  69094. var effect = pp.apply();
  69095. if (effect) {
  69096. pp.onBeforeRenderObservable.notifyObservers(effect);
  69097. // VBOs
  69098. this._prepareBuffers();
  69099. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69100. // Draw order
  69101. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69102. pp.onAfterRenderObservable.notifyObservers(effect);
  69103. }
  69104. }
  69105. // Restore depth buffer
  69106. engine.setDepthBuffer(true);
  69107. engine.setDepthWrite(true);
  69108. };
  69109. /**
  69110. * Finalize the result of the output of the postprocesses.
  69111. * @param doNotPresent If true the result will not be displayed to the screen.
  69112. * @param targetTexture The target texture to render to.
  69113. * @param faceIndex The index of the face to bind the target texture to.
  69114. * @param postProcesses The array of post processes to render.
  69115. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  69116. * @hidden
  69117. */
  69118. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  69119. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69120. var camera = this._scene.activeCamera;
  69121. if (!camera) {
  69122. return;
  69123. }
  69124. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69125. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69126. return;
  69127. }
  69128. var engine = this._scene.getEngine();
  69129. for (var index = 0, len = postProcesses.length; index < len; index++) {
  69130. var pp = postProcesses[index];
  69131. if (index < len - 1) {
  69132. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  69133. }
  69134. else {
  69135. if (targetTexture) {
  69136. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  69137. pp._outputTexture = targetTexture;
  69138. }
  69139. else {
  69140. engine.restoreDefaultFramebuffer();
  69141. pp._outputTexture = null;
  69142. }
  69143. }
  69144. if (doNotPresent) {
  69145. break;
  69146. }
  69147. var effect = pp.apply();
  69148. if (effect) {
  69149. pp.onBeforeRenderObservable.notifyObservers(effect);
  69150. // VBOs
  69151. this._prepareBuffers();
  69152. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69153. // Draw order
  69154. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69155. pp.onAfterRenderObservable.notifyObservers(effect);
  69156. }
  69157. }
  69158. // Restore states
  69159. engine.setDepthBuffer(true);
  69160. engine.setDepthWrite(true);
  69161. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69162. };
  69163. /**
  69164. * Disposes of the post process manager.
  69165. */
  69166. PostProcessManager.prototype.dispose = function () {
  69167. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69168. if (buffer) {
  69169. buffer.dispose();
  69170. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69171. }
  69172. if (this._indexBuffer) {
  69173. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69174. this._indexBuffer = null;
  69175. }
  69176. };
  69177. return PostProcessManager;
  69178. }());
  69179. BABYLON.PostProcessManager = PostProcessManager;
  69180. })(BABYLON || (BABYLON = {}));
  69181. //# sourceMappingURL=babylon.postProcessManager.js.map
  69182. var BABYLON;
  69183. (function (BABYLON) {
  69184. /**
  69185. * PostProcess can be used to apply a shader to a texture after it has been rendered
  69186. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69187. */
  69188. var PostProcess = /** @class */ (function () {
  69189. /**
  69190. * Creates a new instance PostProcess
  69191. * @param name The name of the PostProcess.
  69192. * @param fragmentUrl The url of the fragment shader to be used.
  69193. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  69194. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  69195. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69196. * @param camera The camera to apply the render pass to.
  69197. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69198. * @param engine The engine which the post process will be applied. (default: current engine)
  69199. * @param reusable If the post process can be reused on the same frame. (default: false)
  69200. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  69201. * @param textureType Type of textures used when performing the post process. (default: 0)
  69202. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  69203. * @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
  69204. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  69205. */
  69206. function PostProcess(
  69207. /** Name of the PostProcess. */
  69208. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  69209. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  69210. if (defines === void 0) { defines = null; }
  69211. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69212. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  69213. if (blockCompilation === void 0) { blockCompilation = false; }
  69214. this.name = name;
  69215. /**
  69216. * Width of the texture to apply the post process on
  69217. */
  69218. this.width = -1;
  69219. /**
  69220. * Height of the texture to apply the post process on
  69221. */
  69222. this.height = -1;
  69223. /**
  69224. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  69225. * @hidden
  69226. */
  69227. this._outputTexture = null;
  69228. /**
  69229. * If the buffer needs to be cleared before applying the post process. (default: true)
  69230. * Should be set to false if shader will overwrite all previous pixels.
  69231. */
  69232. this.autoClear = true;
  69233. /**
  69234. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  69235. */
  69236. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  69237. /**
  69238. * Animations to be used for the post processing
  69239. */
  69240. this.animations = new Array();
  69241. /**
  69242. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  69243. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  69244. */
  69245. this.enablePixelPerfectMode = false;
  69246. /**
  69247. * Force the postprocess to be applied without taking in account viewport
  69248. */
  69249. this.forceFullscreenViewport = true;
  69250. /**
  69251. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  69252. *
  69253. * | Value | Type | Description |
  69254. * | ----- | ----------------------------------- | ----------- |
  69255. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  69256. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  69257. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  69258. *
  69259. */
  69260. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  69261. /**
  69262. * Force textures to be a power of two (default: false)
  69263. */
  69264. this.alwaysForcePOT = false;
  69265. this._samples = 1;
  69266. /**
  69267. * Modify the scale of the post process to be the same as the viewport (default: false)
  69268. */
  69269. this.adaptScaleToCurrentViewport = false;
  69270. this._reusable = false;
  69271. /**
  69272. * Smart array of input and output textures for the post process.
  69273. * @hidden
  69274. */
  69275. this._textures = new BABYLON.SmartArray(2);
  69276. /**
  69277. * The index in _textures that corresponds to the output texture.
  69278. * @hidden
  69279. */
  69280. this._currentRenderTextureInd = 0;
  69281. this._scaleRatio = new BABYLON.Vector2(1, 1);
  69282. this._texelSize = BABYLON.Vector2.Zero();
  69283. // Events
  69284. /**
  69285. * An event triggered when the postprocess is activated.
  69286. */
  69287. this.onActivateObservable = new BABYLON.Observable();
  69288. /**
  69289. * An event triggered when the postprocess changes its size.
  69290. */
  69291. this.onSizeChangedObservable = new BABYLON.Observable();
  69292. /**
  69293. * An event triggered when the postprocess applies its effect.
  69294. */
  69295. this.onApplyObservable = new BABYLON.Observable();
  69296. /**
  69297. * An event triggered before rendering the postprocess
  69298. */
  69299. this.onBeforeRenderObservable = new BABYLON.Observable();
  69300. /**
  69301. * An event triggered after rendering the postprocess
  69302. */
  69303. this.onAfterRenderObservable = new BABYLON.Observable();
  69304. if (camera != null) {
  69305. this._camera = camera;
  69306. this._scene = camera.getScene();
  69307. camera.attachPostProcess(this);
  69308. this._engine = this._scene.getEngine();
  69309. this._scene.postProcesses.push(this);
  69310. }
  69311. else if (engine) {
  69312. this._engine = engine;
  69313. this._engine.postProcesses.push(this);
  69314. }
  69315. this._options = options;
  69316. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  69317. this._reusable = reusable || false;
  69318. this._textureType = textureType;
  69319. this._samplers = samplers || [];
  69320. this._samplers.push("textureSampler");
  69321. this._fragmentUrl = fragmentUrl;
  69322. this._vertexUrl = vertexUrl;
  69323. this._parameters = parameters || [];
  69324. this._parameters.push("scale");
  69325. this._indexParameters = indexParameters;
  69326. if (!blockCompilation) {
  69327. this.updateEffect(defines);
  69328. }
  69329. }
  69330. Object.defineProperty(PostProcess.prototype, "samples", {
  69331. /**
  69332. * Number of sample textures (default: 1)
  69333. */
  69334. get: function () {
  69335. return this._samples;
  69336. },
  69337. set: function (n) {
  69338. var _this = this;
  69339. this._samples = n;
  69340. this._textures.forEach(function (texture) {
  69341. if (texture.samples !== _this._samples) {
  69342. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  69343. }
  69344. });
  69345. },
  69346. enumerable: true,
  69347. configurable: true
  69348. });
  69349. Object.defineProperty(PostProcess.prototype, "onActivate", {
  69350. /**
  69351. * A function that is added to the onActivateObservable
  69352. */
  69353. set: function (callback) {
  69354. if (this._onActivateObserver) {
  69355. this.onActivateObservable.remove(this._onActivateObserver);
  69356. }
  69357. if (callback) {
  69358. this._onActivateObserver = this.onActivateObservable.add(callback);
  69359. }
  69360. },
  69361. enumerable: true,
  69362. configurable: true
  69363. });
  69364. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  69365. /**
  69366. * A function that is added to the onSizeChangedObservable
  69367. */
  69368. set: function (callback) {
  69369. if (this._onSizeChangedObserver) {
  69370. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  69371. }
  69372. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  69373. },
  69374. enumerable: true,
  69375. configurable: true
  69376. });
  69377. Object.defineProperty(PostProcess.prototype, "onApply", {
  69378. /**
  69379. * A function that is added to the onApplyObservable
  69380. */
  69381. set: function (callback) {
  69382. if (this._onApplyObserver) {
  69383. this.onApplyObservable.remove(this._onApplyObserver);
  69384. }
  69385. this._onApplyObserver = this.onApplyObservable.add(callback);
  69386. },
  69387. enumerable: true,
  69388. configurable: true
  69389. });
  69390. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  69391. /**
  69392. * A function that is added to the onBeforeRenderObservable
  69393. */
  69394. set: function (callback) {
  69395. if (this._onBeforeRenderObserver) {
  69396. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69397. }
  69398. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69399. },
  69400. enumerable: true,
  69401. configurable: true
  69402. });
  69403. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  69404. /**
  69405. * A function that is added to the onAfterRenderObservable
  69406. */
  69407. set: function (callback) {
  69408. if (this._onAfterRenderObserver) {
  69409. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69410. }
  69411. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69412. },
  69413. enumerable: true,
  69414. configurable: true
  69415. });
  69416. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  69417. /**
  69418. * 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
  69419. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  69420. */
  69421. get: function () {
  69422. return this._textures.data[this._currentRenderTextureInd];
  69423. },
  69424. set: function (value) {
  69425. this._forcedOutputTexture = value;
  69426. },
  69427. enumerable: true,
  69428. configurable: true
  69429. });
  69430. /**
  69431. * Gets the camera which post process is applied to.
  69432. * @returns The camera the post process is applied to.
  69433. */
  69434. PostProcess.prototype.getCamera = function () {
  69435. return this._camera;
  69436. };
  69437. Object.defineProperty(PostProcess.prototype, "texelSize", {
  69438. /**
  69439. * Gets the texel size of the postprocess.
  69440. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  69441. */
  69442. get: function () {
  69443. if (this._shareOutputWithPostProcess) {
  69444. return this._shareOutputWithPostProcess.texelSize;
  69445. }
  69446. if (this._forcedOutputTexture) {
  69447. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  69448. }
  69449. return this._texelSize;
  69450. },
  69451. enumerable: true,
  69452. configurable: true
  69453. });
  69454. /**
  69455. * Gets the engine which this post process belongs to.
  69456. * @returns The engine the post process was enabled with.
  69457. */
  69458. PostProcess.prototype.getEngine = function () {
  69459. return this._engine;
  69460. };
  69461. /**
  69462. * The effect that is created when initializing the post process.
  69463. * @returns The created effect corrisponding the the postprocess.
  69464. */
  69465. PostProcess.prototype.getEffect = function () {
  69466. return this._effect;
  69467. };
  69468. /**
  69469. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  69470. * @param postProcess The post process to share the output with.
  69471. * @returns This post process.
  69472. */
  69473. PostProcess.prototype.shareOutputWith = function (postProcess) {
  69474. this._disposeTextures();
  69475. this._shareOutputWithPostProcess = postProcess;
  69476. return this;
  69477. };
  69478. /**
  69479. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  69480. * This should be called if the post process that shares output with this post process is disabled/disposed.
  69481. */
  69482. PostProcess.prototype.useOwnOutput = function () {
  69483. if (this._textures.length == 0) {
  69484. this._textures = new BABYLON.SmartArray(2);
  69485. }
  69486. this._shareOutputWithPostProcess = null;
  69487. };
  69488. /**
  69489. * Updates the effect with the current post process compile time values and recompiles the shader.
  69490. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69491. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69492. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69493. * @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
  69494. * @param onCompiled Called when the shader has been compiled.
  69495. * @param onError Called if there is an error when compiling a shader.
  69496. */
  69497. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69498. if (defines === void 0) { defines = null; }
  69499. if (uniforms === void 0) { uniforms = null; }
  69500. if (samplers === void 0) { samplers = null; }
  69501. 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);
  69502. };
  69503. /**
  69504. * The post process is reusable if it can be used multiple times within one frame.
  69505. * @returns If the post process is reusable
  69506. */
  69507. PostProcess.prototype.isReusable = function () {
  69508. return this._reusable;
  69509. };
  69510. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  69511. PostProcess.prototype.markTextureDirty = function () {
  69512. this.width = -1;
  69513. };
  69514. /**
  69515. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  69516. * 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.
  69517. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  69518. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  69519. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  69520. * @returns The target texture that was bound to be written to.
  69521. */
  69522. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  69523. var _this = this;
  69524. if (sourceTexture === void 0) { sourceTexture = null; }
  69525. camera = camera || this._camera;
  69526. var scene = camera.getScene();
  69527. var engine = scene.getEngine();
  69528. var maxSize = engine.getCaps().maxTextureSize;
  69529. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  69530. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  69531. // 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
  69532. var webVRCamera = camera.parent;
  69533. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  69534. requiredWidth /= 2;
  69535. }
  69536. var desiredWidth = (this._options.width || requiredWidth);
  69537. var desiredHeight = this._options.height || requiredHeight;
  69538. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  69539. if (this.adaptScaleToCurrentViewport) {
  69540. var currentViewport = engine.currentViewport;
  69541. if (currentViewport) {
  69542. desiredWidth *= currentViewport.width;
  69543. desiredHeight *= currentViewport.height;
  69544. }
  69545. }
  69546. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  69547. if (!this._options.width) {
  69548. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  69549. }
  69550. if (!this._options.height) {
  69551. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  69552. }
  69553. }
  69554. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  69555. if (this._textures.length > 0) {
  69556. for (var i = 0; i < this._textures.length; i++) {
  69557. this._engine._releaseTexture(this._textures.data[i]);
  69558. }
  69559. this._textures.reset();
  69560. }
  69561. this.width = desiredWidth;
  69562. this.height = desiredHeight;
  69563. var textureSize = { width: this.width, height: this.height };
  69564. var textureOptions = {
  69565. generateMipMaps: false,
  69566. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  69567. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  69568. samplingMode: this.renderTargetSamplingMode,
  69569. type: this._textureType
  69570. };
  69571. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69572. if (this._reusable) {
  69573. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69574. }
  69575. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  69576. this.onSizeChangedObservable.notifyObservers(this);
  69577. }
  69578. this._textures.forEach(function (texture) {
  69579. if (texture.samples !== _this.samples) {
  69580. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  69581. }
  69582. });
  69583. }
  69584. var target;
  69585. if (this._shareOutputWithPostProcess) {
  69586. target = this._shareOutputWithPostProcess.inputTexture;
  69587. }
  69588. else if (this._forcedOutputTexture) {
  69589. target = this._forcedOutputTexture;
  69590. this.width = this._forcedOutputTexture.width;
  69591. this.height = this._forcedOutputTexture.height;
  69592. }
  69593. else {
  69594. target = this.inputTexture;
  69595. }
  69596. // Bind the input of this post process to be used as the output of the previous post process.
  69597. if (this.enablePixelPerfectMode) {
  69598. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  69599. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  69600. }
  69601. else {
  69602. this._scaleRatio.copyFromFloats(1, 1);
  69603. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  69604. }
  69605. this.onActivateObservable.notifyObservers(camera);
  69606. // Clear
  69607. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  69608. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  69609. }
  69610. if (this._reusable) {
  69611. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  69612. }
  69613. return target;
  69614. };
  69615. Object.defineProperty(PostProcess.prototype, "isSupported", {
  69616. /**
  69617. * If the post process is supported.
  69618. */
  69619. get: function () {
  69620. return this._effect.isSupported;
  69621. },
  69622. enumerable: true,
  69623. configurable: true
  69624. });
  69625. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  69626. /**
  69627. * The aspect ratio of the output texture.
  69628. */
  69629. get: function () {
  69630. if (this._shareOutputWithPostProcess) {
  69631. return this._shareOutputWithPostProcess.aspectRatio;
  69632. }
  69633. if (this._forcedOutputTexture) {
  69634. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  69635. }
  69636. return this.width / this.height;
  69637. },
  69638. enumerable: true,
  69639. configurable: true
  69640. });
  69641. /**
  69642. * Get a value indicating if the post-process is ready to be used
  69643. * @returns true if the post-process is ready (shader is compiled)
  69644. */
  69645. PostProcess.prototype.isReady = function () {
  69646. return this._effect && this._effect.isReady();
  69647. };
  69648. /**
  69649. * Binds all textures and uniforms to the shader, this will be run on every pass.
  69650. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  69651. */
  69652. PostProcess.prototype.apply = function () {
  69653. // Check
  69654. if (!this._effect || !this._effect.isReady())
  69655. return null;
  69656. // States
  69657. this._engine.enableEffect(this._effect);
  69658. this._engine.setState(false);
  69659. this._engine.setDepthBuffer(false);
  69660. this._engine.setDepthWrite(false);
  69661. // Alpha
  69662. this._engine.setAlphaMode(this.alphaMode);
  69663. if (this.alphaConstants) {
  69664. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  69665. }
  69666. // Bind the output texture of the preivous post process as the input to this post process.
  69667. var source;
  69668. if (this._shareOutputWithPostProcess) {
  69669. source = this._shareOutputWithPostProcess.inputTexture;
  69670. }
  69671. else if (this._forcedOutputTexture) {
  69672. source = this._forcedOutputTexture;
  69673. }
  69674. else {
  69675. source = this.inputTexture;
  69676. }
  69677. this._effect._bindTexture("textureSampler", source);
  69678. // Parameters
  69679. this._effect.setVector2("scale", this._scaleRatio);
  69680. this.onApplyObservable.notifyObservers(this._effect);
  69681. return this._effect;
  69682. };
  69683. PostProcess.prototype._disposeTextures = function () {
  69684. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  69685. return;
  69686. }
  69687. if (this._textures.length > 0) {
  69688. for (var i = 0; i < this._textures.length; i++) {
  69689. this._engine._releaseTexture(this._textures.data[i]);
  69690. }
  69691. }
  69692. this._textures.dispose();
  69693. };
  69694. /**
  69695. * Disposes the post process.
  69696. * @param camera The camera to dispose the post process on.
  69697. */
  69698. PostProcess.prototype.dispose = function (camera) {
  69699. camera = camera || this._camera;
  69700. this._disposeTextures();
  69701. if (this._scene) {
  69702. var index_1 = this._scene.postProcesses.indexOf(this);
  69703. if (index_1 !== -1) {
  69704. this._scene.postProcesses.splice(index_1, 1);
  69705. }
  69706. }
  69707. else {
  69708. var index_2 = this._engine.postProcesses.indexOf(this);
  69709. if (index_2 !== -1) {
  69710. this._engine.postProcesses.splice(index_2, 1);
  69711. }
  69712. }
  69713. if (!camera) {
  69714. return;
  69715. }
  69716. camera.detachPostProcess(this);
  69717. var index = camera._postProcesses.indexOf(this);
  69718. if (index === 0 && camera._postProcesses.length > 0) {
  69719. var firstPostProcess = this._camera._getFirstPostProcess();
  69720. if (firstPostProcess) {
  69721. firstPostProcess.markTextureDirty();
  69722. }
  69723. }
  69724. this.onActivateObservable.clear();
  69725. this.onAfterRenderObservable.clear();
  69726. this.onApplyObservable.clear();
  69727. this.onBeforeRenderObservable.clear();
  69728. this.onSizeChangedObservable.clear();
  69729. };
  69730. return PostProcess;
  69731. }());
  69732. BABYLON.PostProcess = PostProcess;
  69733. })(BABYLON || (BABYLON = {}));
  69734. //# sourceMappingURL=babylon.postProcess.js.map
  69735. var BABYLON;
  69736. (function (BABYLON) {
  69737. var PassPostProcess = /** @class */ (function (_super) {
  69738. __extends(PassPostProcess, _super);
  69739. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69740. if (camera === void 0) { camera = null; }
  69741. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69742. if (blockCompilation === void 0) { blockCompilation = false; }
  69743. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  69744. }
  69745. return PassPostProcess;
  69746. }(BABYLON.PostProcess));
  69747. BABYLON.PassPostProcess = PassPostProcess;
  69748. })(BABYLON || (BABYLON = {}));
  69749. //# sourceMappingURL=babylon.passPostProcess.js.map
  69750. var __assign = (this && this.__assign) || function () {
  69751. __assign = Object.assign || function(t) {
  69752. for (var s, i = 1, n = arguments.length; i < n; i++) {
  69753. s = arguments[i];
  69754. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  69755. t[p] = s[p];
  69756. }
  69757. return t;
  69758. };
  69759. return __assign.apply(this, arguments);
  69760. };
  69761. var BABYLON;
  69762. (function (BABYLON) {
  69763. /**
  69764. * Default implementation IShadowGenerator.
  69765. * This is the main object responsible of generating shadows in the framework.
  69766. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  69767. */
  69768. var ShadowGenerator = /** @class */ (function () {
  69769. /**
  69770. * Creates a ShadowGenerator object.
  69771. * A ShadowGenerator is the required tool to use the shadows.
  69772. * Each light casting shadows needs to use its own ShadowGenerator.
  69773. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  69774. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  69775. * @param light The light object generating the shadows.
  69776. * @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.
  69777. */
  69778. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  69779. this._bias = 0.00005;
  69780. this._normalBias = 0;
  69781. this._blurBoxOffset = 1;
  69782. this._blurScale = 2;
  69783. this._blurKernel = 1;
  69784. this._useKernelBlur = false;
  69785. this._filter = ShadowGenerator.FILTER_NONE;
  69786. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  69787. this._contactHardeningLightSizeUVRatio = 0.1;
  69788. this._darkness = 0;
  69789. this._transparencyShadow = false;
  69790. /**
  69791. * Controls the extent to which the shadows fade out at the edge of the frustum
  69792. * Used only by directionals and spots
  69793. */
  69794. this.frustumEdgeFalloff = 0;
  69795. /**
  69796. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  69797. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  69798. * It might on the other hand introduce peter panning.
  69799. */
  69800. this.forceBackFacesOnly = false;
  69801. this._lightDirection = BABYLON.Vector3.Zero();
  69802. this._viewMatrix = BABYLON.Matrix.Zero();
  69803. this._projectionMatrix = BABYLON.Matrix.Zero();
  69804. this._transformMatrix = BABYLON.Matrix.Zero();
  69805. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69806. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69807. this._currentFaceIndex = 0;
  69808. this._currentFaceIndexCache = 0;
  69809. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  69810. this._mapSize = mapSize;
  69811. this._light = light;
  69812. this._scene = light.getScene();
  69813. light._shadowGenerator = this;
  69814. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  69815. if (!component) {
  69816. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  69817. this._scene._addComponent(component);
  69818. }
  69819. // Texture type fallback from float to int if not supported.
  69820. var caps = this._scene.getEngine().getCaps();
  69821. if (!useFullFloatFirst) {
  69822. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69823. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69824. }
  69825. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69826. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69827. }
  69828. else {
  69829. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69830. }
  69831. }
  69832. else {
  69833. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69834. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69835. }
  69836. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69837. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69838. }
  69839. else {
  69840. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69841. }
  69842. }
  69843. this._initializeGenerator();
  69844. this._applyFilterValues();
  69845. }
  69846. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  69847. /**
  69848. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  69849. */
  69850. get: function () {
  69851. return this._bias;
  69852. },
  69853. /**
  69854. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  69855. */
  69856. set: function (bias) {
  69857. this._bias = bias;
  69858. },
  69859. enumerable: true,
  69860. configurable: true
  69861. });
  69862. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  69863. /**
  69864. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69865. */
  69866. get: function () {
  69867. return this._normalBias;
  69868. },
  69869. /**
  69870. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69871. */
  69872. set: function (normalBias) {
  69873. this._normalBias = normalBias;
  69874. },
  69875. enumerable: true,
  69876. configurable: true
  69877. });
  69878. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  69879. /**
  69880. * Gets the blur box offset: offset applied during the blur pass.
  69881. * Only usefull if useKernelBlur = false
  69882. */
  69883. get: function () {
  69884. return this._blurBoxOffset;
  69885. },
  69886. /**
  69887. * Sets the blur box offset: offset applied during the blur pass.
  69888. * Only usefull if useKernelBlur = false
  69889. */
  69890. set: function (value) {
  69891. if (this._blurBoxOffset === value) {
  69892. return;
  69893. }
  69894. this._blurBoxOffset = value;
  69895. this._disposeBlurPostProcesses();
  69896. },
  69897. enumerable: true,
  69898. configurable: true
  69899. });
  69900. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  69901. /**
  69902. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  69903. * 2 means half of the size.
  69904. */
  69905. get: function () {
  69906. return this._blurScale;
  69907. },
  69908. /**
  69909. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  69910. * 2 means half of the size.
  69911. */
  69912. set: function (value) {
  69913. if (this._blurScale === value) {
  69914. return;
  69915. }
  69916. this._blurScale = value;
  69917. this._disposeBlurPostProcesses();
  69918. },
  69919. enumerable: true,
  69920. configurable: true
  69921. });
  69922. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  69923. /**
  69924. * Gets the blur kernel: kernel size of the blur pass.
  69925. * Only usefull if useKernelBlur = true
  69926. */
  69927. get: function () {
  69928. return this._blurKernel;
  69929. },
  69930. /**
  69931. * Sets the blur kernel: kernel size of the blur pass.
  69932. * Only usefull if useKernelBlur = true
  69933. */
  69934. set: function (value) {
  69935. if (this._blurKernel === value) {
  69936. return;
  69937. }
  69938. this._blurKernel = value;
  69939. this._disposeBlurPostProcesses();
  69940. },
  69941. enumerable: true,
  69942. configurable: true
  69943. });
  69944. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  69945. /**
  69946. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  69947. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69948. */
  69949. get: function () {
  69950. return this._useKernelBlur;
  69951. },
  69952. /**
  69953. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  69954. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69955. */
  69956. set: function (value) {
  69957. if (this._useKernelBlur === value) {
  69958. return;
  69959. }
  69960. this._useKernelBlur = value;
  69961. this._disposeBlurPostProcesses();
  69962. },
  69963. enumerable: true,
  69964. configurable: true
  69965. });
  69966. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  69967. /**
  69968. * Gets the depth scale used in ESM mode.
  69969. */
  69970. get: function () {
  69971. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  69972. },
  69973. /**
  69974. * Sets the depth scale used in ESM mode.
  69975. * This can override the scale stored on the light.
  69976. */
  69977. set: function (value) {
  69978. this._depthScale = value;
  69979. },
  69980. enumerable: true,
  69981. configurable: true
  69982. });
  69983. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  69984. /**
  69985. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  69986. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69987. */
  69988. get: function () {
  69989. return this._filter;
  69990. },
  69991. /**
  69992. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  69993. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69994. */
  69995. set: function (value) {
  69996. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  69997. if (this._light.needCube()) {
  69998. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69999. this.useExponentialShadowMap = true;
  70000. return;
  70001. }
  70002. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70003. this.useCloseExponentialShadowMap = true;
  70004. return;
  70005. }
  70006. // PCF on cubemap would also be expensive
  70007. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70008. this.usePoissonSampling = true;
  70009. return;
  70010. }
  70011. }
  70012. // Weblg1 fallback for PCF.
  70013. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70014. if (this._scene.getEngine().webGLVersion === 1) {
  70015. this.usePoissonSampling = true;
  70016. return;
  70017. }
  70018. }
  70019. if (this._filter === value) {
  70020. return;
  70021. }
  70022. this._filter = value;
  70023. this._disposeBlurPostProcesses();
  70024. this._applyFilterValues();
  70025. this._light._markMeshesAsLightDirty();
  70026. },
  70027. enumerable: true,
  70028. configurable: true
  70029. });
  70030. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  70031. /**
  70032. * Gets if the current filter is set to Poisson Sampling.
  70033. */
  70034. get: function () {
  70035. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  70036. },
  70037. /**
  70038. * Sets the current filter to Poisson Sampling.
  70039. */
  70040. set: function (value) {
  70041. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  70042. return;
  70043. }
  70044. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  70045. },
  70046. enumerable: true,
  70047. configurable: true
  70048. });
  70049. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  70050. /**
  70051. * Gets if the current filter is set to VSM.
  70052. * DEPRECATED. Should use useExponentialShadowMap instead.
  70053. */
  70054. get: function () {
  70055. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70056. return this.useExponentialShadowMap;
  70057. },
  70058. /**
  70059. * Sets the current filter is to VSM.
  70060. * DEPRECATED. Should use useExponentialShadowMap instead.
  70061. */
  70062. set: function (value) {
  70063. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70064. this.useExponentialShadowMap = value;
  70065. },
  70066. enumerable: true,
  70067. configurable: true
  70068. });
  70069. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  70070. /**
  70071. * Gets if the current filter is set to blurred VSM.
  70072. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70073. */
  70074. get: function () {
  70075. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70076. return this.useBlurExponentialShadowMap;
  70077. },
  70078. /**
  70079. * Sets the current filter is to blurred VSM.
  70080. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70081. */
  70082. set: function (value) {
  70083. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70084. this.useBlurExponentialShadowMap = value;
  70085. },
  70086. enumerable: true,
  70087. configurable: true
  70088. });
  70089. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  70090. /**
  70091. * Gets if the current filter is set to ESM.
  70092. */
  70093. get: function () {
  70094. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  70095. },
  70096. /**
  70097. * Sets the current filter is to ESM.
  70098. */
  70099. set: function (value) {
  70100. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  70101. return;
  70102. }
  70103. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70104. },
  70105. enumerable: true,
  70106. configurable: true
  70107. });
  70108. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  70109. /**
  70110. * Gets if the current filter is set to filtered ESM.
  70111. */
  70112. get: function () {
  70113. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  70114. },
  70115. /**
  70116. * Gets if the current filter is set to filtered ESM.
  70117. */
  70118. set: function (value) {
  70119. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70120. return;
  70121. }
  70122. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70123. },
  70124. enumerable: true,
  70125. configurable: true
  70126. });
  70127. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  70128. /**
  70129. * Gets if the current filter is set to "close ESM" (using the inverse of the
  70130. * exponential to prevent steep falloff artifacts).
  70131. */
  70132. get: function () {
  70133. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  70134. },
  70135. /**
  70136. * Sets the current filter to "close ESM" (using the inverse of the
  70137. * exponential to prevent steep falloff artifacts).
  70138. */
  70139. set: function (value) {
  70140. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  70141. return;
  70142. }
  70143. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70144. },
  70145. enumerable: true,
  70146. configurable: true
  70147. });
  70148. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  70149. /**
  70150. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  70151. * exponential to prevent steep falloff artifacts).
  70152. */
  70153. get: function () {
  70154. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  70155. },
  70156. /**
  70157. * Sets the current filter to filtered "close ESM" (using the inverse of the
  70158. * exponential to prevent steep falloff artifacts).
  70159. */
  70160. set: function (value) {
  70161. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70162. return;
  70163. }
  70164. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70165. },
  70166. enumerable: true,
  70167. configurable: true
  70168. });
  70169. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  70170. /**
  70171. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  70172. */
  70173. get: function () {
  70174. return this.filter === ShadowGenerator.FILTER_PCF;
  70175. },
  70176. /**
  70177. * Sets the current filter to "PCF" (percentage closer filtering).
  70178. */
  70179. set: function (value) {
  70180. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  70181. return;
  70182. }
  70183. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  70184. },
  70185. enumerable: true,
  70186. configurable: true
  70187. });
  70188. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  70189. /**
  70190. * Gets the PCF or PCSS Quality.
  70191. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70192. */
  70193. get: function () {
  70194. return this._filteringQuality;
  70195. },
  70196. /**
  70197. * Sets the PCF or PCSS Quality.
  70198. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70199. */
  70200. set: function (filteringQuality) {
  70201. this._filteringQuality = filteringQuality;
  70202. },
  70203. enumerable: true,
  70204. configurable: true
  70205. });
  70206. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  70207. /**
  70208. * Gets if the current filter is set to "PCSS" (contact hardening).
  70209. */
  70210. get: function () {
  70211. return this.filter === ShadowGenerator.FILTER_PCSS;
  70212. },
  70213. /**
  70214. * Sets the current filter to "PCSS" (contact hardening).
  70215. */
  70216. set: function (value) {
  70217. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  70218. return;
  70219. }
  70220. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  70221. },
  70222. enumerable: true,
  70223. configurable: true
  70224. });
  70225. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  70226. /**
  70227. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70228. * Using a ratio helps keeping shape stability independently of the map size.
  70229. *
  70230. * It does not account for the light projection as it was having too much
  70231. * instability during the light setup or during light position changes.
  70232. *
  70233. * Only valid if useContactHardeningShadow is true.
  70234. */
  70235. get: function () {
  70236. return this._contactHardeningLightSizeUVRatio;
  70237. },
  70238. /**
  70239. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70240. * Using a ratio helps keeping shape stability independently of the map size.
  70241. *
  70242. * It does not account for the light projection as it was having too much
  70243. * instability during the light setup or during light position changes.
  70244. *
  70245. * Only valid if useContactHardeningShadow is true.
  70246. */
  70247. set: function (contactHardeningLightSizeUVRatio) {
  70248. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  70249. },
  70250. enumerable: true,
  70251. configurable: true
  70252. });
  70253. /**
  70254. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  70255. * 0 means strongest and 1 would means no shadow.
  70256. * @returns the darkness.
  70257. */
  70258. ShadowGenerator.prototype.getDarkness = function () {
  70259. return this._darkness;
  70260. };
  70261. /**
  70262. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  70263. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  70264. * @returns the shadow generator allowing fluent coding.
  70265. */
  70266. ShadowGenerator.prototype.setDarkness = function (darkness) {
  70267. if (darkness >= 1.0)
  70268. this._darkness = 1.0;
  70269. else if (darkness <= 0.0)
  70270. this._darkness = 0.0;
  70271. else
  70272. this._darkness = darkness;
  70273. return this;
  70274. };
  70275. /**
  70276. * Sets the ability to have transparent shadow (boolean).
  70277. * @param transparent True if transparent else False
  70278. * @returns the shadow generator allowing fluent coding
  70279. */
  70280. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  70281. this._transparencyShadow = transparent;
  70282. return this;
  70283. };
  70284. /**
  70285. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  70286. * @returns The render target texture if present otherwise, null
  70287. */
  70288. ShadowGenerator.prototype.getShadowMap = function () {
  70289. return this._shadowMap;
  70290. };
  70291. /**
  70292. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  70293. * @returns The render target texture if the shadow map is present otherwise, null
  70294. */
  70295. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  70296. if (this._shadowMap2) {
  70297. return this._shadowMap2;
  70298. }
  70299. return this._shadowMap;
  70300. };
  70301. /**
  70302. * Helper function to add a mesh and its descendants to the list of shadow casters.
  70303. * @param mesh Mesh to add
  70304. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  70305. * @returns the Shadow Generator itself
  70306. */
  70307. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  70308. if (includeDescendants === void 0) { includeDescendants = true; }
  70309. var _a;
  70310. if (!this._shadowMap) {
  70311. return this;
  70312. }
  70313. if (!this._shadowMap.renderList) {
  70314. this._shadowMap.renderList = [];
  70315. }
  70316. this._shadowMap.renderList.push(mesh);
  70317. if (includeDescendants) {
  70318. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  70319. }
  70320. return this;
  70321. };
  70322. /**
  70323. * Helper function to remove a mesh and its descendants from the list of shadow casters
  70324. * @param mesh Mesh to remove
  70325. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  70326. * @returns the Shadow Generator itself
  70327. */
  70328. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  70329. if (includeDescendants === void 0) { includeDescendants = true; }
  70330. if (!this._shadowMap || !this._shadowMap.renderList) {
  70331. return this;
  70332. }
  70333. var index = this._shadowMap.renderList.indexOf(mesh);
  70334. if (index !== -1) {
  70335. this._shadowMap.renderList.splice(index, 1);
  70336. }
  70337. if (includeDescendants) {
  70338. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  70339. var child = _a[_i];
  70340. this.removeShadowCaster(child);
  70341. }
  70342. }
  70343. return this;
  70344. };
  70345. /**
  70346. * Returns the associated light object.
  70347. * @returns the light generating the shadow
  70348. */
  70349. ShadowGenerator.prototype.getLight = function () {
  70350. return this._light;
  70351. };
  70352. ShadowGenerator.prototype._initializeGenerator = function () {
  70353. this._light._markMeshesAsLightDirty();
  70354. this._initializeShadowMap();
  70355. };
  70356. ShadowGenerator.prototype._initializeShadowMap = function () {
  70357. var _this = this;
  70358. // Render target
  70359. var engine = this._scene.getEngine();
  70360. if (engine.webGLVersion > 1) {
  70361. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  70362. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  70363. }
  70364. else {
  70365. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  70366. }
  70367. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70368. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70369. this._shadowMap.anisotropicFilteringLevel = 1;
  70370. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70371. this._shadowMap.renderParticles = false;
  70372. this._shadowMap.ignoreCameraViewport = true;
  70373. // Record Face Index before render.
  70374. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  70375. _this._currentFaceIndex = faceIndex;
  70376. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70377. engine.setColorWrite(false);
  70378. }
  70379. });
  70380. // Custom render function.
  70381. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  70382. // Blur if required afer render.
  70383. this._shadowMap.onAfterUnbindObservable.add(function () {
  70384. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70385. engine.setColorWrite(true);
  70386. }
  70387. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  70388. return;
  70389. }
  70390. var shadowMap = _this.getShadowMapForRendering();
  70391. if (shadowMap) {
  70392. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  70393. }
  70394. });
  70395. // Clear according to the chosen filter.
  70396. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  70397. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  70398. this._shadowMap.onClearObservable.add(function (engine) {
  70399. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70400. engine.clear(clearOne, false, true, false);
  70401. }
  70402. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  70403. engine.clear(clearZero, true, true, false);
  70404. }
  70405. else {
  70406. engine.clear(clearOne, true, true, false);
  70407. }
  70408. });
  70409. };
  70410. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  70411. var _this = this;
  70412. var engine = this._scene.getEngine();
  70413. var targetSize = this._mapSize / this.blurScale;
  70414. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  70415. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  70416. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70417. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70418. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70419. }
  70420. if (this.useKernelBlur) {
  70421. 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);
  70422. this._kernelBlurXPostprocess.width = targetSize;
  70423. this._kernelBlurXPostprocess.height = targetSize;
  70424. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  70425. effect.setTexture("textureSampler", _this._shadowMap);
  70426. });
  70427. 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);
  70428. this._kernelBlurXPostprocess.autoClear = false;
  70429. this._kernelBlurYPostprocess.autoClear = false;
  70430. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70431. this._kernelBlurXPostprocess.packedFloat = true;
  70432. this._kernelBlurYPostprocess.packedFloat = true;
  70433. }
  70434. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  70435. }
  70436. else {
  70437. 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);
  70438. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  70439. effect.setFloat2("screenSize", targetSize, targetSize);
  70440. effect.setTexture("textureSampler", _this._shadowMap);
  70441. });
  70442. this._boxBlurPostprocess.autoClear = false;
  70443. this._blurPostProcesses = [this._boxBlurPostprocess];
  70444. }
  70445. };
  70446. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70447. var index;
  70448. var engine = this._scene.getEngine();
  70449. if (depthOnlySubMeshes.length) {
  70450. engine.setColorWrite(false);
  70451. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70452. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  70453. }
  70454. engine.setColorWrite(true);
  70455. }
  70456. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70457. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  70458. }
  70459. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70460. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  70461. }
  70462. if (this._transparencyShadow) {
  70463. for (index = 0; index < transparentSubMeshes.length; index++) {
  70464. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  70465. }
  70466. }
  70467. };
  70468. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  70469. var _this = this;
  70470. var mesh = subMesh.getRenderingMesh();
  70471. var scene = this._scene;
  70472. var engine = scene.getEngine();
  70473. var material = subMesh.getMaterial();
  70474. if (!material) {
  70475. return;
  70476. }
  70477. // Culling
  70478. engine.setState(material.backFaceCulling);
  70479. // Managing instances
  70480. var batch = mesh._getInstancesRenderList(subMesh._id);
  70481. if (batch.mustReturn) {
  70482. return;
  70483. }
  70484. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70485. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  70486. engine.enableEffect(this._effect);
  70487. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70488. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  70489. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  70490. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70491. this._effect.setVector3("lightData", this._cachedDirection);
  70492. }
  70493. else {
  70494. this._effect.setVector3("lightData", this._cachedPosition);
  70495. }
  70496. if (scene.activeCamera) {
  70497. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  70498. }
  70499. // Alpha test
  70500. if (material && material.needAlphaTesting()) {
  70501. var alphaTexture = material.getAlphaTestTexture();
  70502. if (alphaTexture) {
  70503. this._effect.setTexture("diffuseSampler", alphaTexture);
  70504. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  70505. }
  70506. }
  70507. // Bones
  70508. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70509. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  70510. }
  70511. // Morph targets
  70512. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  70513. if (this.forceBackFacesOnly) {
  70514. engine.setState(true, 0, false, true);
  70515. }
  70516. // Draw
  70517. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70518. if (this.forceBackFacesOnly) {
  70519. engine.setState(true, 0, false, false);
  70520. }
  70521. }
  70522. else {
  70523. // Need to reset refresh rate of the shadowMap
  70524. if (this._shadowMap) {
  70525. this._shadowMap.resetRefreshCounter();
  70526. }
  70527. }
  70528. };
  70529. ShadowGenerator.prototype._applyFilterValues = function () {
  70530. if (!this._shadowMap) {
  70531. return;
  70532. }
  70533. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  70534. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  70535. }
  70536. else {
  70537. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70538. }
  70539. };
  70540. /**
  70541. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70542. * @param onCompiled Callback triggered at the and of the effects compilation
  70543. * @param options Sets of optional options forcing the compilation with different modes
  70544. */
  70545. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  70546. var _this = this;
  70547. var localOptions = __assign({ useInstances: false }, options);
  70548. var shadowMap = this.getShadowMap();
  70549. if (!shadowMap) {
  70550. if (onCompiled) {
  70551. onCompiled(this);
  70552. }
  70553. return;
  70554. }
  70555. var renderList = shadowMap.renderList;
  70556. if (!renderList) {
  70557. if (onCompiled) {
  70558. onCompiled(this);
  70559. }
  70560. return;
  70561. }
  70562. var subMeshes = new Array();
  70563. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  70564. var mesh = renderList_1[_i];
  70565. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  70566. }
  70567. if (subMeshes.length === 0) {
  70568. if (onCompiled) {
  70569. onCompiled(this);
  70570. }
  70571. return;
  70572. }
  70573. var currentIndex = 0;
  70574. var checkReady = function () {
  70575. if (!_this._scene || !_this._scene.getEngine()) {
  70576. return;
  70577. }
  70578. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  70579. currentIndex++;
  70580. if (currentIndex >= subMeshes.length) {
  70581. if (onCompiled) {
  70582. onCompiled(_this);
  70583. }
  70584. return;
  70585. }
  70586. }
  70587. setTimeout(checkReady, 16);
  70588. };
  70589. checkReady();
  70590. };
  70591. /**
  70592. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70593. * @param options Sets of optional options forcing the compilation with different modes
  70594. * @returns A promise that resolves when the compilation completes
  70595. */
  70596. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  70597. var _this = this;
  70598. return new Promise(function (resolve) {
  70599. _this.forceCompilation(function () {
  70600. resolve();
  70601. }, options);
  70602. });
  70603. };
  70604. /**
  70605. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  70606. * @param subMesh The submesh we want to render in the shadow map
  70607. * @param useInstances Defines wether will draw in the map using instances
  70608. * @returns true if ready otherwise, false
  70609. */
  70610. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  70611. var defines = [];
  70612. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70613. defines.push("#define FLOAT");
  70614. }
  70615. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70616. defines.push("#define ESM");
  70617. }
  70618. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  70619. defines.push("#define DEPTHTEXTURE");
  70620. }
  70621. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70622. var mesh = subMesh.getMesh();
  70623. var material = subMesh.getMaterial();
  70624. // Normal bias.
  70625. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70626. attribs.push(BABYLON.VertexBuffer.NormalKind);
  70627. defines.push("#define NORMAL");
  70628. if (mesh.nonUniformScaling) {
  70629. defines.push("#define NONUNIFORMSCALING");
  70630. }
  70631. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70632. defines.push("#define DIRECTIONINLIGHTDATA");
  70633. }
  70634. }
  70635. // Alpha test
  70636. if (material && material.needAlphaTesting()) {
  70637. var alphaTexture = material.getAlphaTestTexture();
  70638. if (alphaTexture) {
  70639. defines.push("#define ALPHATEST");
  70640. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70641. attribs.push(BABYLON.VertexBuffer.UVKind);
  70642. defines.push("#define UV1");
  70643. }
  70644. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70645. if (alphaTexture.coordinatesIndex === 1) {
  70646. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70647. defines.push("#define UV2");
  70648. }
  70649. }
  70650. }
  70651. }
  70652. // Bones
  70653. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70654. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70655. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70656. if (mesh.numBoneInfluencers > 4) {
  70657. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70658. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70659. }
  70660. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70661. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70662. }
  70663. else {
  70664. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70665. }
  70666. // Morph targets
  70667. var manager = mesh.morphTargetManager;
  70668. var morphInfluencers = 0;
  70669. if (manager) {
  70670. if (manager.numInfluencers > 0) {
  70671. defines.push("#define MORPHTARGETS");
  70672. morphInfluencers = manager.numInfluencers;
  70673. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  70674. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  70675. }
  70676. }
  70677. // Instances
  70678. if (useInstances) {
  70679. defines.push("#define INSTANCES");
  70680. attribs.push("world0");
  70681. attribs.push("world1");
  70682. attribs.push("world2");
  70683. attribs.push("world3");
  70684. }
  70685. // Get correct effect
  70686. var join = defines.join("\n");
  70687. if (this._cachedDefines !== join) {
  70688. this._cachedDefines = join;
  70689. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  70690. }
  70691. if (!this._effect.isReady()) {
  70692. return false;
  70693. }
  70694. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70695. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  70696. this._initializeBlurRTTAndPostProcesses();
  70697. }
  70698. }
  70699. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  70700. return false;
  70701. }
  70702. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  70703. return false;
  70704. }
  70705. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  70706. return false;
  70707. }
  70708. return true;
  70709. };
  70710. /**
  70711. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  70712. * @param defines Defines of the material we want to update
  70713. * @param lightIndex Index of the light in the enabled light list of the material
  70714. */
  70715. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  70716. var scene = this._scene;
  70717. var light = this._light;
  70718. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70719. return;
  70720. }
  70721. defines["SHADOW" + lightIndex] = true;
  70722. if (this.useContactHardeningShadow) {
  70723. defines["SHADOWPCSS" + lightIndex] = true;
  70724. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70725. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70726. }
  70727. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70728. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70729. }
  70730. // else default to high.
  70731. }
  70732. if (this.usePercentageCloserFiltering) {
  70733. defines["SHADOWPCF" + lightIndex] = true;
  70734. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70735. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70736. }
  70737. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70738. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70739. }
  70740. // else default to high.
  70741. }
  70742. else if (this.usePoissonSampling) {
  70743. defines["SHADOWPOISSON" + lightIndex] = true;
  70744. }
  70745. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70746. defines["SHADOWESM" + lightIndex] = true;
  70747. }
  70748. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70749. defines["SHADOWCLOSEESM" + lightIndex] = true;
  70750. }
  70751. if (light.needCube()) {
  70752. defines["SHADOWCUBE" + lightIndex] = true;
  70753. }
  70754. };
  70755. /**
  70756. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  70757. * defined in the generator but impacting the effect).
  70758. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  70759. * @param effect The effect we are binfing the information for
  70760. */
  70761. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  70762. var light = this._light;
  70763. var scene = this._scene;
  70764. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70765. return;
  70766. }
  70767. var camera = scene.activeCamera;
  70768. if (!camera) {
  70769. return;
  70770. }
  70771. var shadowMap = this.getShadowMap();
  70772. if (!shadowMap) {
  70773. return;
  70774. }
  70775. if (!light.needCube()) {
  70776. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  70777. }
  70778. // Only PCF uses depth stencil texture.
  70779. if (this._filter === ShadowGenerator.FILTER_PCF) {
  70780. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70781. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70782. }
  70783. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  70784. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70785. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  70786. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70787. }
  70788. else {
  70789. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70790. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  70791. }
  70792. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  70793. };
  70794. /**
  70795. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  70796. * (eq to shadow prjection matrix * light transform matrix)
  70797. * @returns The transform matrix used to create the shadow map
  70798. */
  70799. ShadowGenerator.prototype.getTransformMatrix = function () {
  70800. var scene = this._scene;
  70801. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  70802. return this._transformMatrix;
  70803. }
  70804. this._currentRenderID = scene.getRenderId();
  70805. this._currentFaceIndexCache = this._currentFaceIndex;
  70806. var lightPosition = this._light.position;
  70807. if (this._light.computeTransformedInformation()) {
  70808. lightPosition = this._light.transformedPosition;
  70809. }
  70810. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  70811. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  70812. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  70813. }
  70814. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  70815. this._cachedPosition.copyFrom(lightPosition);
  70816. this._cachedDirection.copyFrom(this._lightDirection);
  70817. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  70818. var shadowMap = this.getShadowMap();
  70819. if (shadowMap) {
  70820. var renderList = shadowMap.renderList;
  70821. if (renderList) {
  70822. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  70823. }
  70824. }
  70825. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  70826. }
  70827. return this._transformMatrix;
  70828. };
  70829. /**
  70830. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  70831. * Cube and 2D textures for instance.
  70832. */
  70833. ShadowGenerator.prototype.recreateShadowMap = function () {
  70834. var shadowMap = this._shadowMap;
  70835. if (!shadowMap) {
  70836. return;
  70837. }
  70838. // Track render list.
  70839. var renderList = shadowMap.renderList;
  70840. // Clean up existing data.
  70841. this._disposeRTTandPostProcesses();
  70842. // Reinitializes.
  70843. this._initializeGenerator();
  70844. // Reaffect the filter to ensure a correct fallback if necessary.
  70845. this.filter = this.filter;
  70846. // Reaffect the filter.
  70847. this._applyFilterValues();
  70848. // Reaffect Render List.
  70849. this._shadowMap.renderList = renderList;
  70850. };
  70851. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  70852. if (this._shadowMap2) {
  70853. this._shadowMap2.dispose();
  70854. this._shadowMap2 = null;
  70855. }
  70856. if (this._boxBlurPostprocess) {
  70857. this._boxBlurPostprocess.dispose();
  70858. this._boxBlurPostprocess = null;
  70859. }
  70860. if (this._kernelBlurXPostprocess) {
  70861. this._kernelBlurXPostprocess.dispose();
  70862. this._kernelBlurXPostprocess = null;
  70863. }
  70864. if (this._kernelBlurYPostprocess) {
  70865. this._kernelBlurYPostprocess.dispose();
  70866. this._kernelBlurYPostprocess = null;
  70867. }
  70868. this._blurPostProcesses = [];
  70869. };
  70870. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  70871. if (this._shadowMap) {
  70872. this._shadowMap.dispose();
  70873. this._shadowMap = null;
  70874. }
  70875. this._disposeBlurPostProcesses();
  70876. };
  70877. /**
  70878. * Disposes the ShadowGenerator.
  70879. * Returns nothing.
  70880. */
  70881. ShadowGenerator.prototype.dispose = function () {
  70882. this._disposeRTTandPostProcesses();
  70883. if (this._light) {
  70884. this._light._shadowGenerator = null;
  70885. this._light._markMeshesAsLightDirty();
  70886. }
  70887. };
  70888. /**
  70889. * Serializes the shadow generator setup to a json object.
  70890. * @returns The serialized JSON object
  70891. */
  70892. ShadowGenerator.prototype.serialize = function () {
  70893. var serializationObject = {};
  70894. var shadowMap = this.getShadowMap();
  70895. if (!shadowMap) {
  70896. return serializationObject;
  70897. }
  70898. serializationObject.lightId = this._light.id;
  70899. serializationObject.mapSize = shadowMap.getRenderSize();
  70900. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  70901. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  70902. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70903. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70904. serializationObject.usePoissonSampling = this.usePoissonSampling;
  70905. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  70906. serializationObject.depthScale = this.depthScale;
  70907. serializationObject.darkness = this.getDarkness();
  70908. serializationObject.blurBoxOffset = this.blurBoxOffset;
  70909. serializationObject.blurKernel = this.blurKernel;
  70910. serializationObject.blurScale = this.blurScale;
  70911. serializationObject.useKernelBlur = this.useKernelBlur;
  70912. serializationObject.transparencyShadow = this._transparencyShadow;
  70913. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70914. serializationObject.bias = this.bias;
  70915. serializationObject.normalBias = this.normalBias;
  70916. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70917. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70918. serializationObject.filteringQuality = this.filteringQuality;
  70919. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  70920. serializationObject.renderList = [];
  70921. if (shadowMap.renderList) {
  70922. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  70923. var mesh = shadowMap.renderList[meshIndex];
  70924. serializationObject.renderList.push(mesh.id);
  70925. }
  70926. }
  70927. return serializationObject;
  70928. };
  70929. /**
  70930. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  70931. * @param parsedShadowGenerator The JSON object to parse
  70932. * @param scene The scene to create the shadow map for
  70933. * @returns The parsed shadow generator
  70934. */
  70935. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  70936. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  70937. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  70938. var shadowMap = shadowGenerator.getShadowMap();
  70939. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  70940. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  70941. meshes.forEach(function (mesh) {
  70942. if (!shadowMap) {
  70943. return;
  70944. }
  70945. if (!shadowMap.renderList) {
  70946. shadowMap.renderList = [];
  70947. }
  70948. shadowMap.renderList.push(mesh);
  70949. });
  70950. }
  70951. if (parsedShadowGenerator.usePoissonSampling) {
  70952. shadowGenerator.usePoissonSampling = true;
  70953. }
  70954. else if (parsedShadowGenerator.useExponentialShadowMap) {
  70955. shadowGenerator.useExponentialShadowMap = true;
  70956. }
  70957. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  70958. shadowGenerator.useBlurExponentialShadowMap = true;
  70959. }
  70960. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  70961. shadowGenerator.useCloseExponentialShadowMap = true;
  70962. }
  70963. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  70964. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  70965. }
  70966. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  70967. shadowGenerator.usePercentageCloserFiltering = true;
  70968. }
  70969. else if (parsedShadowGenerator.useContactHardeningShadow) {
  70970. shadowGenerator.useContactHardeningShadow = true;
  70971. }
  70972. if (parsedShadowGenerator.filteringQuality) {
  70973. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  70974. }
  70975. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  70976. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  70977. }
  70978. // Backward compat
  70979. else if (parsedShadowGenerator.useVarianceShadowMap) {
  70980. shadowGenerator.useExponentialShadowMap = true;
  70981. }
  70982. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  70983. shadowGenerator.useBlurExponentialShadowMap = true;
  70984. }
  70985. if (parsedShadowGenerator.depthScale) {
  70986. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  70987. }
  70988. if (parsedShadowGenerator.blurScale) {
  70989. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  70990. }
  70991. if (parsedShadowGenerator.blurBoxOffset) {
  70992. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  70993. }
  70994. if (parsedShadowGenerator.useKernelBlur) {
  70995. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  70996. }
  70997. if (parsedShadowGenerator.blurKernel) {
  70998. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  70999. }
  71000. if (parsedShadowGenerator.bias !== undefined) {
  71001. shadowGenerator.bias = parsedShadowGenerator.bias;
  71002. }
  71003. if (parsedShadowGenerator.normalBias !== undefined) {
  71004. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  71005. }
  71006. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  71007. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  71008. }
  71009. if (parsedShadowGenerator.darkness) {
  71010. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  71011. }
  71012. if (parsedShadowGenerator.transparencyShadow) {
  71013. shadowGenerator.setTransparencyShadow(true);
  71014. }
  71015. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  71016. return shadowGenerator;
  71017. };
  71018. /**
  71019. * Shadow generator mode None: no filtering applied.
  71020. */
  71021. ShadowGenerator.FILTER_NONE = 0;
  71022. /**
  71023. * Shadow generator mode ESM: Exponential Shadow Mapping.
  71024. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71025. */
  71026. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  71027. /**
  71028. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  71029. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  71030. */
  71031. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  71032. /**
  71033. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  71034. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71035. */
  71036. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  71037. /**
  71038. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  71039. * edge artifacts on steep falloff.
  71040. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71041. */
  71042. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  71043. /**
  71044. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  71045. * edge artifacts on steep falloff.
  71046. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71047. */
  71048. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  71049. /**
  71050. * Shadow generator mode PCF: Percentage Closer Filtering
  71051. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71052. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  71053. */
  71054. ShadowGenerator.FILTER_PCF = 6;
  71055. /**
  71056. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  71057. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71058. * Contact Hardening
  71059. */
  71060. ShadowGenerator.FILTER_PCSS = 7;
  71061. /**
  71062. * Reserved for PCF and PCSS
  71063. * Highest Quality.
  71064. *
  71065. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  71066. *
  71067. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  71068. */
  71069. ShadowGenerator.QUALITY_HIGH = 0;
  71070. /**
  71071. * Reserved for PCF and PCSS
  71072. * Good tradeoff for quality/perf cross devices
  71073. *
  71074. * Execute PCF on a 3*3 kernel.
  71075. *
  71076. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  71077. */
  71078. ShadowGenerator.QUALITY_MEDIUM = 1;
  71079. /**
  71080. * Reserved for PCF and PCSS
  71081. * The lowest quality but the fastest.
  71082. *
  71083. * Execute PCF on a 1*1 kernel.
  71084. *
  71085. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  71086. */
  71087. ShadowGenerator.QUALITY_LOW = 2;
  71088. return ShadowGenerator;
  71089. }());
  71090. BABYLON.ShadowGenerator = ShadowGenerator;
  71091. })(BABYLON || (BABYLON = {}));
  71092. //# sourceMappingURL=babylon.shadowGenerator.js.map
  71093. var BABYLON;
  71094. (function (BABYLON) {
  71095. // Adds the parser to the scene parsers.
  71096. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  71097. // Shadows
  71098. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71099. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71100. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71101. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71102. // SG would be available on their associated lights
  71103. }
  71104. }
  71105. });
  71106. /**
  71107. * Defines the shadow generator component responsible to manage any shadow generators
  71108. * in a given scene.
  71109. */
  71110. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  71111. /**
  71112. * Creates a new instance of the component for the given scene
  71113. * @param scene Defines the scene to register the component in
  71114. */
  71115. function ShadowGeneratorSceneComponent(scene) {
  71116. /**
  71117. * The component name helpfull to identify the component in the list of scene components.
  71118. */
  71119. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  71120. this.scene = scene;
  71121. }
  71122. /**
  71123. * Registers the component in a given scene
  71124. */
  71125. ShadowGeneratorSceneComponent.prototype.register = function () {
  71126. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  71127. };
  71128. /**
  71129. * Rebuilds the elements related to this component in case of
  71130. * context lost for instance.
  71131. */
  71132. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  71133. // Nothing To Do Here.
  71134. };
  71135. /**
  71136. * Serializes the component data to the specified json object
  71137. * @param serializationObject The object to serialize to
  71138. */
  71139. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  71140. // Shadows
  71141. serializationObject.shadowGenerators = [];
  71142. var lights = this.scene.lights;
  71143. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  71144. var light = lights_1[_i];
  71145. var shadowGenerator = light.getShadowGenerator();
  71146. if (shadowGenerator) {
  71147. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71148. }
  71149. }
  71150. };
  71151. /**
  71152. * Adds all the element from the container to the scene
  71153. * @param container the container holding the elements
  71154. */
  71155. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  71156. // Nothing To Do Here. (directly attached to a light)
  71157. };
  71158. /**
  71159. * Removes all the elements in the container from the scene
  71160. * @param container contains the elements to remove
  71161. */
  71162. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  71163. // Nothing To Do Here. (directly attached to a light)
  71164. };
  71165. /**
  71166. * Rebuilds the elements related to this component in case of
  71167. * context lost for instance.
  71168. */
  71169. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  71170. // Nothing To Do Here.
  71171. };
  71172. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  71173. // Shadows
  71174. var scene = this.scene;
  71175. if (this.scene.shadowsEnabled) {
  71176. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  71177. var light = scene.lights[lightIndex];
  71178. var shadowGenerator = light.getShadowGenerator();
  71179. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  71180. var shadowMap = (shadowGenerator.getShadowMap());
  71181. if (scene.textures.indexOf(shadowMap) !== -1) {
  71182. renderTargets.push(shadowMap);
  71183. }
  71184. }
  71185. }
  71186. }
  71187. };
  71188. return ShadowGeneratorSceneComponent;
  71189. }());
  71190. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  71191. })(BABYLON || (BABYLON = {}));
  71192. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  71193. var BABYLON;
  71194. (function (BABYLON) {
  71195. var DefaultLoadingScreen = /** @class */ (function () {
  71196. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  71197. if (_loadingText === void 0) { _loadingText = ""; }
  71198. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  71199. var _this = this;
  71200. this._renderingCanvas = _renderingCanvas;
  71201. this._loadingText = _loadingText;
  71202. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  71203. // Resize
  71204. this._resizeLoadingUI = function () {
  71205. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  71206. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  71207. if (!_this._loadingDiv) {
  71208. return;
  71209. }
  71210. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  71211. _this._loadingDiv.style.left = canvasRect.left + "px";
  71212. _this._loadingDiv.style.top = canvasRect.top + "px";
  71213. _this._loadingDiv.style.width = canvasRect.width + "px";
  71214. _this._loadingDiv.style.height = canvasRect.height + "px";
  71215. };
  71216. }
  71217. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  71218. if (this._loadingDiv) {
  71219. // Do not add a loading screen if there is already one
  71220. return;
  71221. }
  71222. this._loadingDiv = document.createElement("div");
  71223. this._loadingDiv.id = "babylonjsLoadingDiv";
  71224. this._loadingDiv.style.opacity = "0";
  71225. this._loadingDiv.style.transition = "opacity 1.5s ease";
  71226. this._loadingDiv.style.pointerEvents = "none";
  71227. // Loading text
  71228. this._loadingTextDiv = document.createElement("div");
  71229. this._loadingTextDiv.style.position = "absolute";
  71230. this._loadingTextDiv.style.left = "0";
  71231. this._loadingTextDiv.style.top = "50%";
  71232. this._loadingTextDiv.style.marginTop = "80px";
  71233. this._loadingTextDiv.style.width = "100%";
  71234. this._loadingTextDiv.style.height = "20px";
  71235. this._loadingTextDiv.style.fontFamily = "Arial";
  71236. this._loadingTextDiv.style.fontSize = "14px";
  71237. this._loadingTextDiv.style.color = "white";
  71238. this._loadingTextDiv.style.textAlign = "center";
  71239. this._loadingTextDiv.innerHTML = "Loading";
  71240. this._loadingDiv.appendChild(this._loadingTextDiv);
  71241. //set the predefined text
  71242. this._loadingTextDiv.innerHTML = this._loadingText;
  71243. // Generating keyframes
  71244. var style = document.createElement('style');
  71245. style.type = 'text/css';
  71246. 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 }";
  71247. style.innerHTML = keyFrames;
  71248. document.getElementsByTagName('head')[0].appendChild(style);
  71249. // Loading img
  71250. var imgBack = new Image();
  71251. 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";
  71252. imgBack.style.position = "absolute";
  71253. imgBack.style.left = "50%";
  71254. imgBack.style.top = "50%";
  71255. imgBack.style.marginLeft = "-60px";
  71256. imgBack.style.marginTop = "-60px";
  71257. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  71258. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  71259. imgBack.style.transformOrigin = "50% 50%";
  71260. imgBack.style.webkitTransformOrigin = "50% 50%";
  71261. this._loadingDiv.appendChild(imgBack);
  71262. this._resizeLoadingUI();
  71263. window.addEventListener("resize", this._resizeLoadingUI);
  71264. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71265. document.body.appendChild(this._loadingDiv);
  71266. this._loadingDiv.style.opacity = "1";
  71267. };
  71268. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  71269. var _this = this;
  71270. if (!this._loadingDiv) {
  71271. return;
  71272. }
  71273. var onTransitionEnd = function () {
  71274. if (!_this._loadingDiv) {
  71275. return;
  71276. }
  71277. document.body.removeChild(_this._loadingDiv);
  71278. window.removeEventListener("resize", _this._resizeLoadingUI);
  71279. _this._loadingDiv = null;
  71280. };
  71281. this._loadingDiv.style.opacity = "0";
  71282. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  71283. };
  71284. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  71285. set: function (text) {
  71286. this._loadingText = text;
  71287. if (this._loadingTextDiv) {
  71288. this._loadingTextDiv.innerHTML = this._loadingText;
  71289. }
  71290. },
  71291. enumerable: true,
  71292. configurable: true
  71293. });
  71294. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  71295. get: function () {
  71296. return this._loadingDivBackgroundColor;
  71297. },
  71298. set: function (color) {
  71299. this._loadingDivBackgroundColor = color;
  71300. if (!this._loadingDiv) {
  71301. return;
  71302. }
  71303. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71304. },
  71305. enumerable: true,
  71306. configurable: true
  71307. });
  71308. return DefaultLoadingScreen;
  71309. }());
  71310. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  71311. })(BABYLON || (BABYLON = {}));
  71312. //# sourceMappingURL=babylon.loadingScreen.js.map
  71313. var BABYLON;
  71314. (function (BABYLON) {
  71315. var SceneLoaderProgressEvent = /** @class */ (function () {
  71316. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  71317. this.lengthComputable = lengthComputable;
  71318. this.loaded = loaded;
  71319. this.total = total;
  71320. }
  71321. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  71322. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  71323. };
  71324. return SceneLoaderProgressEvent;
  71325. }());
  71326. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  71327. var SceneLoader = /** @class */ (function () {
  71328. function SceneLoader() {
  71329. }
  71330. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  71331. get: function () {
  71332. return 0;
  71333. },
  71334. enumerable: true,
  71335. configurable: true
  71336. });
  71337. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  71338. get: function () {
  71339. return 1;
  71340. },
  71341. enumerable: true,
  71342. configurable: true
  71343. });
  71344. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  71345. get: function () {
  71346. return 2;
  71347. },
  71348. enumerable: true,
  71349. configurable: true
  71350. });
  71351. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  71352. get: function () {
  71353. return 3;
  71354. },
  71355. enumerable: true,
  71356. configurable: true
  71357. });
  71358. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  71359. get: function () {
  71360. return SceneLoader._ForceFullSceneLoadingForIncremental;
  71361. },
  71362. set: function (value) {
  71363. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  71364. },
  71365. enumerable: true,
  71366. configurable: true
  71367. });
  71368. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  71369. get: function () {
  71370. return SceneLoader._ShowLoadingScreen;
  71371. },
  71372. set: function (value) {
  71373. SceneLoader._ShowLoadingScreen = value;
  71374. },
  71375. enumerable: true,
  71376. configurable: true
  71377. });
  71378. Object.defineProperty(SceneLoader, "loggingLevel", {
  71379. get: function () {
  71380. return SceneLoader._loggingLevel;
  71381. },
  71382. set: function (value) {
  71383. SceneLoader._loggingLevel = value;
  71384. },
  71385. enumerable: true,
  71386. configurable: true
  71387. });
  71388. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  71389. get: function () {
  71390. return SceneLoader._CleanBoneMatrixWeights;
  71391. },
  71392. set: function (value) {
  71393. SceneLoader._CleanBoneMatrixWeights = value;
  71394. },
  71395. enumerable: true,
  71396. configurable: true
  71397. });
  71398. SceneLoader._getDefaultPlugin = function () {
  71399. return SceneLoader._registeredPlugins[".babylon"];
  71400. };
  71401. SceneLoader._getPluginForExtension = function (extension) {
  71402. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  71403. if (registeredPlugin) {
  71404. return registeredPlugin;
  71405. }
  71406. 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");
  71407. return SceneLoader._getDefaultPlugin();
  71408. };
  71409. SceneLoader._getPluginForDirectLoad = function (data) {
  71410. for (var extension in SceneLoader._registeredPlugins) {
  71411. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  71412. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  71413. return SceneLoader._registeredPlugins[extension];
  71414. }
  71415. }
  71416. return SceneLoader._getDefaultPlugin();
  71417. };
  71418. SceneLoader._getPluginForFilename = function (sceneFilename) {
  71419. if (sceneFilename.name) {
  71420. sceneFilename = sceneFilename.name;
  71421. }
  71422. var queryStringPosition = sceneFilename.indexOf("?");
  71423. if (queryStringPosition !== -1) {
  71424. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  71425. }
  71426. var dotPosition = sceneFilename.lastIndexOf(".");
  71427. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  71428. return SceneLoader._getPluginForExtension(extension);
  71429. };
  71430. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  71431. SceneLoader._getDirectLoad = function (sceneFilename) {
  71432. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  71433. return sceneFilename.substr(5);
  71434. }
  71435. return null;
  71436. };
  71437. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  71438. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  71439. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  71440. var plugin;
  71441. if (registeredPlugin.plugin.createPlugin) {
  71442. plugin = registeredPlugin.plugin.createPlugin();
  71443. }
  71444. else {
  71445. plugin = registeredPlugin.plugin;
  71446. }
  71447. var useArrayBuffer = registeredPlugin.isBinary;
  71448. var database;
  71449. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  71450. var dataCallback = function (data, responseURL) {
  71451. if (scene.isDisposed) {
  71452. onError("Scene has been disposed");
  71453. return;
  71454. }
  71455. scene.database = database;
  71456. onSuccess(plugin, data, responseURL);
  71457. };
  71458. var request = null;
  71459. var pluginDisposed = false;
  71460. var onDisposeObservable = plugin.onDisposeObservable;
  71461. if (onDisposeObservable) {
  71462. onDisposeObservable.add(function () {
  71463. pluginDisposed = true;
  71464. if (request) {
  71465. request.abort();
  71466. request = null;
  71467. }
  71468. onDispose();
  71469. });
  71470. }
  71471. var manifestChecked = function () {
  71472. if (pluginDisposed) {
  71473. return;
  71474. }
  71475. var url = rootUrl + sceneFilename;
  71476. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  71477. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  71478. } : undefined, database, useArrayBuffer, function (request, exception) {
  71479. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  71480. });
  71481. };
  71482. if (directLoad) {
  71483. dataCallback(directLoad);
  71484. return plugin;
  71485. }
  71486. if (rootUrl.indexOf("file:") === -1) {
  71487. var engine = scene.getEngine();
  71488. var canUseOfflineSupport = engine.enableOfflineSupport;
  71489. if (canUseOfflineSupport) {
  71490. // Also check for exceptions
  71491. var exceptionFound = false;
  71492. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  71493. var regex = _a[_i];
  71494. if (regex.test(rootUrl + sceneFilename)) {
  71495. exceptionFound = true;
  71496. break;
  71497. }
  71498. }
  71499. canUseOfflineSupport = !exceptionFound;
  71500. }
  71501. if (canUseOfflineSupport) {
  71502. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  71503. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  71504. }
  71505. else {
  71506. manifestChecked();
  71507. }
  71508. }
  71509. // Loading file from disk via input file or drag'n'drop
  71510. else {
  71511. var fileOrString = sceneFilename;
  71512. if (fileOrString.name) { // File
  71513. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  71514. }
  71515. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  71516. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  71517. }
  71518. else {
  71519. onError("Unable to find file named " + sceneFilename);
  71520. }
  71521. }
  71522. return plugin;
  71523. };
  71524. // Public functions
  71525. SceneLoader.GetPluginForExtension = function (extension) {
  71526. return SceneLoader._getPluginForExtension(extension).plugin;
  71527. };
  71528. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  71529. return !!SceneLoader._registeredPlugins[extension];
  71530. };
  71531. SceneLoader.RegisterPlugin = function (plugin) {
  71532. if (typeof plugin.extensions === "string") {
  71533. var extension = plugin.extensions;
  71534. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71535. plugin: plugin,
  71536. isBinary: false
  71537. };
  71538. }
  71539. else {
  71540. var extensions = plugin.extensions;
  71541. Object.keys(extensions).forEach(function (extension) {
  71542. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71543. plugin: plugin,
  71544. isBinary: extensions[extension].isBinary
  71545. };
  71546. });
  71547. }
  71548. };
  71549. /**
  71550. * Import meshes into a scene
  71551. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71552. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71553. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71554. * @param scene the instance of BABYLON.Scene to append to
  71555. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  71556. * @param onProgress a callback with a progress event for each file being loaded
  71557. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71558. * @param pluginExtension the extension used to determine the plugin
  71559. * @returns The loaded plugin
  71560. */
  71561. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71562. if (sceneFilename === void 0) { sceneFilename = ""; }
  71563. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71564. if (onSuccess === void 0) { onSuccess = null; }
  71565. if (onProgress === void 0) { onProgress = null; }
  71566. if (onError === void 0) { onError = null; }
  71567. if (pluginExtension === void 0) { pluginExtension = null; }
  71568. if (!scene) {
  71569. BABYLON.Tools.Error("No scene available to import mesh to");
  71570. return null;
  71571. }
  71572. if (!sceneFilename) {
  71573. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71574. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71575. }
  71576. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71577. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71578. return null;
  71579. }
  71580. var loadingToken = {};
  71581. scene._addPendingData(loadingToken);
  71582. var disposeHandler = function () {
  71583. scene._removePendingData(loadingToken);
  71584. };
  71585. var errorHandler = function (message, exception) {
  71586. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  71587. if (onError) {
  71588. onError(scene, errorMessage, exception);
  71589. }
  71590. else {
  71591. BABYLON.Tools.Error(errorMessage);
  71592. // should the exception be thrown?
  71593. }
  71594. disposeHandler();
  71595. };
  71596. var progressHandler = onProgress ? function (event) {
  71597. try {
  71598. onProgress(event);
  71599. }
  71600. catch (e) {
  71601. errorHandler("Error in onProgress callback", e);
  71602. }
  71603. } : undefined;
  71604. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  71605. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  71606. if (onSuccess) {
  71607. try {
  71608. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  71609. }
  71610. catch (e) {
  71611. errorHandler("Error in onSuccess callback", e);
  71612. }
  71613. }
  71614. scene._removePendingData(loadingToken);
  71615. };
  71616. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71617. if (plugin.rewriteRootURL) {
  71618. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  71619. }
  71620. if (sceneFilename === "") {
  71621. if (sceneFilename === "") {
  71622. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71623. }
  71624. }
  71625. if (plugin.importMesh) {
  71626. var syncedPlugin = plugin;
  71627. var meshes = new Array();
  71628. var particleSystems = new Array();
  71629. var skeletons = new Array();
  71630. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  71631. return;
  71632. }
  71633. scene.loadingPluginName = plugin.name;
  71634. successHandler(meshes, particleSystems, skeletons, []);
  71635. }
  71636. else {
  71637. var asyncedPlugin = plugin;
  71638. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (result) {
  71639. scene.loadingPluginName = plugin.name;
  71640. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  71641. }).catch(function (error) {
  71642. errorHandler(error.message, error);
  71643. });
  71644. }
  71645. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71646. };
  71647. /**
  71648. * Import meshes into a scene
  71649. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71650. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71651. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71652. * @param scene the instance of BABYLON.Scene to append to
  71653. * @param onProgress a callback with a progress event for each file being loaded
  71654. * @param pluginExtension the extension used to determine the plugin
  71655. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  71656. */
  71657. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71658. if (sceneFilename === void 0) { sceneFilename = ""; }
  71659. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71660. if (onProgress === void 0) { onProgress = null; }
  71661. if (pluginExtension === void 0) { pluginExtension = null; }
  71662. return new Promise(function (resolve, reject) {
  71663. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  71664. resolve({
  71665. meshes: meshes,
  71666. particleSystems: particleSystems,
  71667. skeletons: skeletons,
  71668. animationGroups: animationGroups
  71669. });
  71670. }, onProgress, function (scene, message, exception) {
  71671. reject(exception || new Error(message));
  71672. }, pluginExtension);
  71673. });
  71674. };
  71675. /**
  71676. * Load a scene
  71677. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71678. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71679. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71680. * @param onSuccess a callback with the scene when import succeeds
  71681. * @param onProgress a callback with a progress event for each file being loaded
  71682. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71683. * @param pluginExtension the extension used to determine the plugin
  71684. * @returns The loaded plugin
  71685. */
  71686. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  71687. if (onSuccess === void 0) { onSuccess = null; }
  71688. if (onProgress === void 0) { onProgress = null; }
  71689. if (onError === void 0) { onError = null; }
  71690. if (pluginExtension === void 0) { pluginExtension = null; }
  71691. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  71692. };
  71693. /**
  71694. * Load a scene
  71695. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71696. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71697. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71698. * @param onProgress a callback with a progress event for each file being loaded
  71699. * @param pluginExtension the extension used to determine the plugin
  71700. * @returns The loaded scene
  71701. */
  71702. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  71703. if (onProgress === void 0) { onProgress = null; }
  71704. if (pluginExtension === void 0) { pluginExtension = null; }
  71705. return new Promise(function (resolve, reject) {
  71706. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  71707. resolve(scene);
  71708. }, onProgress, function (scene, message, exception) {
  71709. reject(exception || new Error(message));
  71710. }, pluginExtension);
  71711. });
  71712. };
  71713. /**
  71714. * Append a scene
  71715. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71716. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71717. * @param scene is the instance of BABYLON.Scene to append to
  71718. * @param onSuccess a callback with the scene when import succeeds
  71719. * @param onProgress a callback with a progress event for each file being loaded
  71720. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71721. * @param pluginExtension the extension used to determine the plugin
  71722. * @returns The loaded plugin
  71723. */
  71724. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71725. if (sceneFilename === void 0) { sceneFilename = ""; }
  71726. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71727. if (onSuccess === void 0) { onSuccess = null; }
  71728. if (onProgress === void 0) { onProgress = null; }
  71729. if (onError === void 0) { onError = null; }
  71730. if (pluginExtension === void 0) { pluginExtension = null; }
  71731. if (!scene) {
  71732. BABYLON.Tools.Error("No scene available to append to");
  71733. return null;
  71734. }
  71735. if (!sceneFilename) {
  71736. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71737. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71738. }
  71739. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71740. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71741. return null;
  71742. }
  71743. if (SceneLoader.ShowLoadingScreen) {
  71744. scene.getEngine().displayLoadingUI();
  71745. }
  71746. var loadingToken = {};
  71747. scene._addPendingData(loadingToken);
  71748. var disposeHandler = function () {
  71749. scene._removePendingData(loadingToken);
  71750. scene.getEngine().hideLoadingUI();
  71751. };
  71752. var errorHandler = function (message, exception) {
  71753. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71754. if (onError) {
  71755. onError(scene, errorMessage, exception);
  71756. }
  71757. else {
  71758. BABYLON.Tools.Error(errorMessage);
  71759. // should the exception be thrown?
  71760. }
  71761. disposeHandler();
  71762. };
  71763. var progressHandler = onProgress ? function (event) {
  71764. try {
  71765. onProgress(event);
  71766. }
  71767. catch (e) {
  71768. errorHandler("Error in onProgress callback", e);
  71769. }
  71770. } : undefined;
  71771. var successHandler = function () {
  71772. if (onSuccess) {
  71773. try {
  71774. onSuccess(scene);
  71775. }
  71776. catch (e) {
  71777. errorHandler("Error in onSuccess callback", e);
  71778. }
  71779. }
  71780. scene._removePendingData(loadingToken);
  71781. };
  71782. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71783. if (sceneFilename === "") {
  71784. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71785. }
  71786. if (plugin.load) {
  71787. var syncedPlugin = plugin;
  71788. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  71789. return;
  71790. }
  71791. scene.loadingPluginName = plugin.name;
  71792. successHandler();
  71793. }
  71794. else {
  71795. var asyncedPlugin = plugin;
  71796. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function () {
  71797. scene.loadingPluginName = plugin.name;
  71798. successHandler();
  71799. }).catch(function (error) {
  71800. errorHandler(error.message, error);
  71801. });
  71802. }
  71803. if (SceneLoader.ShowLoadingScreen) {
  71804. scene.executeWhenReady(function () {
  71805. scene.getEngine().hideLoadingUI();
  71806. });
  71807. }
  71808. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71809. };
  71810. /**
  71811. * Append a scene
  71812. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71813. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71814. * @param scene is the instance of BABYLON.Scene to append to
  71815. * @param onProgress a callback with a progress event for each file being loaded
  71816. * @param pluginExtension the extension used to determine the plugin
  71817. * @returns The given scene
  71818. */
  71819. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71820. if (sceneFilename === void 0) { sceneFilename = ""; }
  71821. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71822. if (onProgress === void 0) { onProgress = null; }
  71823. if (pluginExtension === void 0) { pluginExtension = null; }
  71824. return new Promise(function (resolve, reject) {
  71825. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  71826. resolve(scene);
  71827. }, onProgress, function (scene, message, exception) {
  71828. reject(exception || new Error(message));
  71829. }, pluginExtension);
  71830. });
  71831. };
  71832. /**
  71833. * Load a scene into an asset container
  71834. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71835. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71836. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  71837. * @param onSuccess a callback with the scene when import succeeds
  71838. * @param onProgress a callback with a progress event for each file being loaded
  71839. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71840. * @param pluginExtension the extension used to determine the plugin
  71841. * @returns The loaded plugin
  71842. */
  71843. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71844. if (sceneFilename === void 0) { sceneFilename = ""; }
  71845. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71846. if (onSuccess === void 0) { onSuccess = null; }
  71847. if (onProgress === void 0) { onProgress = null; }
  71848. if (onError === void 0) { onError = null; }
  71849. if (pluginExtension === void 0) { pluginExtension = null; }
  71850. if (!scene) {
  71851. BABYLON.Tools.Error("No scene available to load asset container to");
  71852. return null;
  71853. }
  71854. if (!sceneFilename) {
  71855. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71856. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71857. }
  71858. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71859. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71860. return null;
  71861. }
  71862. var loadingToken = {};
  71863. scene._addPendingData(loadingToken);
  71864. var disposeHandler = function () {
  71865. scene._removePendingData(loadingToken);
  71866. };
  71867. var errorHandler = function (message, exception) {
  71868. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71869. if (onError) {
  71870. onError(scene, errorMessage, exception);
  71871. }
  71872. else {
  71873. BABYLON.Tools.Error(errorMessage);
  71874. // should the exception be thrown?
  71875. }
  71876. disposeHandler();
  71877. };
  71878. var progressHandler = onProgress ? function (event) {
  71879. try {
  71880. onProgress(event);
  71881. }
  71882. catch (e) {
  71883. errorHandler("Error in onProgress callback", e);
  71884. }
  71885. } : undefined;
  71886. var successHandler = function (assets) {
  71887. if (onSuccess) {
  71888. try {
  71889. onSuccess(assets);
  71890. }
  71891. catch (e) {
  71892. errorHandler("Error in onSuccess callback", e);
  71893. }
  71894. }
  71895. scene._removePendingData(loadingToken);
  71896. };
  71897. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71898. if (plugin.loadAssetContainer) {
  71899. var syncedPlugin = plugin;
  71900. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  71901. if (!assetContainer) {
  71902. return;
  71903. }
  71904. scene.loadingPluginName = plugin.name;
  71905. successHandler(assetContainer);
  71906. }
  71907. else if (plugin.loadAssetContainerAsync) {
  71908. var asyncedPlugin = plugin;
  71909. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (assetContainer) {
  71910. scene.loadingPluginName = plugin.name;
  71911. successHandler(assetContainer);
  71912. }).catch(function (error) {
  71913. errorHandler(error.message, error);
  71914. });
  71915. }
  71916. else {
  71917. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  71918. }
  71919. if (SceneLoader.ShowLoadingScreen) {
  71920. scene.executeWhenReady(function () {
  71921. scene.getEngine().hideLoadingUI();
  71922. });
  71923. }
  71924. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71925. };
  71926. /**
  71927. * Load a scene into an asset container
  71928. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71929. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71930. * @param scene is the instance of BABYLON.Scene to append to
  71931. * @param onProgress a callback with a progress event for each file being loaded
  71932. * @param pluginExtension the extension used to determine the plugin
  71933. * @returns The loaded asset container
  71934. */
  71935. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71936. if (sceneFilename === void 0) { sceneFilename = ""; }
  71937. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71938. if (onProgress === void 0) { onProgress = null; }
  71939. if (pluginExtension === void 0) { pluginExtension = null; }
  71940. return new Promise(function (resolve, reject) {
  71941. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  71942. resolve(assetContainer);
  71943. }, onProgress, function (scene, message, exception) {
  71944. reject(exception || new Error(message));
  71945. }, pluginExtension);
  71946. });
  71947. };
  71948. // Flags
  71949. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  71950. SceneLoader._ShowLoadingScreen = true;
  71951. SceneLoader._CleanBoneMatrixWeights = false;
  71952. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  71953. // Members
  71954. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  71955. SceneLoader._registeredPlugins = {};
  71956. return SceneLoader;
  71957. }());
  71958. BABYLON.SceneLoader = SceneLoader;
  71959. ;
  71960. })(BABYLON || (BABYLON = {}));
  71961. //# sourceMappingURL=babylon.sceneLoader.js.map
  71962. var BABYLON;
  71963. (function (BABYLON) {
  71964. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  71965. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71966. var parsedMaterial = parsedData.materials[index];
  71967. if (parsedMaterial.id === id) {
  71968. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71969. }
  71970. }
  71971. return null;
  71972. };
  71973. var isDescendantOf = function (mesh, names, hierarchyIds) {
  71974. for (var i in names) {
  71975. if (mesh.name === names[i]) {
  71976. hierarchyIds.push(mesh.id);
  71977. return true;
  71978. }
  71979. }
  71980. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  71981. hierarchyIds.push(mesh.id);
  71982. return true;
  71983. }
  71984. return false;
  71985. };
  71986. var logOperation = function (operation, producer) {
  71987. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  71988. };
  71989. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  71990. if (addToScene === void 0) { addToScene = false; }
  71991. var container = new BABYLON.AssetContainer(scene);
  71992. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71993. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71994. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71995. // and avoid problems with multiple concurrent .babylon loads.
  71996. var log = "importScene has failed JSON parse";
  71997. try {
  71998. var parsedData = JSON.parse(data);
  71999. log = "";
  72000. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72001. var index;
  72002. var cache;
  72003. // Lights
  72004. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  72005. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  72006. var parsedLight = parsedData.lights[index];
  72007. var light = BABYLON.Light.Parse(parsedLight, scene);
  72008. if (light) {
  72009. container.lights.push(light);
  72010. log += (index === 0 ? "\n\tLights:" : "");
  72011. log += "\n\t\t" + light.toString(fullDetails);
  72012. }
  72013. }
  72014. }
  72015. // Animations
  72016. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  72017. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  72018. var parsedAnimation = parsedData.animations[index];
  72019. var animation = BABYLON.Animation.Parse(parsedAnimation);
  72020. scene.animations.push(animation);
  72021. container.animations.push(animation);
  72022. log += (index === 0 ? "\n\tAnimations:" : "");
  72023. log += "\n\t\t" + animation.toString(fullDetails);
  72024. }
  72025. }
  72026. // Materials
  72027. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  72028. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72029. var parsedMaterial = parsedData.materials[index];
  72030. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72031. container.materials.push(mat);
  72032. log += (index === 0 ? "\n\tMaterials:" : "");
  72033. log += "\n\t\t" + mat.toString(fullDetails);
  72034. }
  72035. }
  72036. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72037. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  72038. var parsedMultiMaterial = parsedData.multiMaterials[index];
  72039. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72040. container.multiMaterials.push(mmat);
  72041. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  72042. log += "\n\t\t" + mmat.toString(fullDetails);
  72043. }
  72044. }
  72045. // Morph targets
  72046. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72047. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72048. var managerData = _a[_i];
  72049. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  72050. }
  72051. }
  72052. // Skeletons
  72053. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72054. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  72055. var parsedSkeleton = parsedData.skeletons[index];
  72056. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72057. container.skeletons.push(skeleton);
  72058. log += (index === 0 ? "\n\tSkeletons:" : "");
  72059. log += "\n\t\t" + skeleton.toString(fullDetails);
  72060. }
  72061. }
  72062. // Geometries
  72063. var geometries = parsedData.geometries;
  72064. if (geometries !== undefined && geometries !== null) {
  72065. var addedGeometry = new Array();
  72066. // Boxes
  72067. var boxes = geometries.boxes;
  72068. if (boxes !== undefined && boxes !== null) {
  72069. for (index = 0, cache = boxes.length; index < cache; index++) {
  72070. var parsedBox = boxes[index];
  72071. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  72072. }
  72073. }
  72074. // Spheres
  72075. var spheres = geometries.spheres;
  72076. if (spheres !== undefined && spheres !== null) {
  72077. for (index = 0, cache = spheres.length; index < cache; index++) {
  72078. var parsedSphere = spheres[index];
  72079. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  72080. }
  72081. }
  72082. // Cylinders
  72083. var cylinders = geometries.cylinders;
  72084. if (cylinders !== undefined && cylinders !== null) {
  72085. for (index = 0, cache = cylinders.length; index < cache; index++) {
  72086. var parsedCylinder = cylinders[index];
  72087. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  72088. }
  72089. }
  72090. // Toruses
  72091. var toruses = geometries.toruses;
  72092. if (toruses !== undefined && toruses !== null) {
  72093. for (index = 0, cache = toruses.length; index < cache; index++) {
  72094. var parsedTorus = toruses[index];
  72095. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  72096. }
  72097. }
  72098. // Grounds
  72099. var grounds = geometries.grounds;
  72100. if (grounds !== undefined && grounds !== null) {
  72101. for (index = 0, cache = grounds.length; index < cache; index++) {
  72102. var parsedGround = grounds[index];
  72103. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  72104. }
  72105. }
  72106. // Planes
  72107. var planes = geometries.planes;
  72108. if (planes !== undefined && planes !== null) {
  72109. for (index = 0, cache = planes.length; index < cache; index++) {
  72110. var parsedPlane = planes[index];
  72111. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  72112. }
  72113. }
  72114. // TorusKnots
  72115. var torusKnots = geometries.torusKnots;
  72116. if (torusKnots !== undefined && torusKnots !== null) {
  72117. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  72118. var parsedTorusKnot = torusKnots[index];
  72119. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  72120. }
  72121. }
  72122. // VertexData
  72123. var vertexData = geometries.vertexData;
  72124. if (vertexData !== undefined && vertexData !== null) {
  72125. for (index = 0, cache = vertexData.length; index < cache; index++) {
  72126. var parsedVertexData = vertexData[index];
  72127. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  72128. }
  72129. }
  72130. addedGeometry.forEach(function (g) {
  72131. if (g) {
  72132. container.geometries.push(g);
  72133. }
  72134. });
  72135. }
  72136. // Transform nodes
  72137. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  72138. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  72139. var parsedTransformNode = parsedData.transformNodes[index];
  72140. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  72141. container.transformNodes.push(node);
  72142. }
  72143. }
  72144. // Meshes
  72145. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72146. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72147. var parsedMesh = parsedData.meshes[index];
  72148. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72149. container.meshes.push(mesh);
  72150. log += (index === 0 ? "\n\tMeshes:" : "");
  72151. log += "\n\t\t" + mesh.toString(fullDetails);
  72152. }
  72153. }
  72154. // Cameras
  72155. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  72156. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  72157. var parsedCamera = parsedData.cameras[index];
  72158. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  72159. container.cameras.push(camera);
  72160. log += (index === 0 ? "\n\tCameras:" : "");
  72161. log += "\n\t\t" + camera.toString(fullDetails);
  72162. }
  72163. }
  72164. // Browsing all the graph to connect the dots
  72165. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  72166. var camera = scene.cameras[index];
  72167. if (camera._waitingParentId) {
  72168. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  72169. camera._waitingParentId = null;
  72170. }
  72171. }
  72172. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72173. var light_1 = scene.lights[index];
  72174. if (light_1 && light_1._waitingParentId) {
  72175. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  72176. light_1._waitingParentId = null;
  72177. }
  72178. }
  72179. // Sounds
  72180. // TODO: add sound
  72181. var loadedSounds = [];
  72182. var loadedSound;
  72183. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72184. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72185. var parsedSound = parsedData.sounds[index];
  72186. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72187. if (!parsedSound.url)
  72188. parsedSound.url = parsedSound.name;
  72189. if (!loadedSounds[parsedSound.url]) {
  72190. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72191. loadedSounds[parsedSound.url] = loadedSound;
  72192. container.sounds.push(loadedSound);
  72193. }
  72194. else {
  72195. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72196. }
  72197. }
  72198. else {
  72199. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72200. }
  72201. }
  72202. }
  72203. loadedSounds = [];
  72204. // Connect parents & children and parse actions
  72205. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  72206. var transformNode = scene.transformNodes[index];
  72207. if (transformNode._waitingParentId) {
  72208. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  72209. transformNode._waitingParentId = null;
  72210. }
  72211. }
  72212. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72213. var mesh = scene.meshes[index];
  72214. if (mesh._waitingParentId) {
  72215. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  72216. mesh._waitingParentId = null;
  72217. }
  72218. if (mesh._waitingActions) {
  72219. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  72220. mesh._waitingActions = null;
  72221. }
  72222. }
  72223. // freeze world matrix application
  72224. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72225. var currentMesh = scene.meshes[index];
  72226. if (currentMesh._waitingFreezeWorldMatrix) {
  72227. currentMesh.freezeWorldMatrix();
  72228. currentMesh._waitingFreezeWorldMatrix = null;
  72229. }
  72230. else {
  72231. currentMesh.computeWorldMatrix(true);
  72232. }
  72233. }
  72234. // Lights exclusions / inclusions
  72235. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72236. var light_2 = scene.lights[index];
  72237. // Excluded check
  72238. if (light_2._excludedMeshesIds.length > 0) {
  72239. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  72240. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  72241. if (excludedMesh) {
  72242. light_2.excludedMeshes.push(excludedMesh);
  72243. }
  72244. }
  72245. light_2._excludedMeshesIds = [];
  72246. }
  72247. // Included check
  72248. if (light_2._includedOnlyMeshesIds.length > 0) {
  72249. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  72250. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  72251. if (includedOnlyMesh) {
  72252. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  72253. }
  72254. }
  72255. light_2._includedOnlyMeshesIds = [];
  72256. }
  72257. }
  72258. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  72259. // Actions (scene)
  72260. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  72261. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  72262. }
  72263. if (!addToScene) {
  72264. container.removeAllFromScene();
  72265. }
  72266. }
  72267. catch (err) {
  72268. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  72269. if (onError) {
  72270. onError(msg, err);
  72271. }
  72272. else {
  72273. BABYLON.Tools.Log(msg);
  72274. throw err;
  72275. }
  72276. }
  72277. finally {
  72278. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72279. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72280. }
  72281. }
  72282. return container;
  72283. };
  72284. BABYLON.SceneLoader.RegisterPlugin({
  72285. name: "babylon.js",
  72286. extensions: ".babylon",
  72287. canDirectLoad: function (data) {
  72288. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  72289. return true;
  72290. }
  72291. return false;
  72292. },
  72293. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  72294. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72295. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72296. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72297. // and avoid problems with multiple concurrent .babylon loads.
  72298. var log = "importMesh has failed JSON parse";
  72299. try {
  72300. var parsedData = JSON.parse(data);
  72301. log = "";
  72302. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72303. if (!meshesNames) {
  72304. meshesNames = null;
  72305. }
  72306. else if (!Array.isArray(meshesNames)) {
  72307. meshesNames = [meshesNames];
  72308. }
  72309. var hierarchyIds = new Array();
  72310. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72311. var loadedSkeletonsIds = [];
  72312. var loadedMaterialsIds = [];
  72313. var index;
  72314. var cache;
  72315. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72316. var parsedMesh = parsedData.meshes[index];
  72317. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  72318. if (meshesNames !== null) {
  72319. // Remove found mesh name from list.
  72320. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  72321. }
  72322. //Geometry?
  72323. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  72324. //does the file contain geometries?
  72325. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  72326. //find the correct geometry and add it to the scene
  72327. var found = false;
  72328. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  72329. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  72330. return;
  72331. }
  72332. else {
  72333. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  72334. if (parsedGeometryData.id === parsedMesh.geometryId) {
  72335. switch (geometryType) {
  72336. case "boxes":
  72337. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  72338. break;
  72339. case "spheres":
  72340. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  72341. break;
  72342. case "cylinders":
  72343. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  72344. break;
  72345. case "toruses":
  72346. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  72347. break;
  72348. case "grounds":
  72349. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  72350. break;
  72351. case "planes":
  72352. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  72353. break;
  72354. case "torusKnots":
  72355. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  72356. break;
  72357. case "vertexData":
  72358. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  72359. break;
  72360. }
  72361. found = true;
  72362. }
  72363. });
  72364. }
  72365. });
  72366. if (found === false) {
  72367. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  72368. }
  72369. }
  72370. }
  72371. // Material ?
  72372. if (parsedMesh.materialId) {
  72373. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  72374. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72375. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  72376. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  72377. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  72378. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  72379. var subMatId = parsedMultiMaterial.materials[matIndex];
  72380. loadedMaterialsIds.push(subMatId);
  72381. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  72382. if (mat) {
  72383. log += "\n\tMaterial " + mat.toString(fullDetails);
  72384. }
  72385. }
  72386. loadedMaterialsIds.push(parsedMultiMaterial.id);
  72387. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72388. if (mmat) {
  72389. materialFound = true;
  72390. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  72391. }
  72392. break;
  72393. }
  72394. }
  72395. }
  72396. if (materialFound === false) {
  72397. loadedMaterialsIds.push(parsedMesh.materialId);
  72398. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  72399. if (!mat) {
  72400. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  72401. }
  72402. else {
  72403. log += "\n\tMaterial " + mat.toString(fullDetails);
  72404. }
  72405. }
  72406. }
  72407. // Skeleton ?
  72408. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72409. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  72410. if (skeletonAlreadyLoaded === false) {
  72411. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  72412. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  72413. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  72414. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72415. skeletons.push(skeleton);
  72416. loadedSkeletonsIds.push(parsedSkeleton.id);
  72417. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  72418. }
  72419. }
  72420. }
  72421. }
  72422. // Morph targets ?
  72423. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72424. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72425. var managerData = _a[_i];
  72426. BABYLON.MorphTargetManager.Parse(managerData, scene);
  72427. }
  72428. }
  72429. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72430. meshes.push(mesh);
  72431. log += "\n\tMesh " + mesh.toString(fullDetails);
  72432. }
  72433. }
  72434. // Connecting parents
  72435. var currentMesh;
  72436. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72437. currentMesh = scene.meshes[index];
  72438. if (currentMesh._waitingParentId) {
  72439. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  72440. currentMesh._waitingParentId = null;
  72441. }
  72442. }
  72443. // freeze and compute world matrix application
  72444. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72445. currentMesh = scene.meshes[index];
  72446. if (currentMesh._waitingFreezeWorldMatrix) {
  72447. currentMesh.freezeWorldMatrix();
  72448. currentMesh._waitingFreezeWorldMatrix = null;
  72449. }
  72450. else {
  72451. currentMesh.computeWorldMatrix(true);
  72452. }
  72453. }
  72454. }
  72455. // Particles
  72456. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  72457. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  72458. if (parser) {
  72459. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  72460. var parsedParticleSystem = parsedData.particleSystems[index];
  72461. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  72462. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  72463. }
  72464. }
  72465. }
  72466. }
  72467. return true;
  72468. }
  72469. catch (err) {
  72470. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  72471. if (onError) {
  72472. onError(msg, err);
  72473. }
  72474. else {
  72475. BABYLON.Tools.Log(msg);
  72476. throw err;
  72477. }
  72478. }
  72479. finally {
  72480. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72481. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72482. }
  72483. }
  72484. return false;
  72485. },
  72486. load: function (scene, data, rootUrl, onError) {
  72487. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72488. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72489. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72490. // and avoid problems with multiple concurrent .babylon loads.
  72491. var log = "importScene has failed JSON parse";
  72492. try {
  72493. var parsedData = JSON.parse(data);
  72494. log = "";
  72495. // Scene
  72496. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  72497. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  72498. }
  72499. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  72500. scene.autoClear = parsedData.autoClear;
  72501. }
  72502. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  72503. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  72504. }
  72505. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  72506. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  72507. }
  72508. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  72509. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  72510. }
  72511. // Fog
  72512. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  72513. scene.fogMode = parsedData.fogMode;
  72514. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  72515. scene.fogStart = parsedData.fogStart;
  72516. scene.fogEnd = parsedData.fogEnd;
  72517. scene.fogDensity = parsedData.fogDensity;
  72518. log += "\tFog mode for scene: ";
  72519. switch (scene.fogMode) {
  72520. // getters not compiling, so using hardcoded
  72521. case 1:
  72522. log += "exp\n";
  72523. break;
  72524. case 2:
  72525. log += "exp2\n";
  72526. break;
  72527. case 3:
  72528. log += "linear\n";
  72529. break;
  72530. }
  72531. }
  72532. //Physics
  72533. if (parsedData.physicsEnabled) {
  72534. var physicsPlugin;
  72535. if (parsedData.physicsEngine === "cannon") {
  72536. physicsPlugin = new BABYLON.CannonJSPlugin();
  72537. }
  72538. else if (parsedData.physicsEngine === "oimo") {
  72539. physicsPlugin = new BABYLON.OimoJSPlugin();
  72540. }
  72541. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  72542. //else - default engine, which is currently oimo
  72543. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  72544. scene.enablePhysics(physicsGravity, physicsPlugin);
  72545. }
  72546. // Metadata
  72547. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  72548. scene.metadata = parsedData.metadata;
  72549. }
  72550. //collisions, if defined. otherwise, default is true
  72551. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  72552. scene.collisionsEnabled = parsedData.collisionsEnabled;
  72553. }
  72554. scene.workerCollisions = !!parsedData.workerCollisions;
  72555. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  72556. if (!container) {
  72557. return false;
  72558. }
  72559. if (parsedData.autoAnimate) {
  72560. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  72561. }
  72562. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  72563. scene.setActiveCameraByID(parsedData.activeCameraID);
  72564. }
  72565. // Environment texture
  72566. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  72567. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  72568. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  72569. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  72570. if (parsedData.environmentTextureRotationY) {
  72571. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  72572. }
  72573. scene.environmentTexture = hdrTexture;
  72574. }
  72575. else {
  72576. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  72577. if (parsedData.environmentTextureRotationY) {
  72578. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  72579. }
  72580. scene.environmentTexture = cubeTexture;
  72581. }
  72582. if (parsedData.createDefaultSkybox === true) {
  72583. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  72584. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  72585. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  72586. }
  72587. }
  72588. // Finish
  72589. return true;
  72590. }
  72591. catch (err) {
  72592. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  72593. if (onError) {
  72594. onError(msg, err);
  72595. }
  72596. else {
  72597. BABYLON.Tools.Log(msg);
  72598. throw err;
  72599. }
  72600. }
  72601. finally {
  72602. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72603. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72604. }
  72605. }
  72606. return false;
  72607. },
  72608. loadAssetContainer: function (scene, data, rootUrl, onError) {
  72609. var container = loadAssetContainer(scene, data, rootUrl, onError);
  72610. return container;
  72611. }
  72612. });
  72613. })(BABYLON || (BABYLON = {}));
  72614. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  72615. var BABYLON;
  72616. (function (BABYLON) {
  72617. var FilesInput = /** @class */ (function () {
  72618. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  72619. this.onProcessFileCallback = function () { return true; };
  72620. this._engine = engine;
  72621. this._currentScene = scene;
  72622. this._sceneLoadedCallback = sceneLoadedCallback;
  72623. this._progressCallback = progressCallback;
  72624. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  72625. this._textureLoadingCallback = textureLoadingCallback;
  72626. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  72627. this._onReloadCallback = onReloadCallback;
  72628. this._errorCallback = errorCallback;
  72629. }
  72630. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  72631. var _this = this;
  72632. if (elementToMonitor) {
  72633. this._elementToMonitor = elementToMonitor;
  72634. this._dragEnterHandler = function (e) { _this.drag(e); };
  72635. this._dragOverHandler = function (e) { _this.drag(e); };
  72636. this._dropHandler = function (e) { _this.drop(e); };
  72637. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  72638. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  72639. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72640. }
  72641. };
  72642. FilesInput.prototype.dispose = function () {
  72643. if (!this._elementToMonitor) {
  72644. return;
  72645. }
  72646. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  72647. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  72648. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  72649. };
  72650. FilesInput.prototype.renderFunction = function () {
  72651. if (this._additionalRenderLoopLogicCallback) {
  72652. this._additionalRenderLoopLogicCallback();
  72653. }
  72654. if (this._currentScene) {
  72655. if (this._textureLoadingCallback) {
  72656. var remaining = this._currentScene.getWaitingItemsCount();
  72657. if (remaining > 0) {
  72658. this._textureLoadingCallback(remaining);
  72659. }
  72660. }
  72661. this._currentScene.render();
  72662. }
  72663. };
  72664. FilesInput.prototype.drag = function (e) {
  72665. e.stopPropagation();
  72666. e.preventDefault();
  72667. };
  72668. FilesInput.prototype.drop = function (eventDrop) {
  72669. eventDrop.stopPropagation();
  72670. eventDrop.preventDefault();
  72671. this.loadFiles(eventDrop);
  72672. };
  72673. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  72674. var _this = this;
  72675. var reader = folder.createReader();
  72676. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  72677. reader.readEntries(function (entries) {
  72678. remaining.count += entries.length;
  72679. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  72680. var entry = entries_1[_i];
  72681. if (entry.isFile) {
  72682. entry.file(function (file) {
  72683. file.correctName = relativePath + file.name;
  72684. files.push(file);
  72685. if (--remaining.count === 0) {
  72686. callback();
  72687. }
  72688. });
  72689. }
  72690. else if (entry.isDirectory) {
  72691. _this._traverseFolder(entry, files, remaining, callback);
  72692. }
  72693. }
  72694. if (--remaining.count) {
  72695. callback();
  72696. }
  72697. });
  72698. };
  72699. FilesInput.prototype._processFiles = function (files) {
  72700. for (var i = 0; i < files.length; i++) {
  72701. var name = files[i].correctName.toLowerCase();
  72702. var extension = name.split('.').pop();
  72703. if (!this.onProcessFileCallback(files[i], name, extension)) {
  72704. continue;
  72705. }
  72706. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  72707. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  72708. this._sceneFileToLoad = files[i];
  72709. }
  72710. else {
  72711. FilesInput.FilesToLoad[name] = files[i];
  72712. }
  72713. }
  72714. };
  72715. FilesInput.prototype.loadFiles = function (event) {
  72716. var _this = this;
  72717. // Handling data transfer via drag'n'drop
  72718. if (event && event.dataTransfer && event.dataTransfer.files) {
  72719. this._filesToLoad = event.dataTransfer.files;
  72720. }
  72721. // Handling files from input files
  72722. if (event && event.target && event.target.files) {
  72723. this._filesToLoad = event.target.files;
  72724. }
  72725. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  72726. return;
  72727. }
  72728. if (this._startingProcessingFilesCallback) {
  72729. this._startingProcessingFilesCallback(this._filesToLoad);
  72730. }
  72731. if (this._filesToLoad && this._filesToLoad.length > 0) {
  72732. var files_1 = new Array();
  72733. var folders = [];
  72734. var items = event.dataTransfer ? event.dataTransfer.items : null;
  72735. for (var i = 0; i < this._filesToLoad.length; i++) {
  72736. var fileToLoad = this._filesToLoad[i];
  72737. var name_1 = fileToLoad.name.toLowerCase();
  72738. var entry = void 0;
  72739. fileToLoad.correctName = name_1;
  72740. if (items) {
  72741. var item = items[i];
  72742. if (item.getAsEntry) {
  72743. entry = item.getAsEntry();
  72744. }
  72745. else if (item.webkitGetAsEntry) {
  72746. entry = item.webkitGetAsEntry();
  72747. }
  72748. }
  72749. if (!entry) {
  72750. files_1.push(fileToLoad);
  72751. }
  72752. else {
  72753. if (entry.isDirectory) {
  72754. folders.push(entry);
  72755. }
  72756. else {
  72757. files_1.push(fileToLoad);
  72758. }
  72759. }
  72760. }
  72761. if (folders.length === 0) {
  72762. this._processFiles(files_1);
  72763. this._processReload();
  72764. }
  72765. else {
  72766. var remaining = { count: folders.length };
  72767. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  72768. var folder = folders_1[_i];
  72769. this._traverseFolder(folder, files_1, remaining, function () {
  72770. _this._processFiles(files_1);
  72771. if (remaining.count === 0) {
  72772. _this._processReload();
  72773. }
  72774. });
  72775. }
  72776. }
  72777. }
  72778. };
  72779. FilesInput.prototype._processReload = function () {
  72780. if (this._onReloadCallback) {
  72781. this._onReloadCallback(this._sceneFileToLoad);
  72782. }
  72783. else {
  72784. this.reload();
  72785. }
  72786. };
  72787. FilesInput.prototype.reload = function () {
  72788. var _this = this;
  72789. // If a scene file has been provided
  72790. if (this._sceneFileToLoad) {
  72791. if (this._currentScene) {
  72792. if (BABYLON.Tools.errorsCount > 0) {
  72793. BABYLON.Tools.ClearLogCache();
  72794. }
  72795. this._engine.stopRenderLoop();
  72796. }
  72797. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  72798. if (_this._progressCallback) {
  72799. _this._progressCallback(progress);
  72800. }
  72801. }).then(function (scene) {
  72802. if (_this._currentScene) {
  72803. _this._currentScene.dispose();
  72804. }
  72805. _this._currentScene = scene;
  72806. if (_this._sceneLoadedCallback) {
  72807. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  72808. }
  72809. // Wait for textures and shaders to be ready
  72810. _this._currentScene.executeWhenReady(function () {
  72811. _this._engine.runRenderLoop(function () {
  72812. _this.renderFunction();
  72813. });
  72814. });
  72815. }).catch(function (error) {
  72816. if (_this._errorCallback) {
  72817. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  72818. }
  72819. });
  72820. }
  72821. else {
  72822. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  72823. }
  72824. };
  72825. FilesInput.FilesToLoad = {};
  72826. return FilesInput;
  72827. }());
  72828. BABYLON.FilesInput = FilesInput;
  72829. })(BABYLON || (BABYLON = {}));
  72830. //# sourceMappingURL=babylon.filesInput.js.map
  72831. var BABYLON;
  72832. (function (BABYLON) {
  72833. var Tags = /** @class */ (function () {
  72834. function Tags() {
  72835. }
  72836. Tags.EnableFor = function (obj) {
  72837. obj._tags = obj._tags || {};
  72838. obj.hasTags = function () {
  72839. return Tags.HasTags(obj);
  72840. };
  72841. obj.addTags = function (tagsString) {
  72842. return Tags.AddTagsTo(obj, tagsString);
  72843. };
  72844. obj.removeTags = function (tagsString) {
  72845. return Tags.RemoveTagsFrom(obj, tagsString);
  72846. };
  72847. obj.matchesTagsQuery = function (tagsQuery) {
  72848. return Tags.MatchesQuery(obj, tagsQuery);
  72849. };
  72850. };
  72851. Tags.DisableFor = function (obj) {
  72852. delete obj._tags;
  72853. delete obj.hasTags;
  72854. delete obj.addTags;
  72855. delete obj.removeTags;
  72856. delete obj.matchesTagsQuery;
  72857. };
  72858. Tags.HasTags = function (obj) {
  72859. if (!obj._tags) {
  72860. return false;
  72861. }
  72862. return !BABYLON.Tools.IsEmpty(obj._tags);
  72863. };
  72864. Tags.GetTags = function (obj, asString) {
  72865. if (asString === void 0) { asString = true; }
  72866. if (!obj._tags) {
  72867. return null;
  72868. }
  72869. if (asString) {
  72870. var tagsArray = [];
  72871. for (var tag in obj._tags) {
  72872. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  72873. tagsArray.push(tag);
  72874. }
  72875. }
  72876. return tagsArray.join(" ");
  72877. }
  72878. else {
  72879. return obj._tags;
  72880. }
  72881. };
  72882. // the tags 'true' and 'false' are reserved and cannot be used as tags
  72883. // a tag cannot start with '||', '&&', and '!'
  72884. // it cannot contain whitespaces
  72885. Tags.AddTagsTo = function (obj, tagsString) {
  72886. if (!tagsString) {
  72887. return;
  72888. }
  72889. if (typeof tagsString !== "string") {
  72890. return;
  72891. }
  72892. var tags = tagsString.split(" ");
  72893. tags.forEach(function (tag, index, array) {
  72894. Tags._AddTagTo(obj, tag);
  72895. });
  72896. };
  72897. Tags._AddTagTo = function (obj, tag) {
  72898. tag = tag.trim();
  72899. if (tag === "" || tag === "true" || tag === "false") {
  72900. return;
  72901. }
  72902. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  72903. return;
  72904. }
  72905. Tags.EnableFor(obj);
  72906. obj._tags[tag] = true;
  72907. };
  72908. Tags.RemoveTagsFrom = function (obj, tagsString) {
  72909. if (!Tags.HasTags(obj)) {
  72910. return;
  72911. }
  72912. var tags = tagsString.split(" ");
  72913. for (var t in tags) {
  72914. Tags._RemoveTagFrom(obj, tags[t]);
  72915. }
  72916. };
  72917. Tags._RemoveTagFrom = function (obj, tag) {
  72918. delete obj._tags[tag];
  72919. };
  72920. Tags.MatchesQuery = function (obj, tagsQuery) {
  72921. if (tagsQuery === undefined) {
  72922. return true;
  72923. }
  72924. if (tagsQuery === "") {
  72925. return Tags.HasTags(obj);
  72926. }
  72927. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  72928. };
  72929. return Tags;
  72930. }());
  72931. BABYLON.Tags = Tags;
  72932. })(BABYLON || (BABYLON = {}));
  72933. //# sourceMappingURL=babylon.tags.js.map
  72934. var BABYLON;
  72935. (function (BABYLON) {
  72936. /**
  72937. * Class used to evalaute queries containing `and` and `or` operators
  72938. */
  72939. var AndOrNotEvaluator = /** @class */ (function () {
  72940. function AndOrNotEvaluator() {
  72941. }
  72942. /**
  72943. * Evaluate a query
  72944. * @param query defines the query to evaluate
  72945. * @param evaluateCallback defines the callback used to filter result
  72946. * @returns true if the query matches
  72947. */
  72948. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  72949. if (!query.match(/\([^\(\)]*\)/g)) {
  72950. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  72951. }
  72952. else {
  72953. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  72954. // remove parenthesis
  72955. r = r.slice(1, r.length - 1);
  72956. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  72957. });
  72958. }
  72959. if (query === "true") {
  72960. return true;
  72961. }
  72962. if (query === "false") {
  72963. return false;
  72964. }
  72965. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  72966. };
  72967. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  72968. evaluateCallback = evaluateCallback || (function (r) {
  72969. return r === "true" ? true : false;
  72970. });
  72971. var result;
  72972. var or = parenthesisContent.split("||");
  72973. for (var i in or) {
  72974. if (or.hasOwnProperty(i)) {
  72975. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  72976. var and = ori.split("&&");
  72977. if (and.length > 1) {
  72978. for (var j = 0; j < and.length; ++j) {
  72979. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  72980. if (andj !== "true" && andj !== "false") {
  72981. if (andj[0] === "!") {
  72982. result = !evaluateCallback(andj.substring(1));
  72983. }
  72984. else {
  72985. result = evaluateCallback(andj);
  72986. }
  72987. }
  72988. else {
  72989. result = andj === "true" ? true : false;
  72990. }
  72991. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  72992. ori = "false";
  72993. break;
  72994. }
  72995. }
  72996. }
  72997. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  72998. result = true;
  72999. break;
  73000. }
  73001. // result equals false (or undefined)
  73002. if (ori !== "true" && ori !== "false") {
  73003. if (ori[0] === "!") {
  73004. result = !evaluateCallback(ori.substring(1));
  73005. }
  73006. else {
  73007. result = evaluateCallback(ori);
  73008. }
  73009. }
  73010. else {
  73011. result = ori === "true" ? true : false;
  73012. }
  73013. }
  73014. }
  73015. // the whole parenthesis scope is replaced by 'true' or 'false'
  73016. return result ? "true" : "false";
  73017. };
  73018. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  73019. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  73020. // remove whitespaces
  73021. r = r.replace(/[\s]/g, function () { return ""; });
  73022. return r.length % 2 ? "!" : "";
  73023. });
  73024. booleanString = booleanString.trim();
  73025. if (booleanString === "!true") {
  73026. booleanString = "false";
  73027. }
  73028. else if (booleanString === "!false") {
  73029. booleanString = "true";
  73030. }
  73031. return booleanString;
  73032. };
  73033. return AndOrNotEvaluator;
  73034. }());
  73035. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  73036. })(BABYLON || (BABYLON = {}));
  73037. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  73038. var BABYLON;
  73039. (function (BABYLON) {
  73040. /**
  73041. * Class used to enable access to IndexedDB
  73042. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  73043. */
  73044. var Database = /** @class */ (function () {
  73045. /**
  73046. * Creates a new Database
  73047. * @param urlToScene defines the url to load the scene
  73048. * @param callbackManifestChecked defines the callback to use when manifest is checked
  73049. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  73050. */
  73051. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  73052. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  73053. var _this = this;
  73054. // Handling various flavors of prefixed version of IndexedDB
  73055. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  73056. this.callbackManifestChecked = callbackManifestChecked;
  73057. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  73058. this.db = null;
  73059. this._enableSceneOffline = false;
  73060. this._enableTexturesOffline = false;
  73061. this.manifestVersionFound = 0;
  73062. this.mustUpdateRessources = false;
  73063. this.hasReachedQuota = false;
  73064. if (!Database.IDBStorageEnabled) {
  73065. this.callbackManifestChecked(true);
  73066. }
  73067. else {
  73068. if (disableManifestCheck) {
  73069. this._enableSceneOffline = true;
  73070. this._enableTexturesOffline = true;
  73071. this.manifestVersionFound = 1;
  73072. BABYLON.Tools.SetImmediate(function () {
  73073. _this.callbackManifestChecked(true);
  73074. });
  73075. }
  73076. else {
  73077. this._checkManifestFile();
  73078. }
  73079. }
  73080. }
  73081. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  73082. /**
  73083. * Gets a boolean indicating if scene must be saved in the database
  73084. */
  73085. get: function () {
  73086. return this._enableSceneOffline;
  73087. },
  73088. enumerable: true,
  73089. configurable: true
  73090. });
  73091. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  73092. /**
  73093. * Gets a boolean indicating if textures must be saved in the database
  73094. */
  73095. get: function () {
  73096. return this._enableTexturesOffline;
  73097. },
  73098. enumerable: true,
  73099. configurable: true
  73100. });
  73101. Database.prototype._checkManifestFile = function () {
  73102. var _this = this;
  73103. var noManifestFile = function () {
  73104. _this._enableSceneOffline = false;
  73105. _this._enableTexturesOffline = false;
  73106. _this.callbackManifestChecked(false);
  73107. };
  73108. var timeStampUsed = false;
  73109. var manifestURL = this.currentSceneUrl + ".manifest";
  73110. var xhr = new XMLHttpRequest();
  73111. if (navigator.onLine) {
  73112. // Adding a timestamp to by-pass browsers' cache
  73113. timeStampUsed = true;
  73114. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  73115. }
  73116. xhr.open("GET", manifestURL, true);
  73117. xhr.addEventListener("load", function () {
  73118. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73119. try {
  73120. var manifestFile = JSON.parse(xhr.response);
  73121. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  73122. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  73123. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  73124. _this.manifestVersionFound = manifestFile.version;
  73125. }
  73126. if (_this.callbackManifestChecked) {
  73127. _this.callbackManifestChecked(true);
  73128. }
  73129. }
  73130. catch (ex) {
  73131. noManifestFile();
  73132. }
  73133. }
  73134. else {
  73135. noManifestFile();
  73136. }
  73137. }, false);
  73138. xhr.addEventListener("error", function (event) {
  73139. if (timeStampUsed) {
  73140. timeStampUsed = false;
  73141. // Let's retry without the timeStamp
  73142. // It could fail when coupled with HTML5 Offline API
  73143. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  73144. xhr.open("GET", retryManifestURL, true);
  73145. xhr.send();
  73146. }
  73147. else {
  73148. noManifestFile();
  73149. }
  73150. }, false);
  73151. try {
  73152. xhr.send();
  73153. }
  73154. catch (ex) {
  73155. BABYLON.Tools.Error("Error on XHR send request.");
  73156. this.callbackManifestChecked(false);
  73157. }
  73158. };
  73159. /**
  73160. * Open the database and make it available
  73161. * @param successCallback defines the callback to call on success
  73162. * @param errorCallback defines the callback to call on error
  73163. */
  73164. Database.prototype.openAsync = function (successCallback, errorCallback) {
  73165. var _this = this;
  73166. var handleError = function () {
  73167. _this.isSupported = false;
  73168. if (errorCallback)
  73169. errorCallback();
  73170. };
  73171. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  73172. // Your browser doesn't support IndexedDB
  73173. this.isSupported = false;
  73174. if (errorCallback)
  73175. errorCallback();
  73176. }
  73177. else {
  73178. // If the DB hasn't been opened or created yet
  73179. if (!this.db) {
  73180. this.hasReachedQuota = false;
  73181. this.isSupported = true;
  73182. var request = this.idbFactory.open("babylonjs", 1);
  73183. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  73184. request.onerror = function (event) {
  73185. handleError();
  73186. };
  73187. // executes when a version change transaction cannot complete due to other active transactions
  73188. request.onblocked = function (event) {
  73189. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  73190. handleError();
  73191. };
  73192. // DB has been opened successfully
  73193. request.onsuccess = function (event) {
  73194. _this.db = request.result;
  73195. successCallback();
  73196. };
  73197. // Initialization of the DB. Creating Scenes & Textures stores
  73198. request.onupgradeneeded = function (event) {
  73199. _this.db = (event.target).result;
  73200. if (_this.db) {
  73201. try {
  73202. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  73203. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  73204. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  73205. }
  73206. catch (ex) {
  73207. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  73208. handleError();
  73209. }
  73210. }
  73211. };
  73212. }
  73213. // DB has already been created and opened
  73214. else {
  73215. if (successCallback)
  73216. successCallback();
  73217. }
  73218. }
  73219. };
  73220. /**
  73221. * Loads an image from the database
  73222. * @param url defines the url to load from
  73223. * @param image defines the target DOM image
  73224. */
  73225. Database.prototype.loadImageFromDB = function (url, image) {
  73226. var _this = this;
  73227. var completeURL = Database._ReturnFullUrlLocation(url);
  73228. var saveAndLoadImage = function () {
  73229. if (!_this.hasReachedQuota && _this.db !== null) {
  73230. // the texture is not yet in the DB, let's try to save it
  73231. _this._saveImageIntoDBAsync(completeURL, image);
  73232. }
  73233. // If the texture is not in the DB and we've reached the DB quota limit
  73234. // let's load it directly from the web
  73235. else {
  73236. image.src = url;
  73237. }
  73238. };
  73239. if (!this.mustUpdateRessources) {
  73240. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  73241. }
  73242. // First time we're download the images or update requested in the manifest file by a version change
  73243. else {
  73244. saveAndLoadImage();
  73245. }
  73246. };
  73247. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  73248. if (this.isSupported && this.db !== null) {
  73249. var texture;
  73250. var transaction = this.db.transaction(["textures"]);
  73251. transaction.onabort = function (event) {
  73252. image.src = url;
  73253. };
  73254. transaction.oncomplete = function (event) {
  73255. var blobTextureURL;
  73256. if (texture) {
  73257. var URL = window.URL || window.webkitURL;
  73258. blobTextureURL = URL.createObjectURL(texture.data);
  73259. image.onerror = function () {
  73260. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  73261. image.src = url;
  73262. };
  73263. image.src = blobTextureURL;
  73264. }
  73265. else {
  73266. notInDBCallback();
  73267. }
  73268. };
  73269. var getRequest = transaction.objectStore("textures").get(url);
  73270. getRequest.onsuccess = function (event) {
  73271. texture = (event.target).result;
  73272. };
  73273. getRequest.onerror = function (event) {
  73274. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  73275. image.src = url;
  73276. };
  73277. }
  73278. else {
  73279. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73280. image.src = url;
  73281. }
  73282. };
  73283. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  73284. var _this = this;
  73285. if (this.isSupported) {
  73286. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  73287. var generateBlobUrl = function () {
  73288. var blobTextureURL;
  73289. if (blob) {
  73290. var URL = window.URL || window.webkitURL;
  73291. try {
  73292. blobTextureURL = URL.createObjectURL(blob);
  73293. }
  73294. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  73295. catch (ex) {
  73296. blobTextureURL = URL.createObjectURL(blob);
  73297. }
  73298. }
  73299. if (blobTextureURL) {
  73300. image.src = blobTextureURL;
  73301. }
  73302. };
  73303. if (Database.IsUASupportingBlobStorage) { // Create XHR
  73304. var xhr = new XMLHttpRequest(), blob;
  73305. xhr.open("GET", url, true);
  73306. xhr.responseType = "blob";
  73307. xhr.addEventListener("load", function () {
  73308. if (xhr.status === 200 && _this.db) {
  73309. // Blob as response (XHR2)
  73310. blob = xhr.response;
  73311. var transaction = _this.db.transaction(["textures"], "readwrite");
  73312. // the transaction could abort because of a QuotaExceededError error
  73313. transaction.onabort = function (event) {
  73314. try {
  73315. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73316. var srcElement = (event.srcElement || event.target);
  73317. var error = srcElement.error;
  73318. if (error && error.name === "QuotaExceededError") {
  73319. _this.hasReachedQuota = true;
  73320. }
  73321. }
  73322. catch (ex) { }
  73323. generateBlobUrl();
  73324. };
  73325. transaction.oncomplete = function (event) {
  73326. generateBlobUrl();
  73327. };
  73328. var newTexture = { textureUrl: url, data: blob };
  73329. try {
  73330. // Put the blob into the dabase
  73331. var addRequest = transaction.objectStore("textures").put(newTexture);
  73332. addRequest.onsuccess = function (event) {
  73333. };
  73334. addRequest.onerror = function (event) {
  73335. generateBlobUrl();
  73336. };
  73337. }
  73338. catch (ex) {
  73339. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  73340. if (ex.code === 25) {
  73341. Database.IsUASupportingBlobStorage = false;
  73342. }
  73343. image.src = url;
  73344. }
  73345. }
  73346. else {
  73347. image.src = url;
  73348. }
  73349. }, false);
  73350. xhr.addEventListener("error", function (event) {
  73351. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  73352. image.src = url;
  73353. }, false);
  73354. xhr.send();
  73355. }
  73356. else {
  73357. image.src = url;
  73358. }
  73359. }
  73360. else {
  73361. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73362. image.src = url;
  73363. }
  73364. };
  73365. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  73366. var _this = this;
  73367. var updateVersion = function () {
  73368. // the version is not yet in the DB or we need to update it
  73369. _this._saveVersionIntoDBAsync(url, versionLoaded);
  73370. };
  73371. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  73372. };
  73373. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  73374. var _this = this;
  73375. if (this.isSupported && this.db) {
  73376. var version;
  73377. try {
  73378. var transaction = this.db.transaction(["versions"]);
  73379. transaction.oncomplete = function (event) {
  73380. if (version) {
  73381. // If the version in the JSON file is different from the version in DB
  73382. if (_this.manifestVersionFound !== version.data) {
  73383. _this.mustUpdateRessources = true;
  73384. updateInDBCallback();
  73385. }
  73386. else {
  73387. callback(version.data);
  73388. }
  73389. }
  73390. // version was not found in DB
  73391. else {
  73392. _this.mustUpdateRessources = true;
  73393. updateInDBCallback();
  73394. }
  73395. };
  73396. transaction.onabort = function (event) {
  73397. callback(-1);
  73398. };
  73399. var getRequest = transaction.objectStore("versions").get(url);
  73400. getRequest.onsuccess = function (event) {
  73401. version = (event.target).result;
  73402. };
  73403. getRequest.onerror = function (event) {
  73404. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  73405. callback(-1);
  73406. };
  73407. }
  73408. catch (ex) {
  73409. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  73410. callback(-1);
  73411. }
  73412. }
  73413. else {
  73414. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73415. callback(-1);
  73416. }
  73417. };
  73418. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  73419. var _this = this;
  73420. if (this.isSupported && !this.hasReachedQuota && this.db) {
  73421. try {
  73422. // Open a transaction to the database
  73423. var transaction = this.db.transaction(["versions"], "readwrite");
  73424. // the transaction could abort because of a QuotaExceededError error
  73425. transaction.onabort = function (event) {
  73426. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73427. var error = event.srcElement['error'];
  73428. if (error && error.name === "QuotaExceededError") {
  73429. _this.hasReachedQuota = true;
  73430. }
  73431. }
  73432. catch (ex) { }
  73433. callback(-1);
  73434. };
  73435. transaction.oncomplete = function (event) {
  73436. callback(_this.manifestVersionFound);
  73437. };
  73438. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  73439. // Put the scene into the database
  73440. var addRequest = transaction.objectStore("versions").put(newVersion);
  73441. addRequest.onsuccess = function (event) {
  73442. };
  73443. addRequest.onerror = function (event) {
  73444. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  73445. };
  73446. }
  73447. catch (ex) {
  73448. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  73449. callback(-1);
  73450. }
  73451. }
  73452. else {
  73453. callback(-1);
  73454. }
  73455. };
  73456. /**
  73457. * Loads a file from database
  73458. * @param url defines the URL to load from
  73459. * @param sceneLoaded defines a callback to call on success
  73460. * @param progressCallBack defines a callback to call when progress changed
  73461. * @param errorCallback defines a callback to call on error
  73462. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  73463. */
  73464. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  73465. var _this = this;
  73466. var completeUrl = Database._ReturnFullUrlLocation(url);
  73467. var saveAndLoadFile = function () {
  73468. // the scene is not yet in the DB, let's try to save it
  73469. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73470. };
  73471. this._checkVersionFromDB(completeUrl, function (version) {
  73472. if (version !== -1) {
  73473. if (!_this.mustUpdateRessources) {
  73474. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  73475. }
  73476. else {
  73477. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73478. }
  73479. }
  73480. else {
  73481. if (errorCallback) {
  73482. errorCallback();
  73483. }
  73484. }
  73485. });
  73486. };
  73487. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  73488. if (this.isSupported && this.db) {
  73489. var targetStore;
  73490. if (url.indexOf(".babylon") !== -1) {
  73491. targetStore = "scenes";
  73492. }
  73493. else {
  73494. targetStore = "textures";
  73495. }
  73496. var file;
  73497. var transaction = this.db.transaction([targetStore]);
  73498. transaction.oncomplete = function (event) {
  73499. if (file) {
  73500. callback(file.data);
  73501. }
  73502. // file was not found in DB
  73503. else {
  73504. notInDBCallback();
  73505. }
  73506. };
  73507. transaction.onabort = function (event) {
  73508. notInDBCallback();
  73509. };
  73510. var getRequest = transaction.objectStore(targetStore).get(url);
  73511. getRequest.onsuccess = function (event) {
  73512. file = (event.target).result;
  73513. };
  73514. getRequest.onerror = function (event) {
  73515. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  73516. notInDBCallback();
  73517. };
  73518. }
  73519. else {
  73520. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73521. callback();
  73522. }
  73523. };
  73524. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  73525. var _this = this;
  73526. if (this.isSupported) {
  73527. var targetStore;
  73528. if (url.indexOf(".babylon") !== -1) {
  73529. targetStore = "scenes";
  73530. }
  73531. else {
  73532. targetStore = "textures";
  73533. }
  73534. // Create XHR
  73535. var xhr = new XMLHttpRequest();
  73536. var fileData;
  73537. xhr.open("GET", url + "?" + Date.now(), true);
  73538. if (useArrayBuffer) {
  73539. xhr.responseType = "arraybuffer";
  73540. }
  73541. if (progressCallback) {
  73542. xhr.onprogress = progressCallback;
  73543. }
  73544. xhr.addEventListener("load", function () {
  73545. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  73546. // Blob as response (XHR2)
  73547. //fileData = xhr.responseText;
  73548. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  73549. if (!_this.hasReachedQuota && _this.db) {
  73550. // Open a transaction to the database
  73551. var transaction = _this.db.transaction([targetStore], "readwrite");
  73552. // the transaction could abort because of a QuotaExceededError error
  73553. transaction.onabort = function (event) {
  73554. try {
  73555. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73556. var error = event.srcElement['error'];
  73557. if (error && error.name === "QuotaExceededError") {
  73558. _this.hasReachedQuota = true;
  73559. }
  73560. }
  73561. catch (ex) { }
  73562. callback(fileData);
  73563. };
  73564. transaction.oncomplete = function (event) {
  73565. callback(fileData);
  73566. };
  73567. var newFile;
  73568. if (targetStore === "scenes") {
  73569. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  73570. }
  73571. else {
  73572. newFile = { textureUrl: url, data: fileData };
  73573. }
  73574. try {
  73575. // Put the scene into the database
  73576. var addRequest = transaction.objectStore(targetStore).put(newFile);
  73577. addRequest.onsuccess = function (event) {
  73578. };
  73579. addRequest.onerror = function (event) {
  73580. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  73581. };
  73582. }
  73583. catch (ex) {
  73584. callback(fileData);
  73585. }
  73586. }
  73587. else {
  73588. callback(fileData);
  73589. }
  73590. }
  73591. else {
  73592. if (xhr.status >= 400 && errorCallback) {
  73593. errorCallback(xhr);
  73594. }
  73595. else {
  73596. callback();
  73597. }
  73598. }
  73599. }, false);
  73600. xhr.addEventListener("error", function (event) {
  73601. BABYLON.Tools.Error("error on XHR request.");
  73602. callback();
  73603. }, false);
  73604. xhr.send();
  73605. }
  73606. else {
  73607. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73608. callback();
  73609. }
  73610. };
  73611. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  73612. Database.IsUASupportingBlobStorage = true;
  73613. /** Gets a boolean indicating if Database storate is enabled */
  73614. Database.IDBStorageEnabled = true;
  73615. Database._ParseURL = function (url) {
  73616. var a = document.createElement('a');
  73617. a.href = url;
  73618. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  73619. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  73620. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  73621. return absLocation;
  73622. };
  73623. Database._ReturnFullUrlLocation = function (url) {
  73624. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  73625. return (Database._ParseURL(window.location.href) + url);
  73626. }
  73627. else {
  73628. return url;
  73629. }
  73630. };
  73631. return Database;
  73632. }());
  73633. BABYLON.Database = Database;
  73634. })(BABYLON || (BABYLON = {}));
  73635. //# sourceMappingURL=babylon.database.js.map
  73636. var BABYLON;
  73637. (function (BABYLON) {
  73638. var FresnelParameters = /** @class */ (function () {
  73639. function FresnelParameters() {
  73640. this._isEnabled = true;
  73641. this.leftColor = BABYLON.Color3.White();
  73642. this.rightColor = BABYLON.Color3.Black();
  73643. this.bias = 0;
  73644. this.power = 1;
  73645. }
  73646. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  73647. get: function () {
  73648. return this._isEnabled;
  73649. },
  73650. set: function (value) {
  73651. if (this._isEnabled === value) {
  73652. return;
  73653. }
  73654. this._isEnabled = value;
  73655. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  73656. },
  73657. enumerable: true,
  73658. configurable: true
  73659. });
  73660. FresnelParameters.prototype.clone = function () {
  73661. var newFresnelParameters = new FresnelParameters();
  73662. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  73663. return newFresnelParameters;
  73664. };
  73665. FresnelParameters.prototype.serialize = function () {
  73666. var serializationObject = {};
  73667. serializationObject.isEnabled = this.isEnabled;
  73668. serializationObject.leftColor = this.leftColor.asArray();
  73669. serializationObject.rightColor = this.rightColor.asArray();
  73670. serializationObject.bias = this.bias;
  73671. serializationObject.power = this.power;
  73672. return serializationObject;
  73673. };
  73674. FresnelParameters.Parse = function (parsedFresnelParameters) {
  73675. var fresnelParameters = new FresnelParameters();
  73676. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  73677. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  73678. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  73679. fresnelParameters.bias = parsedFresnelParameters.bias;
  73680. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  73681. return fresnelParameters;
  73682. };
  73683. return FresnelParameters;
  73684. }());
  73685. BABYLON.FresnelParameters = FresnelParameters;
  73686. })(BABYLON || (BABYLON = {}));
  73687. //# sourceMappingURL=babylon.fresnelParameters.js.map
  73688. var BABYLON;
  73689. (function (BABYLON) {
  73690. var MultiMaterial = /** @class */ (function (_super) {
  73691. __extends(MultiMaterial, _super);
  73692. function MultiMaterial(name, scene) {
  73693. var _this = _super.call(this, name, scene, true) || this;
  73694. scene.multiMaterials.push(_this);
  73695. _this.subMaterials = new Array();
  73696. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  73697. return _this;
  73698. }
  73699. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  73700. get: function () {
  73701. return this._subMaterials;
  73702. },
  73703. set: function (value) {
  73704. this._subMaterials = value;
  73705. this._hookArray(value);
  73706. },
  73707. enumerable: true,
  73708. configurable: true
  73709. });
  73710. MultiMaterial.prototype._hookArray = function (array) {
  73711. var _this = this;
  73712. var oldPush = array.push;
  73713. array.push = function () {
  73714. var items = [];
  73715. for (var _i = 0; _i < arguments.length; _i++) {
  73716. items[_i] = arguments[_i];
  73717. }
  73718. var result = oldPush.apply(array, items);
  73719. _this._markAllSubMeshesAsTexturesDirty();
  73720. return result;
  73721. };
  73722. var oldSplice = array.splice;
  73723. array.splice = function (index, deleteCount) {
  73724. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73725. _this._markAllSubMeshesAsTexturesDirty();
  73726. return deleted;
  73727. };
  73728. };
  73729. // Properties
  73730. MultiMaterial.prototype.getSubMaterial = function (index) {
  73731. if (index < 0 || index >= this.subMaterials.length) {
  73732. return this.getScene().defaultMaterial;
  73733. }
  73734. return this.subMaterials[index];
  73735. };
  73736. MultiMaterial.prototype.getActiveTextures = function () {
  73737. var _a;
  73738. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  73739. if (subMaterial) {
  73740. return subMaterial.getActiveTextures();
  73741. }
  73742. else {
  73743. return [];
  73744. }
  73745. }));
  73746. };
  73747. // Methods
  73748. MultiMaterial.prototype.getClassName = function () {
  73749. return "MultiMaterial";
  73750. };
  73751. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  73752. for (var index = 0; index < this.subMaterials.length; index++) {
  73753. var subMaterial = this.subMaterials[index];
  73754. if (subMaterial) {
  73755. if (subMaterial.storeEffectOnSubMeshes) {
  73756. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  73757. return false;
  73758. }
  73759. continue;
  73760. }
  73761. if (!subMaterial.isReady(mesh)) {
  73762. return false;
  73763. }
  73764. }
  73765. }
  73766. return true;
  73767. };
  73768. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  73769. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  73770. for (var index = 0; index < this.subMaterials.length; index++) {
  73771. var subMaterial = null;
  73772. var current = this.subMaterials[index];
  73773. if (cloneChildren && current) {
  73774. subMaterial = current.clone(name + "-" + current.name);
  73775. }
  73776. else {
  73777. subMaterial = this.subMaterials[index];
  73778. }
  73779. newMultiMaterial.subMaterials.push(subMaterial);
  73780. }
  73781. return newMultiMaterial;
  73782. };
  73783. MultiMaterial.prototype.serialize = function () {
  73784. var serializationObject = {};
  73785. serializationObject.name = this.name;
  73786. serializationObject.id = this.id;
  73787. if (BABYLON.Tags) {
  73788. serializationObject.tags = BABYLON.Tags.GetTags(this);
  73789. }
  73790. serializationObject.materials = [];
  73791. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  73792. var subMat = this.subMaterials[matIndex];
  73793. if (subMat) {
  73794. serializationObject.materials.push(subMat.id);
  73795. }
  73796. else {
  73797. serializationObject.materials.push(null);
  73798. }
  73799. }
  73800. return serializationObject;
  73801. };
  73802. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  73803. var scene = this.getScene();
  73804. if (!scene) {
  73805. return;
  73806. }
  73807. var index = scene.multiMaterials.indexOf(this);
  73808. if (index >= 0) {
  73809. scene.multiMaterials.splice(index, 1);
  73810. }
  73811. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  73812. };
  73813. return MultiMaterial;
  73814. }(BABYLON.Material));
  73815. BABYLON.MultiMaterial = MultiMaterial;
  73816. })(BABYLON || (BABYLON = {}));
  73817. //# sourceMappingURL=babylon.multiMaterial.js.map
  73818. var BABYLON;
  73819. (function (BABYLON) {
  73820. var FreeCameraTouchInput = /** @class */ (function () {
  73821. function FreeCameraTouchInput() {
  73822. this._offsetX = null;
  73823. this._offsetY = null;
  73824. this._pointerPressed = new Array();
  73825. this.touchAngularSensibility = 200000.0;
  73826. this.touchMoveSensibility = 250.0;
  73827. }
  73828. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  73829. var _this = this;
  73830. var previousPosition = null;
  73831. if (this._pointerInput === undefined) {
  73832. this._onLostFocus = function (evt) {
  73833. _this._offsetX = null;
  73834. _this._offsetY = null;
  73835. };
  73836. this._pointerInput = function (p, s) {
  73837. var evt = p.event;
  73838. if (evt.pointerType === "mouse") {
  73839. return;
  73840. }
  73841. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73842. if (!noPreventDefault) {
  73843. evt.preventDefault();
  73844. }
  73845. _this._pointerPressed.push(evt.pointerId);
  73846. if (_this._pointerPressed.length !== 1) {
  73847. return;
  73848. }
  73849. previousPosition = {
  73850. x: evt.clientX,
  73851. y: evt.clientY
  73852. };
  73853. }
  73854. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  73855. if (!noPreventDefault) {
  73856. evt.preventDefault();
  73857. }
  73858. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73859. if (index === -1) {
  73860. return;
  73861. }
  73862. _this._pointerPressed.splice(index, 1);
  73863. if (index != 0) {
  73864. return;
  73865. }
  73866. previousPosition = null;
  73867. _this._offsetX = null;
  73868. _this._offsetY = null;
  73869. }
  73870. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  73871. if (!noPreventDefault) {
  73872. evt.preventDefault();
  73873. }
  73874. if (!previousPosition) {
  73875. return;
  73876. }
  73877. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73878. if (index != 0) {
  73879. return;
  73880. }
  73881. _this._offsetX = evt.clientX - previousPosition.x;
  73882. _this._offsetY = -(evt.clientY - previousPosition.y);
  73883. }
  73884. };
  73885. }
  73886. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  73887. if (this._onLostFocus) {
  73888. element.addEventListener("blur", this._onLostFocus);
  73889. }
  73890. };
  73891. FreeCameraTouchInput.prototype.detachControl = function (element) {
  73892. if (this._pointerInput && element) {
  73893. if (this._observer) {
  73894. this.camera.getScene().onPointerObservable.remove(this._observer);
  73895. this._observer = null;
  73896. }
  73897. if (this._onLostFocus) {
  73898. element.removeEventListener("blur", this._onLostFocus);
  73899. this._onLostFocus = null;
  73900. }
  73901. this._pointerPressed = [];
  73902. this._offsetX = null;
  73903. this._offsetY = null;
  73904. }
  73905. };
  73906. FreeCameraTouchInput.prototype.checkInputs = function () {
  73907. if (this._offsetX && this._offsetY) {
  73908. var camera = this.camera;
  73909. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  73910. if (this._pointerPressed.length > 1) {
  73911. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  73912. }
  73913. else {
  73914. var speed = camera._computeLocalCameraSpeed();
  73915. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  73916. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  73917. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  73918. }
  73919. }
  73920. };
  73921. FreeCameraTouchInput.prototype.getClassName = function () {
  73922. return "FreeCameraTouchInput";
  73923. };
  73924. FreeCameraTouchInput.prototype.getSimpleName = function () {
  73925. return "touch";
  73926. };
  73927. __decorate([
  73928. BABYLON.serialize()
  73929. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  73930. __decorate([
  73931. BABYLON.serialize()
  73932. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  73933. return FreeCameraTouchInput;
  73934. }());
  73935. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  73936. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  73937. })(BABYLON || (BABYLON = {}));
  73938. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  73939. var BABYLON;
  73940. (function (BABYLON) {
  73941. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  73942. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  73943. });
  73944. // We're mainly based on the logic defined into the FreeCamera code
  73945. var TouchCamera = /** @class */ (function (_super) {
  73946. __extends(TouchCamera, _super);
  73947. //-- end properties for backward compatibility for inputs
  73948. function TouchCamera(name, position, scene) {
  73949. var _this = _super.call(this, name, position, scene) || this;
  73950. _this.inputs.addTouch();
  73951. _this._setupInputs();
  73952. return _this;
  73953. }
  73954. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  73955. //-- Begin properties for backward compatibility for inputs
  73956. get: function () {
  73957. var touch = this.inputs.attached["touch"];
  73958. if (touch)
  73959. return touch.touchAngularSensibility;
  73960. return 0;
  73961. },
  73962. set: function (value) {
  73963. var touch = this.inputs.attached["touch"];
  73964. if (touch)
  73965. touch.touchAngularSensibility = value;
  73966. },
  73967. enumerable: true,
  73968. configurable: true
  73969. });
  73970. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  73971. get: function () {
  73972. var touch = this.inputs.attached["touch"];
  73973. if (touch)
  73974. return touch.touchMoveSensibility;
  73975. return 0;
  73976. },
  73977. set: function (value) {
  73978. var touch = this.inputs.attached["touch"];
  73979. if (touch)
  73980. touch.touchMoveSensibility = value;
  73981. },
  73982. enumerable: true,
  73983. configurable: true
  73984. });
  73985. TouchCamera.prototype.getClassName = function () {
  73986. return "TouchCamera";
  73987. };
  73988. /** @hidden */
  73989. TouchCamera.prototype._setupInputs = function () {
  73990. var mouse = this.inputs.attached["mouse"];
  73991. if (mouse) {
  73992. mouse.touchEnabled = false;
  73993. }
  73994. };
  73995. return TouchCamera;
  73996. }(BABYLON.FreeCamera));
  73997. BABYLON.TouchCamera = TouchCamera;
  73998. })(BABYLON || (BABYLON = {}));
  73999. //# sourceMappingURL=babylon.touchCamera.js.map
  74000. var BABYLON;
  74001. (function (BABYLON) {
  74002. var ProceduralTexture = /** @class */ (function (_super) {
  74003. __extends(ProceduralTexture, _super);
  74004. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  74005. if (fallbackTexture === void 0) { fallbackTexture = null; }
  74006. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74007. if (isCube === void 0) { isCube = false; }
  74008. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  74009. _this.isCube = isCube;
  74010. _this.isEnabled = true;
  74011. _this._currentRefreshId = -1;
  74012. _this._refreshRate = 1;
  74013. _this._vertexBuffers = {};
  74014. _this._uniforms = new Array();
  74015. _this._samplers = new Array();
  74016. /** @hidden */
  74017. _this._textures = {};
  74018. _this._floats = {};
  74019. _this._ints = {};
  74020. _this._floatsArrays = {};
  74021. _this._colors3 = {};
  74022. _this._colors4 = {};
  74023. _this._vectors2 = {};
  74024. _this._vectors3 = {};
  74025. _this._matrices = {};
  74026. _this._fallbackTextureUsed = false;
  74027. _this._cachedDefines = "";
  74028. scene = _this.getScene();
  74029. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  74030. if (!component) {
  74031. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  74032. scene._addComponent(component);
  74033. }
  74034. scene.proceduralTextures.push(_this);
  74035. _this._engine = scene.getEngine();
  74036. _this.name = name;
  74037. _this.isRenderTarget = true;
  74038. _this._size = size;
  74039. _this._generateMipMaps = generateMipMaps;
  74040. _this.setFragment(fragment);
  74041. _this._fallbackTexture = fallbackTexture;
  74042. if (isCube) {
  74043. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  74044. _this.setFloat("face", 0);
  74045. }
  74046. else {
  74047. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  74048. }
  74049. // VBO
  74050. var vertices = [];
  74051. vertices.push(1, 1);
  74052. vertices.push(-1, 1);
  74053. vertices.push(-1, -1);
  74054. vertices.push(1, -1);
  74055. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74056. _this._createIndexBuffer();
  74057. return _this;
  74058. }
  74059. ProceduralTexture.prototype._createIndexBuffer = function () {
  74060. var engine = this._engine;
  74061. // Indices
  74062. var indices = [];
  74063. indices.push(0);
  74064. indices.push(1);
  74065. indices.push(2);
  74066. indices.push(0);
  74067. indices.push(2);
  74068. indices.push(3);
  74069. this._indexBuffer = engine.createIndexBuffer(indices);
  74070. };
  74071. /** @hidden */
  74072. ProceduralTexture.prototype._rebuild = function () {
  74073. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74074. if (vb) {
  74075. vb._rebuild();
  74076. }
  74077. this._createIndexBuffer();
  74078. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74079. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74080. }
  74081. };
  74082. ProceduralTexture.prototype.reset = function () {
  74083. if (this._effect === undefined) {
  74084. return;
  74085. }
  74086. var engine = this._engine;
  74087. engine._releaseEffect(this._effect);
  74088. };
  74089. ProceduralTexture.prototype._getDefines = function () {
  74090. return "";
  74091. };
  74092. ProceduralTexture.prototype.isReady = function () {
  74093. var _this = this;
  74094. var engine = this._engine;
  74095. var shaders;
  74096. if (!this._fragment) {
  74097. return false;
  74098. }
  74099. if (this._fallbackTextureUsed) {
  74100. return true;
  74101. }
  74102. var defines = this._getDefines();
  74103. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  74104. return true;
  74105. }
  74106. if (this._fragment.fragmentElement !== undefined) {
  74107. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  74108. }
  74109. else {
  74110. shaders = { vertex: "procedural", fragment: this._fragment };
  74111. }
  74112. this._cachedDefines = defines;
  74113. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  74114. _this.releaseInternalTexture();
  74115. if (_this._fallbackTexture) {
  74116. _this._texture = _this._fallbackTexture._texture;
  74117. if (_this._texture) {
  74118. _this._texture.incrementReferences();
  74119. }
  74120. }
  74121. _this._fallbackTextureUsed = true;
  74122. });
  74123. return this._effect.isReady();
  74124. };
  74125. ProceduralTexture.prototype.resetRefreshCounter = function () {
  74126. this._currentRefreshId = -1;
  74127. };
  74128. ProceduralTexture.prototype.setFragment = function (fragment) {
  74129. this._fragment = fragment;
  74130. };
  74131. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  74132. get: function () {
  74133. return this._refreshRate;
  74134. },
  74135. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74136. set: function (value) {
  74137. this._refreshRate = value;
  74138. this.resetRefreshCounter();
  74139. },
  74140. enumerable: true,
  74141. configurable: true
  74142. });
  74143. /** @hidden */
  74144. ProceduralTexture.prototype._shouldRender = function () {
  74145. if (!this.isEnabled || !this.isReady() || !this._texture) {
  74146. return false;
  74147. }
  74148. if (this._fallbackTextureUsed) {
  74149. return false;
  74150. }
  74151. if (this._currentRefreshId === -1) { // At least render once
  74152. this._currentRefreshId = 1;
  74153. return true;
  74154. }
  74155. if (this.refreshRate === this._currentRefreshId) {
  74156. this._currentRefreshId = 1;
  74157. return true;
  74158. }
  74159. this._currentRefreshId++;
  74160. return false;
  74161. };
  74162. ProceduralTexture.prototype.getRenderSize = function () {
  74163. return this._size;
  74164. };
  74165. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  74166. if (this._fallbackTextureUsed) {
  74167. return;
  74168. }
  74169. this.releaseInternalTexture();
  74170. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  74171. // Update properties
  74172. this._size = size;
  74173. this._generateMipMaps = generateMipMaps;
  74174. };
  74175. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  74176. if (this._uniforms.indexOf(uniformName) === -1) {
  74177. this._uniforms.push(uniformName);
  74178. }
  74179. };
  74180. ProceduralTexture.prototype.setTexture = function (name, texture) {
  74181. if (this._samplers.indexOf(name) === -1) {
  74182. this._samplers.push(name);
  74183. }
  74184. this._textures[name] = texture;
  74185. return this;
  74186. };
  74187. ProceduralTexture.prototype.setFloat = function (name, value) {
  74188. this._checkUniform(name);
  74189. this._floats[name] = value;
  74190. return this;
  74191. };
  74192. /**
  74193. * Set the value of an uniform to an integer value
  74194. * @param name defines the name of the uniform
  74195. * @param value defines the value to set
  74196. * @returns the current procedural texture
  74197. */
  74198. ProceduralTexture.prototype.setInt = function (name, value) {
  74199. this._checkUniform(name);
  74200. this._ints[name] = value;
  74201. return this;
  74202. };
  74203. ProceduralTexture.prototype.setFloats = function (name, value) {
  74204. this._checkUniform(name);
  74205. this._floatsArrays[name] = value;
  74206. return this;
  74207. };
  74208. ProceduralTexture.prototype.setColor3 = function (name, value) {
  74209. this._checkUniform(name);
  74210. this._colors3[name] = value;
  74211. return this;
  74212. };
  74213. ProceduralTexture.prototype.setColor4 = function (name, value) {
  74214. this._checkUniform(name);
  74215. this._colors4[name] = value;
  74216. return this;
  74217. };
  74218. ProceduralTexture.prototype.setVector2 = function (name, value) {
  74219. this._checkUniform(name);
  74220. this._vectors2[name] = value;
  74221. return this;
  74222. };
  74223. ProceduralTexture.prototype.setVector3 = function (name, value) {
  74224. this._checkUniform(name);
  74225. this._vectors3[name] = value;
  74226. return this;
  74227. };
  74228. ProceduralTexture.prototype.setMatrix = function (name, value) {
  74229. this._checkUniform(name);
  74230. this._matrices[name] = value;
  74231. return this;
  74232. };
  74233. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74234. var scene = this.getScene();
  74235. if (!scene) {
  74236. return;
  74237. }
  74238. var engine = this._engine;
  74239. // Render
  74240. engine.enableEffect(this._effect);
  74241. engine.setState(false);
  74242. // Texture
  74243. for (var name in this._textures) {
  74244. this._effect.setTexture(name, this._textures[name]);
  74245. }
  74246. // Float
  74247. for (name in this._ints) {
  74248. this._effect.setInt(name, this._ints[name]);
  74249. }
  74250. // Float
  74251. for (name in this._floats) {
  74252. this._effect.setFloat(name, this._floats[name]);
  74253. }
  74254. // Floats
  74255. for (name in this._floatsArrays) {
  74256. this._effect.setArray(name, this._floatsArrays[name]);
  74257. }
  74258. // Color3
  74259. for (name in this._colors3) {
  74260. this._effect.setColor3(name, this._colors3[name]);
  74261. }
  74262. // Color4
  74263. for (name in this._colors4) {
  74264. var color = this._colors4[name];
  74265. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  74266. }
  74267. // Vector2
  74268. for (name in this._vectors2) {
  74269. this._effect.setVector2(name, this._vectors2[name]);
  74270. }
  74271. // Vector3
  74272. for (name in this._vectors3) {
  74273. this._effect.setVector3(name, this._vectors3[name]);
  74274. }
  74275. // Matrix
  74276. for (name in this._matrices) {
  74277. this._effect.setMatrix(name, this._matrices[name]);
  74278. }
  74279. if (!this._texture) {
  74280. return;
  74281. }
  74282. if (this.isCube) {
  74283. for (var face = 0; face < 6; face++) {
  74284. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  74285. // VBOs
  74286. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74287. this._effect.setFloat("face", face);
  74288. // Clear
  74289. engine.clear(scene.clearColor, true, true, true);
  74290. // Draw order
  74291. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74292. // Mipmaps
  74293. if (face === 5) {
  74294. engine.generateMipMapsForCubemap(this._texture);
  74295. }
  74296. }
  74297. }
  74298. else {
  74299. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  74300. // VBOs
  74301. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74302. // Clear
  74303. engine.clear(scene.clearColor, true, true, true);
  74304. // Draw order
  74305. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74306. }
  74307. // Unbind
  74308. engine.unBindFramebuffer(this._texture, this.isCube);
  74309. if (this.onGenerated) {
  74310. this.onGenerated();
  74311. }
  74312. };
  74313. ProceduralTexture.prototype.clone = function () {
  74314. var textureSize = this.getSize();
  74315. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  74316. // Base texture
  74317. newTexture.hasAlpha = this.hasAlpha;
  74318. newTexture.level = this.level;
  74319. // RenderTarget Texture
  74320. newTexture.coordinatesMode = this.coordinatesMode;
  74321. return newTexture;
  74322. };
  74323. ProceduralTexture.prototype.dispose = function () {
  74324. var scene = this.getScene();
  74325. if (!scene) {
  74326. return;
  74327. }
  74328. var index = scene.proceduralTextures.indexOf(this);
  74329. if (index >= 0) {
  74330. scene.proceduralTextures.splice(index, 1);
  74331. }
  74332. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74333. if (vertexBuffer) {
  74334. vertexBuffer.dispose();
  74335. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74336. }
  74337. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  74338. this._indexBuffer = null;
  74339. }
  74340. _super.prototype.dispose.call(this);
  74341. };
  74342. __decorate([
  74343. BABYLON.serialize()
  74344. ], ProceduralTexture.prototype, "_size", void 0);
  74345. __decorate([
  74346. BABYLON.serialize()
  74347. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  74348. __decorate([
  74349. BABYLON.serialize()
  74350. ], ProceduralTexture.prototype, "isEnabled", void 0);
  74351. __decorate([
  74352. BABYLON.serialize()
  74353. ], ProceduralTexture.prototype, "refreshRate", null);
  74354. return ProceduralTexture;
  74355. }(BABYLON.Texture));
  74356. BABYLON.ProceduralTexture = ProceduralTexture;
  74357. })(BABYLON || (BABYLON = {}));
  74358. //# sourceMappingURL=babylon.proceduralTexture.js.map
  74359. var BABYLON;
  74360. (function (BABYLON) {
  74361. /**
  74362. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  74363. * in a given scene.
  74364. */
  74365. var ProceduralTextureSceneComponent = /** @class */ (function () {
  74366. /**
  74367. * Creates a new instance of the component for the given scene
  74368. * @param scene Defines the scene to register the component in
  74369. */
  74370. function ProceduralTextureSceneComponent(scene) {
  74371. /**
  74372. * The component name helpfull to identify the component in the list of scene components.
  74373. */
  74374. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  74375. this.scene = scene;
  74376. this.scene.proceduralTextures = new Array();
  74377. scene.layers = new Array();
  74378. }
  74379. /**
  74380. * Registers the component in a given scene
  74381. */
  74382. ProceduralTextureSceneComponent.prototype.register = function () {
  74383. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  74384. };
  74385. /**
  74386. * Rebuilds the elements related to this component in case of
  74387. * context lost for instance.
  74388. */
  74389. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  74390. // Nothing to do here.
  74391. };
  74392. /**
  74393. * Disposes the component and the associated ressources.
  74394. */
  74395. ProceduralTextureSceneComponent.prototype.dispose = function () {
  74396. // Nothing to do here.
  74397. };
  74398. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  74399. if (this.scene.proceduralTexturesEnabled) {
  74400. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74401. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  74402. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  74403. if (proceduralTexture._shouldRender()) {
  74404. proceduralTexture.render();
  74405. }
  74406. }
  74407. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74408. }
  74409. };
  74410. return ProceduralTextureSceneComponent;
  74411. }());
  74412. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  74413. })(BABYLON || (BABYLON = {}));
  74414. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  74415. var BABYLON;
  74416. (function (BABYLON) {
  74417. var CustomProceduralTexture = /** @class */ (function (_super) {
  74418. __extends(CustomProceduralTexture, _super);
  74419. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  74420. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  74421. _this._animate = true;
  74422. _this._time = 0;
  74423. _this._texturePath = texturePath;
  74424. //Try to load json
  74425. _this.loadJson(texturePath);
  74426. _this.refreshRate = 1;
  74427. return _this;
  74428. }
  74429. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  74430. var _this = this;
  74431. var noConfigFile = function () {
  74432. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  74433. try {
  74434. _this.setFragment(_this._texturePath);
  74435. }
  74436. catch (ex) {
  74437. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  74438. }
  74439. };
  74440. var configFileUrl = jsonUrl + "/config.json";
  74441. var xhr = new XMLHttpRequest();
  74442. xhr.open("GET", configFileUrl, true);
  74443. xhr.addEventListener("load", function () {
  74444. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  74445. try {
  74446. _this._config = JSON.parse(xhr.response);
  74447. _this.updateShaderUniforms();
  74448. _this.updateTextures();
  74449. _this.setFragment(_this._texturePath + "/custom");
  74450. _this._animate = _this._config.animate;
  74451. _this.refreshRate = _this._config.refreshrate;
  74452. }
  74453. catch (ex) {
  74454. noConfigFile();
  74455. }
  74456. }
  74457. else {
  74458. noConfigFile();
  74459. }
  74460. }, false);
  74461. xhr.addEventListener("error", function () {
  74462. noConfigFile();
  74463. }, false);
  74464. try {
  74465. xhr.send();
  74466. }
  74467. catch (ex) {
  74468. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  74469. }
  74470. };
  74471. CustomProceduralTexture.prototype.isReady = function () {
  74472. if (!_super.prototype.isReady.call(this)) {
  74473. return false;
  74474. }
  74475. for (var name in this._textures) {
  74476. var texture = this._textures[name];
  74477. if (!texture.isReady()) {
  74478. return false;
  74479. }
  74480. }
  74481. return true;
  74482. };
  74483. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74484. var scene = this.getScene();
  74485. if (this._animate && scene) {
  74486. this._time += scene.getAnimationRatio() * 0.03;
  74487. this.updateShaderUniforms();
  74488. }
  74489. _super.prototype.render.call(this, useCameraPostProcess);
  74490. };
  74491. CustomProceduralTexture.prototype.updateTextures = function () {
  74492. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  74493. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  74494. }
  74495. };
  74496. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  74497. if (this._config) {
  74498. for (var j = 0; j < this._config.uniforms.length; j++) {
  74499. var uniform = this._config.uniforms[j];
  74500. switch (uniform.type) {
  74501. case "float":
  74502. this.setFloat(uniform.name, uniform.value);
  74503. break;
  74504. case "color3":
  74505. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  74506. break;
  74507. case "color4":
  74508. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  74509. break;
  74510. case "vector2":
  74511. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  74512. break;
  74513. case "vector3":
  74514. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  74515. break;
  74516. }
  74517. }
  74518. }
  74519. this.setFloat("time", this._time);
  74520. };
  74521. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  74522. get: function () {
  74523. return this._animate;
  74524. },
  74525. set: function (value) {
  74526. this._animate = value;
  74527. },
  74528. enumerable: true,
  74529. configurable: true
  74530. });
  74531. return CustomProceduralTexture;
  74532. }(BABYLON.ProceduralTexture));
  74533. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  74534. })(BABYLON || (BABYLON = {}));
  74535. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  74536. var BABYLON;
  74537. (function (BABYLON) {
  74538. var FreeCameraGamepadInput = /** @class */ (function () {
  74539. function FreeCameraGamepadInput() {
  74540. this.gamepadAngularSensibility = 200;
  74541. this.gamepadMoveSensibility = 40;
  74542. // private members
  74543. this._cameraTransform = BABYLON.Matrix.Identity();
  74544. this._deltaTransform = BABYLON.Vector3.Zero();
  74545. this._vector3 = BABYLON.Vector3.Zero();
  74546. this._vector2 = BABYLON.Vector2.Zero();
  74547. }
  74548. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74549. var _this = this;
  74550. var manager = this.camera.getScene().gamepadManager;
  74551. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74552. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74553. // prioritize XBOX gamepads.
  74554. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74555. _this.gamepad = gamepad;
  74556. }
  74557. }
  74558. });
  74559. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74560. if (_this.gamepad === gamepad) {
  74561. _this.gamepad = null;
  74562. }
  74563. });
  74564. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74565. };
  74566. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  74567. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74568. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74569. this.gamepad = null;
  74570. };
  74571. FreeCameraGamepadInput.prototype.checkInputs = function () {
  74572. if (this.gamepad && this.gamepad.leftStick) {
  74573. var camera = this.camera;
  74574. var LSValues = this.gamepad.leftStick;
  74575. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  74576. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74577. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  74578. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  74579. var RSValues = this.gamepad.rightStick;
  74580. if (RSValues) {
  74581. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  74582. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  74583. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  74584. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  74585. }
  74586. else {
  74587. RSValues = { x: 0, y: 0 };
  74588. }
  74589. if (!camera.rotationQuaternion) {
  74590. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  74591. }
  74592. else {
  74593. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  74594. }
  74595. var speed = camera._computeLocalCameraSpeed() * 50.0;
  74596. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  74597. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  74598. camera.cameraDirection.addInPlace(this._deltaTransform);
  74599. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  74600. camera.cameraRotation.addInPlace(this._vector2);
  74601. }
  74602. };
  74603. FreeCameraGamepadInput.prototype.getClassName = function () {
  74604. return "FreeCameraGamepadInput";
  74605. };
  74606. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  74607. return "gamepad";
  74608. };
  74609. __decorate([
  74610. BABYLON.serialize()
  74611. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  74612. __decorate([
  74613. BABYLON.serialize()
  74614. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74615. return FreeCameraGamepadInput;
  74616. }());
  74617. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  74618. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  74619. })(BABYLON || (BABYLON = {}));
  74620. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  74621. var BABYLON;
  74622. (function (BABYLON) {
  74623. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  74624. function ArcRotateCameraGamepadInput() {
  74625. this.gamepadRotationSensibility = 80;
  74626. this.gamepadMoveSensibility = 40;
  74627. }
  74628. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74629. var _this = this;
  74630. var manager = this.camera.getScene().gamepadManager;
  74631. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74632. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74633. // prioritize XBOX gamepads.
  74634. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74635. _this.gamepad = gamepad;
  74636. }
  74637. }
  74638. });
  74639. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74640. if (_this.gamepad === gamepad) {
  74641. _this.gamepad = null;
  74642. }
  74643. });
  74644. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74645. };
  74646. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  74647. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74648. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74649. this.gamepad = null;
  74650. };
  74651. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  74652. if (this.gamepad) {
  74653. var camera = this.camera;
  74654. var RSValues = this.gamepad.rightStick;
  74655. if (RSValues) {
  74656. if (RSValues.x != 0) {
  74657. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  74658. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  74659. camera.inertialAlphaOffset += normalizedRX;
  74660. }
  74661. }
  74662. if (RSValues.y != 0) {
  74663. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  74664. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  74665. camera.inertialBetaOffset += normalizedRY;
  74666. }
  74667. }
  74668. }
  74669. var LSValues = this.gamepad.leftStick;
  74670. if (LSValues && LSValues.y != 0) {
  74671. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74672. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  74673. this.camera.inertialRadiusOffset -= normalizedLY;
  74674. }
  74675. }
  74676. }
  74677. };
  74678. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  74679. return "ArcRotateCameraGamepadInput";
  74680. };
  74681. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  74682. return "gamepad";
  74683. };
  74684. __decorate([
  74685. BABYLON.serialize()
  74686. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  74687. __decorate([
  74688. BABYLON.serialize()
  74689. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74690. return ArcRotateCameraGamepadInput;
  74691. }());
  74692. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  74693. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  74694. })(BABYLON || (BABYLON = {}));
  74695. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  74696. var BABYLON;
  74697. (function (BABYLON) {
  74698. var GamepadManager = /** @class */ (function () {
  74699. function GamepadManager(_scene) {
  74700. var _this = this;
  74701. this._scene = _scene;
  74702. this._babylonGamepads = [];
  74703. this._oneGamepadConnected = false;
  74704. /** @hidden */
  74705. this._isMonitoring = false;
  74706. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  74707. if (!BABYLON.Tools.IsWindowObjectExist()) {
  74708. this._gamepadEventSupported = false;
  74709. }
  74710. else {
  74711. this._gamepadEventSupported = 'GamepadEvent' in window;
  74712. this._gamepadSupport = (navigator.getGamepads ||
  74713. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  74714. }
  74715. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  74716. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  74717. for (var i in _this._babylonGamepads) {
  74718. var gamepad = _this._babylonGamepads[i];
  74719. if (gamepad && gamepad._isConnected) {
  74720. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  74721. }
  74722. }
  74723. });
  74724. this._onGamepadConnectedEvent = function (evt) {
  74725. var gamepad = evt.gamepad;
  74726. if (gamepad.index in _this._babylonGamepads) {
  74727. if (_this._babylonGamepads[gamepad.index].isConnected) {
  74728. return;
  74729. }
  74730. }
  74731. var newGamepad;
  74732. if (_this._babylonGamepads[gamepad.index]) {
  74733. newGamepad = _this._babylonGamepads[gamepad.index];
  74734. newGamepad.browserGamepad = gamepad;
  74735. newGamepad._isConnected = true;
  74736. }
  74737. else {
  74738. newGamepad = _this._addNewGamepad(gamepad);
  74739. }
  74740. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74741. _this._startMonitoringGamepads();
  74742. };
  74743. this._onGamepadDisconnectedEvent = function (evt) {
  74744. var gamepad = evt.gamepad;
  74745. // Remove the gamepad from the list of gamepads to monitor.
  74746. for (var i in _this._babylonGamepads) {
  74747. if (_this._babylonGamepads[i].index === gamepad.index) {
  74748. var disconnectedGamepad = _this._babylonGamepads[i];
  74749. disconnectedGamepad._isConnected = false;
  74750. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  74751. break;
  74752. }
  74753. }
  74754. };
  74755. if (this._gamepadSupport) {
  74756. //first add already-connected gamepads
  74757. this._updateGamepadObjects();
  74758. if (this._babylonGamepads.length) {
  74759. this._startMonitoringGamepads();
  74760. }
  74761. // Checking if the gamepad connected event is supported (like in Firefox)
  74762. if (this._gamepadEventSupported) {
  74763. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  74764. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  74765. }
  74766. else {
  74767. this._startMonitoringGamepads();
  74768. }
  74769. }
  74770. }
  74771. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  74772. get: function () {
  74773. return this._babylonGamepads;
  74774. },
  74775. enumerable: true,
  74776. configurable: true
  74777. });
  74778. GamepadManager.prototype.getGamepadByType = function (type) {
  74779. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  74780. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  74781. var gamepad = _a[_i];
  74782. if (gamepad && gamepad.type === type) {
  74783. return gamepad;
  74784. }
  74785. }
  74786. return null;
  74787. };
  74788. GamepadManager.prototype.dispose = function () {
  74789. if (this._gamepadEventSupported) {
  74790. if (this._onGamepadConnectedEvent) {
  74791. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  74792. }
  74793. if (this._onGamepadDisconnectedEvent) {
  74794. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  74795. }
  74796. this._onGamepadConnectedEvent = null;
  74797. this._onGamepadDisconnectedEvent = null;
  74798. }
  74799. this._babylonGamepads.forEach(function (gamepad) {
  74800. gamepad.dispose();
  74801. });
  74802. this.onGamepadConnectedObservable.clear();
  74803. this.onGamepadDisconnectedObservable.clear();
  74804. this._oneGamepadConnected = false;
  74805. this._stopMonitoringGamepads();
  74806. this._babylonGamepads = [];
  74807. };
  74808. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  74809. if (!this._oneGamepadConnected) {
  74810. this._oneGamepadConnected = true;
  74811. }
  74812. var newGamepad;
  74813. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  74814. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  74815. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  74816. }
  74817. // if pose is supported, use the (WebVR) pose enabled controller
  74818. else if (gamepad.pose) {
  74819. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  74820. }
  74821. else {
  74822. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  74823. }
  74824. this._babylonGamepads[newGamepad.index] = newGamepad;
  74825. return newGamepad;
  74826. };
  74827. GamepadManager.prototype._startMonitoringGamepads = function () {
  74828. if (!this._isMonitoring) {
  74829. this._isMonitoring = true;
  74830. //back-comp
  74831. if (!this._scene) {
  74832. this._checkGamepadsStatus();
  74833. }
  74834. }
  74835. };
  74836. GamepadManager.prototype._stopMonitoringGamepads = function () {
  74837. this._isMonitoring = false;
  74838. };
  74839. /** @hidden */
  74840. GamepadManager.prototype._checkGamepadsStatus = function () {
  74841. var _this = this;
  74842. // Hack to be compatible Chrome
  74843. this._updateGamepadObjects();
  74844. for (var i in this._babylonGamepads) {
  74845. var gamepad = this._babylonGamepads[i];
  74846. if (!gamepad || !gamepad.isConnected) {
  74847. continue;
  74848. }
  74849. gamepad.update();
  74850. }
  74851. if (this._isMonitoring && !this._scene) {
  74852. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  74853. }
  74854. };
  74855. // This function is called only on Chrome, which does not properly support
  74856. // connection/disconnection events and forces you to recopy again the gamepad object
  74857. GamepadManager.prototype._updateGamepadObjects = function () {
  74858. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  74859. for (var i = 0; i < gamepads.length; i++) {
  74860. var gamepad = gamepads[i];
  74861. if (gamepad) {
  74862. if (!this._babylonGamepads[gamepad.index]) {
  74863. var newGamepad = this._addNewGamepad(gamepad);
  74864. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74865. }
  74866. else {
  74867. // Forced to copy again this object for Chrome for unknown reason
  74868. this._babylonGamepads[i].browserGamepad = gamepad;
  74869. if (!this._babylonGamepads[i].isConnected) {
  74870. this._babylonGamepads[i]._isConnected = true;
  74871. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  74872. }
  74873. }
  74874. }
  74875. }
  74876. };
  74877. return GamepadManager;
  74878. }());
  74879. BABYLON.GamepadManager = GamepadManager;
  74880. })(BABYLON || (BABYLON = {}));
  74881. //# sourceMappingURL=babylon.gamepadManager.js.map
  74882. var BABYLON;
  74883. (function (BABYLON) {
  74884. var StickValues = /** @class */ (function () {
  74885. function StickValues(x, y) {
  74886. this.x = x;
  74887. this.y = y;
  74888. }
  74889. return StickValues;
  74890. }());
  74891. BABYLON.StickValues = StickValues;
  74892. var Gamepad = /** @class */ (function () {
  74893. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  74894. if (leftStickX === void 0) { leftStickX = 0; }
  74895. if (leftStickY === void 0) { leftStickY = 1; }
  74896. if (rightStickX === void 0) { rightStickX = 2; }
  74897. if (rightStickY === void 0) { rightStickY = 3; }
  74898. this.id = id;
  74899. this.index = index;
  74900. this.browserGamepad = browserGamepad;
  74901. this._leftStick = { x: 0, y: 0 };
  74902. this._rightStick = { x: 0, y: 0 };
  74903. /** @hidden */
  74904. this._isConnected = true;
  74905. this._invertLeftStickY = false;
  74906. this.type = Gamepad.GAMEPAD;
  74907. this._leftStickAxisX = leftStickX;
  74908. this._leftStickAxisY = leftStickY;
  74909. this._rightStickAxisX = rightStickX;
  74910. this._rightStickAxisY = rightStickY;
  74911. if (this.browserGamepad.axes.length >= 2) {
  74912. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74913. }
  74914. if (this.browserGamepad.axes.length >= 4) {
  74915. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74916. }
  74917. }
  74918. Object.defineProperty(Gamepad.prototype, "isConnected", {
  74919. get: function () {
  74920. return this._isConnected;
  74921. },
  74922. enumerable: true,
  74923. configurable: true
  74924. });
  74925. Gamepad.prototype.onleftstickchanged = function (callback) {
  74926. this._onleftstickchanged = callback;
  74927. };
  74928. Gamepad.prototype.onrightstickchanged = function (callback) {
  74929. this._onrightstickchanged = callback;
  74930. };
  74931. Object.defineProperty(Gamepad.prototype, "leftStick", {
  74932. get: function () {
  74933. return this._leftStick;
  74934. },
  74935. set: function (newValues) {
  74936. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  74937. this._onleftstickchanged(newValues);
  74938. }
  74939. this._leftStick = newValues;
  74940. },
  74941. enumerable: true,
  74942. configurable: true
  74943. });
  74944. Object.defineProperty(Gamepad.prototype, "rightStick", {
  74945. get: function () {
  74946. return this._rightStick;
  74947. },
  74948. set: function (newValues) {
  74949. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  74950. this._onrightstickchanged(newValues);
  74951. }
  74952. this._rightStick = newValues;
  74953. },
  74954. enumerable: true,
  74955. configurable: true
  74956. });
  74957. Gamepad.prototype.update = function () {
  74958. if (this._leftStick) {
  74959. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74960. if (this._invertLeftStickY) {
  74961. this.leftStick.y *= -1;
  74962. }
  74963. }
  74964. if (this._rightStick) {
  74965. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74966. }
  74967. };
  74968. Gamepad.prototype.dispose = function () {
  74969. };
  74970. Gamepad.GAMEPAD = 0;
  74971. Gamepad.GENERIC = 1;
  74972. Gamepad.XBOX = 2;
  74973. Gamepad.POSE_ENABLED = 3;
  74974. return Gamepad;
  74975. }());
  74976. BABYLON.Gamepad = Gamepad;
  74977. var GenericPad = /** @class */ (function (_super) {
  74978. __extends(GenericPad, _super);
  74979. function GenericPad(id, index, browserGamepad) {
  74980. var _this = _super.call(this, id, index, browserGamepad) || this;
  74981. _this.onButtonDownObservable = new BABYLON.Observable();
  74982. _this.onButtonUpObservable = new BABYLON.Observable();
  74983. _this.type = Gamepad.GENERIC;
  74984. _this._buttons = new Array(browserGamepad.buttons.length);
  74985. return _this;
  74986. }
  74987. GenericPad.prototype.onbuttondown = function (callback) {
  74988. this._onbuttondown = callback;
  74989. };
  74990. GenericPad.prototype.onbuttonup = function (callback) {
  74991. this._onbuttonup = callback;
  74992. };
  74993. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  74994. if (newValue !== currentValue) {
  74995. if (newValue === 1) {
  74996. if (this._onbuttondown) {
  74997. this._onbuttondown(buttonIndex);
  74998. }
  74999. this.onButtonDownObservable.notifyObservers(buttonIndex);
  75000. }
  75001. if (newValue === 0) {
  75002. if (this._onbuttonup) {
  75003. this._onbuttonup(buttonIndex);
  75004. }
  75005. this.onButtonUpObservable.notifyObservers(buttonIndex);
  75006. }
  75007. }
  75008. return newValue;
  75009. };
  75010. GenericPad.prototype.update = function () {
  75011. _super.prototype.update.call(this);
  75012. for (var index = 0; index < this._buttons.length; index++) {
  75013. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  75014. }
  75015. };
  75016. GenericPad.prototype.dispose = function () {
  75017. _super.prototype.dispose.call(this);
  75018. this.onButtonDownObservable.clear();
  75019. this.onButtonUpObservable.clear();
  75020. };
  75021. return GenericPad;
  75022. }(Gamepad));
  75023. BABYLON.GenericPad = GenericPad;
  75024. })(BABYLON || (BABYLON = {}));
  75025. //# sourceMappingURL=babylon.gamepad.js.map
  75026. var BABYLON;
  75027. (function (BABYLON) {
  75028. /**
  75029. * Defines supported buttons for XBox360 compatible gamepads
  75030. */
  75031. var Xbox360Button;
  75032. (function (Xbox360Button) {
  75033. /** A */
  75034. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  75035. /** B */
  75036. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  75037. /** X */
  75038. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  75039. /** Y */
  75040. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  75041. /** Start */
  75042. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  75043. /** Back */
  75044. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  75045. /** Left button */
  75046. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  75047. /** Right button */
  75048. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  75049. /** Left stick */
  75050. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  75051. /** Right stick */
  75052. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  75053. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  75054. /** Defines values for XBox360 DPad */
  75055. var Xbox360Dpad;
  75056. (function (Xbox360Dpad) {
  75057. /** Up */
  75058. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  75059. /** Down */
  75060. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  75061. /** Left */
  75062. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  75063. /** Right */
  75064. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  75065. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  75066. /**
  75067. * Defines a XBox360 gamepad
  75068. */
  75069. var Xbox360Pad = /** @class */ (function (_super) {
  75070. __extends(Xbox360Pad, _super);
  75071. /**
  75072. * Creates a new XBox360 gamepad object
  75073. * @param id defines the id of this gamepad
  75074. * @param index defines its index
  75075. * @param gamepad defines the internal HTML gamepad object
  75076. * @param xboxOne defines if it is a XBox One gamepad
  75077. */
  75078. function Xbox360Pad(id, index, gamepad, xboxOne) {
  75079. if (xboxOne === void 0) { xboxOne = false; }
  75080. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  75081. _this._leftTrigger = 0;
  75082. _this._rightTrigger = 0;
  75083. /** Observable raised when a button is pressed */
  75084. _this.onButtonDownObservable = new BABYLON.Observable();
  75085. /** Observable raised when a button is released */
  75086. _this.onButtonUpObservable = new BABYLON.Observable();
  75087. /** Observable raised when a pad is pressed */
  75088. _this.onPadDownObservable = new BABYLON.Observable();
  75089. /** Observable raised when a pad is released */
  75090. _this.onPadUpObservable = new BABYLON.Observable();
  75091. _this._buttonA = 0;
  75092. _this._buttonB = 0;
  75093. _this._buttonX = 0;
  75094. _this._buttonY = 0;
  75095. _this._buttonBack = 0;
  75096. _this._buttonStart = 0;
  75097. _this._buttonLB = 0;
  75098. _this._buttonRB = 0;
  75099. _this._buttonLeftStick = 0;
  75100. _this._buttonRightStick = 0;
  75101. _this._dPadUp = 0;
  75102. _this._dPadDown = 0;
  75103. _this._dPadLeft = 0;
  75104. _this._dPadRight = 0;
  75105. _this._isXboxOnePad = false;
  75106. _this.type = BABYLON.Gamepad.XBOX;
  75107. _this._isXboxOnePad = xboxOne;
  75108. return _this;
  75109. }
  75110. /**
  75111. * Defines the callback to call when left trigger is pressed
  75112. * @param callback defines the callback to use
  75113. */
  75114. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  75115. this._onlefttriggerchanged = callback;
  75116. };
  75117. /**
  75118. * Defines the callback to call when right trigger is pressed
  75119. * @param callback defines the callback to use
  75120. */
  75121. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  75122. this._onrighttriggerchanged = callback;
  75123. };
  75124. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  75125. /**
  75126. * Gets or sets left trigger value
  75127. */
  75128. get: function () {
  75129. return this._leftTrigger;
  75130. },
  75131. set: function (newValue) {
  75132. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  75133. this._onlefttriggerchanged(newValue);
  75134. }
  75135. this._leftTrigger = newValue;
  75136. },
  75137. enumerable: true,
  75138. configurable: true
  75139. });
  75140. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  75141. /**
  75142. * Gets or sets right trigger value
  75143. */
  75144. get: function () {
  75145. return this._rightTrigger;
  75146. },
  75147. set: function (newValue) {
  75148. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  75149. this._onrighttriggerchanged(newValue);
  75150. }
  75151. this._rightTrigger = newValue;
  75152. },
  75153. enumerable: true,
  75154. configurable: true
  75155. });
  75156. /**
  75157. * Defines the callback to call when a button is pressed
  75158. * @param callback defines the callback to use
  75159. */
  75160. Xbox360Pad.prototype.onbuttondown = function (callback) {
  75161. this._onbuttondown = callback;
  75162. };
  75163. /**
  75164. * Defines the callback to call when a button is released
  75165. * @param callback defines the callback to use
  75166. */
  75167. Xbox360Pad.prototype.onbuttonup = function (callback) {
  75168. this._onbuttonup = callback;
  75169. };
  75170. /**
  75171. * Defines the callback to call when a pad is pressed
  75172. * @param callback defines the callback to use
  75173. */
  75174. Xbox360Pad.prototype.ondpaddown = function (callback) {
  75175. this._ondpaddown = callback;
  75176. };
  75177. /**
  75178. * Defines the callback to call when a pad is released
  75179. * @param callback defines the callback to use
  75180. */
  75181. Xbox360Pad.prototype.ondpadup = function (callback) {
  75182. this._ondpadup = callback;
  75183. };
  75184. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  75185. if (newValue !== currentValue) {
  75186. if (newValue === 1) {
  75187. if (this._onbuttondown) {
  75188. this._onbuttondown(buttonType);
  75189. }
  75190. this.onButtonDownObservable.notifyObservers(buttonType);
  75191. }
  75192. if (newValue === 0) {
  75193. if (this._onbuttonup) {
  75194. this._onbuttonup(buttonType);
  75195. }
  75196. this.onButtonUpObservable.notifyObservers(buttonType);
  75197. }
  75198. }
  75199. return newValue;
  75200. };
  75201. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  75202. if (newValue !== currentValue) {
  75203. if (newValue === 1) {
  75204. if (this._ondpaddown) {
  75205. this._ondpaddown(buttonType);
  75206. }
  75207. this.onPadDownObservable.notifyObservers(buttonType);
  75208. }
  75209. if (newValue === 0) {
  75210. if (this._ondpadup) {
  75211. this._ondpadup(buttonType);
  75212. }
  75213. this.onPadUpObservable.notifyObservers(buttonType);
  75214. }
  75215. }
  75216. return newValue;
  75217. };
  75218. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  75219. /** Gets or sets value of A button */
  75220. get: function () {
  75221. return this._buttonA;
  75222. },
  75223. set: function (value) {
  75224. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  75225. },
  75226. enumerable: true,
  75227. configurable: true
  75228. });
  75229. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  75230. /** Gets or sets value of B button */
  75231. get: function () {
  75232. return this._buttonB;
  75233. },
  75234. set: function (value) {
  75235. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  75236. },
  75237. enumerable: true,
  75238. configurable: true
  75239. });
  75240. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  75241. /** Gets or sets value of X button */
  75242. get: function () {
  75243. return this._buttonX;
  75244. },
  75245. set: function (value) {
  75246. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  75247. },
  75248. enumerable: true,
  75249. configurable: true
  75250. });
  75251. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  75252. /** Gets or sets value of Y button */
  75253. get: function () {
  75254. return this._buttonY;
  75255. },
  75256. set: function (value) {
  75257. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  75258. },
  75259. enumerable: true,
  75260. configurable: true
  75261. });
  75262. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  75263. /** Gets or sets value of Start button */
  75264. get: function () {
  75265. return this._buttonStart;
  75266. },
  75267. set: function (value) {
  75268. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  75269. },
  75270. enumerable: true,
  75271. configurable: true
  75272. });
  75273. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  75274. /** Gets or sets value of Back button */
  75275. get: function () {
  75276. return this._buttonBack;
  75277. },
  75278. set: function (value) {
  75279. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  75280. },
  75281. enumerable: true,
  75282. configurable: true
  75283. });
  75284. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  75285. /** Gets or sets value of Left button */
  75286. get: function () {
  75287. return this._buttonLB;
  75288. },
  75289. set: function (value) {
  75290. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  75291. },
  75292. enumerable: true,
  75293. configurable: true
  75294. });
  75295. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  75296. /** Gets or sets value of Right button */
  75297. get: function () {
  75298. return this._buttonRB;
  75299. },
  75300. set: function (value) {
  75301. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  75302. },
  75303. enumerable: true,
  75304. configurable: true
  75305. });
  75306. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  75307. /** Gets or sets value of left stick */
  75308. get: function () {
  75309. return this._buttonLeftStick;
  75310. },
  75311. set: function (value) {
  75312. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  75313. },
  75314. enumerable: true,
  75315. configurable: true
  75316. });
  75317. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  75318. /** Gets or sets value of right stick */
  75319. get: function () {
  75320. return this._buttonRightStick;
  75321. },
  75322. set: function (value) {
  75323. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  75324. },
  75325. enumerable: true,
  75326. configurable: true
  75327. });
  75328. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  75329. /** Gets or sets value of DPad up */
  75330. get: function () {
  75331. return this._dPadUp;
  75332. },
  75333. set: function (value) {
  75334. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  75335. },
  75336. enumerable: true,
  75337. configurable: true
  75338. });
  75339. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  75340. /** Gets or sets value of DPad down */
  75341. get: function () {
  75342. return this._dPadDown;
  75343. },
  75344. set: function (value) {
  75345. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  75346. },
  75347. enumerable: true,
  75348. configurable: true
  75349. });
  75350. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  75351. /** Gets or sets value of DPad left */
  75352. get: function () {
  75353. return this._dPadLeft;
  75354. },
  75355. set: function (value) {
  75356. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  75357. },
  75358. enumerable: true,
  75359. configurable: true
  75360. });
  75361. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  75362. /** Gets or sets value of DPad right */
  75363. get: function () {
  75364. return this._dPadRight;
  75365. },
  75366. set: function (value) {
  75367. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  75368. },
  75369. enumerable: true,
  75370. configurable: true
  75371. });
  75372. /**
  75373. * Force the gamepad to synchronize with device values
  75374. */
  75375. Xbox360Pad.prototype.update = function () {
  75376. _super.prototype.update.call(this);
  75377. if (this._isXboxOnePad) {
  75378. this.buttonA = this.browserGamepad.buttons[0].value;
  75379. this.buttonB = this.browserGamepad.buttons[1].value;
  75380. this.buttonX = this.browserGamepad.buttons[2].value;
  75381. this.buttonY = this.browserGamepad.buttons[3].value;
  75382. this.buttonLB = this.browserGamepad.buttons[4].value;
  75383. this.buttonRB = this.browserGamepad.buttons[5].value;
  75384. this.leftTrigger = this.browserGamepad.axes[2];
  75385. this.rightTrigger = this.browserGamepad.axes[5];
  75386. this.buttonBack = this.browserGamepad.buttons[9].value;
  75387. this.buttonStart = this.browserGamepad.buttons[8].value;
  75388. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  75389. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  75390. this.dPadUp = this.browserGamepad.buttons[11].value;
  75391. this.dPadDown = this.browserGamepad.buttons[12].value;
  75392. this.dPadLeft = this.browserGamepad.buttons[13].value;
  75393. this.dPadRight = this.browserGamepad.buttons[14].value;
  75394. }
  75395. else {
  75396. this.buttonA = this.browserGamepad.buttons[0].value;
  75397. this.buttonB = this.browserGamepad.buttons[1].value;
  75398. this.buttonX = this.browserGamepad.buttons[2].value;
  75399. this.buttonY = this.browserGamepad.buttons[3].value;
  75400. this.buttonLB = this.browserGamepad.buttons[4].value;
  75401. this.buttonRB = this.browserGamepad.buttons[5].value;
  75402. this.leftTrigger = this.browserGamepad.buttons[6].value;
  75403. this.rightTrigger = this.browserGamepad.buttons[7].value;
  75404. this.buttonBack = this.browserGamepad.buttons[8].value;
  75405. this.buttonStart = this.browserGamepad.buttons[9].value;
  75406. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  75407. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  75408. this.dPadUp = this.browserGamepad.buttons[12].value;
  75409. this.dPadDown = this.browserGamepad.buttons[13].value;
  75410. this.dPadLeft = this.browserGamepad.buttons[14].value;
  75411. this.dPadRight = this.browserGamepad.buttons[15].value;
  75412. }
  75413. };
  75414. Xbox360Pad.prototype.dispose = function () {
  75415. _super.prototype.dispose.call(this);
  75416. this.onButtonDownObservable.clear();
  75417. this.onButtonUpObservable.clear();
  75418. this.onPadDownObservable.clear();
  75419. this.onPadUpObservable.clear();
  75420. };
  75421. return Xbox360Pad;
  75422. }(BABYLON.Gamepad));
  75423. BABYLON.Xbox360Pad = Xbox360Pad;
  75424. })(BABYLON || (BABYLON = {}));
  75425. //# sourceMappingURL=babylon.xboxGamepad.js.map
  75426. var BABYLON;
  75427. (function (BABYLON) {
  75428. /**
  75429. * Defines the types of pose enabled controllers that are supported
  75430. */
  75431. var PoseEnabledControllerType;
  75432. (function (PoseEnabledControllerType) {
  75433. /**
  75434. * HTC Vive
  75435. */
  75436. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  75437. /**
  75438. * Oculus Rift
  75439. */
  75440. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  75441. /**
  75442. * Windows mixed reality
  75443. */
  75444. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  75445. /**
  75446. * Samsung gear VR
  75447. */
  75448. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  75449. /**
  75450. * Google Daydream
  75451. */
  75452. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  75453. /**
  75454. * Generic
  75455. */
  75456. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  75457. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  75458. /**
  75459. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75460. */
  75461. var PoseEnabledControllerHelper = /** @class */ (function () {
  75462. function PoseEnabledControllerHelper() {
  75463. }
  75464. /**
  75465. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75466. * @param vrGamepad the gamepad to initialized
  75467. * @returns a vr controller of the type the gamepad identified as
  75468. */
  75469. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  75470. // Oculus Touch
  75471. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  75472. return new BABYLON.OculusTouchController(vrGamepad);
  75473. }
  75474. // Windows Mixed Reality controllers
  75475. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  75476. return new BABYLON.WindowsMotionController(vrGamepad);
  75477. }
  75478. // HTC Vive
  75479. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  75480. return new BABYLON.ViveController(vrGamepad);
  75481. }
  75482. // Samsung/Oculus Gear VR or Oculus Go
  75483. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  75484. return new BABYLON.GearVRController(vrGamepad);
  75485. }
  75486. // Google Daydream
  75487. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  75488. return new BABYLON.DaydreamController(vrGamepad);
  75489. }
  75490. // Generic
  75491. else {
  75492. return new BABYLON.GenericController(vrGamepad);
  75493. }
  75494. };
  75495. return PoseEnabledControllerHelper;
  75496. }());
  75497. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  75498. /**
  75499. * Defines the PoseEnabledController object that contains state of a vr capable controller
  75500. */
  75501. var PoseEnabledController = /** @class */ (function (_super) {
  75502. __extends(PoseEnabledController, _super);
  75503. /**
  75504. * Creates a new PoseEnabledController from a gamepad
  75505. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  75506. */
  75507. function PoseEnabledController(browserGamepad) {
  75508. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  75509. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75510. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75511. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  75512. /**
  75513. * The device position in babylon space
  75514. */
  75515. _this.devicePosition = BABYLON.Vector3.Zero();
  75516. /**
  75517. * The device rotation in babylon space
  75518. */
  75519. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  75520. /**
  75521. * The scale factor of the device in babylon space
  75522. */
  75523. _this.deviceScaleFactor = 1;
  75524. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  75525. /**
  75526. * Internal, matrix used to convert room space to babylon space
  75527. * @hidden
  75528. */
  75529. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75530. /**
  75531. * Node to be used when casting a ray from the controller
  75532. * @hidden
  75533. */
  75534. _this._pointingPoseNode = null;
  75535. _this._workingMatrix = BABYLON.Matrix.Identity();
  75536. /**
  75537. * @hidden
  75538. */
  75539. _this._meshAttachedObservable = new BABYLON.Observable();
  75540. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  75541. _this.controllerType = PoseEnabledControllerType.GENERIC;
  75542. _this.position = BABYLON.Vector3.Zero();
  75543. _this.rotationQuaternion = new BABYLON.Quaternion();
  75544. _this._calculatedPosition = BABYLON.Vector3.Zero();
  75545. _this._calculatedRotation = new BABYLON.Quaternion();
  75546. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  75547. return _this;
  75548. }
  75549. /**
  75550. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  75551. */
  75552. PoseEnabledController.prototype.update = function () {
  75553. _super.prototype.update.call(this);
  75554. this._updatePoseAndMesh();
  75555. };
  75556. /**
  75557. * Updates only the pose device and mesh without doing any button event checking
  75558. */
  75559. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  75560. var pose = this.browserGamepad.pose;
  75561. this.updateFromDevice(pose);
  75562. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  75563. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  75564. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75565. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  75566. if (this._mesh) {
  75567. this._mesh.position.copyFrom(this.devicePosition);
  75568. if (this._mesh.rotationQuaternion) {
  75569. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  75570. }
  75571. }
  75572. };
  75573. /**
  75574. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75575. * @param poseData raw pose fromthe device
  75576. */
  75577. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  75578. if (poseData) {
  75579. this.rawPose = poseData;
  75580. if (poseData.position) {
  75581. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  75582. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  75583. this._deviceRoomPosition.z *= -1;
  75584. }
  75585. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  75586. this._calculatedPosition.addInPlace(this.position);
  75587. }
  75588. var pose = this.rawPose;
  75589. if (poseData.orientation && pose.orientation) {
  75590. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  75591. if (this._mesh) {
  75592. if (this._mesh.getScene().useRightHandedSystem) {
  75593. this._deviceRoomRotationQuaternion.z *= -1;
  75594. this._deviceRoomRotationQuaternion.w *= -1;
  75595. }
  75596. else {
  75597. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  75598. }
  75599. }
  75600. // if the camera is set, rotate to the camera's rotation
  75601. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  75602. }
  75603. }
  75604. };
  75605. /**
  75606. * Attaches a mesh to the controller
  75607. * @param mesh the mesh to be attached
  75608. */
  75609. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  75610. if (this._mesh) {
  75611. this._mesh.parent = null;
  75612. }
  75613. this._mesh = mesh;
  75614. if (this._poseControlledCamera) {
  75615. this._mesh.parent = this._poseControlledCamera;
  75616. }
  75617. if (!this._mesh.rotationQuaternion) {
  75618. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  75619. }
  75620. // 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
  75621. this._updatePoseAndMesh();
  75622. if (this._pointingPoseNode) {
  75623. var parents = [];
  75624. var obj = this._pointingPoseNode;
  75625. while (obj.parent) {
  75626. parents.push(obj.parent);
  75627. obj = obj.parent;
  75628. }
  75629. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  75630. }
  75631. this._meshAttachedObservable.notifyObservers(mesh);
  75632. };
  75633. /**
  75634. * Attaches the controllers mesh to a camera
  75635. * @param camera the camera the mesh should be attached to
  75636. */
  75637. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  75638. this._poseControlledCamera = camera;
  75639. if (this._mesh) {
  75640. this._mesh.parent = this._poseControlledCamera;
  75641. }
  75642. };
  75643. /**
  75644. * Disposes of the controller
  75645. */
  75646. PoseEnabledController.prototype.dispose = function () {
  75647. if (this._mesh) {
  75648. this._mesh.dispose();
  75649. }
  75650. this._mesh = null;
  75651. _super.prototype.dispose.call(this);
  75652. };
  75653. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  75654. /**
  75655. * The mesh that is attached to the controller
  75656. */
  75657. get: function () {
  75658. return this._mesh;
  75659. },
  75660. enumerable: true,
  75661. configurable: true
  75662. });
  75663. /**
  75664. * Gets the ray of the controller in the direction the controller is pointing
  75665. * @param length the length the resulting ray should be
  75666. * @returns a ray in the direction the controller is pointing
  75667. */
  75668. PoseEnabledController.prototype.getForwardRay = function (length) {
  75669. if (length === void 0) { length = 100; }
  75670. if (!this.mesh) {
  75671. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  75672. }
  75673. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  75674. var origin = m.getTranslation();
  75675. var forward = new BABYLON.Vector3(0, 0, -1);
  75676. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75677. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75678. return new BABYLON.Ray(origin, direction, length);
  75679. };
  75680. /**
  75681. * Name of the child mesh that can be used to cast a ray from the controller
  75682. */
  75683. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  75684. return PoseEnabledController;
  75685. }(BABYLON.Gamepad));
  75686. BABYLON.PoseEnabledController = PoseEnabledController;
  75687. })(BABYLON || (BABYLON = {}));
  75688. //# sourceMappingURL=babylon.poseEnabledController.js.map
  75689. var BABYLON;
  75690. (function (BABYLON) {
  75691. /**
  75692. * Defines the WebVRController object that represents controllers tracked in 3D space
  75693. */
  75694. var WebVRController = /** @class */ (function (_super) {
  75695. __extends(WebVRController, _super);
  75696. /**
  75697. * Creates a new WebVRController from a gamepad
  75698. * @param vrGamepad the gamepad that the WebVRController should be created from
  75699. */
  75700. function WebVRController(vrGamepad) {
  75701. var _this = _super.call(this, vrGamepad) || this;
  75702. // Observables
  75703. /**
  75704. * Fired when the trigger state has changed
  75705. */
  75706. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  75707. /**
  75708. * Fired when the main button state has changed
  75709. */
  75710. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  75711. /**
  75712. * Fired when the secondary button state has changed
  75713. */
  75714. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  75715. /**
  75716. * Fired when the pad state has changed
  75717. */
  75718. _this.onPadStateChangedObservable = new BABYLON.Observable();
  75719. /**
  75720. * Fired when controllers stick values have changed
  75721. */
  75722. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  75723. /**
  75724. * X and Y axis corrisponding to the controllers joystick
  75725. */
  75726. _this.pad = { x: 0, y: 0 };
  75727. // avoid GC, store state in a tmp object
  75728. _this._changes = {
  75729. pressChanged: false,
  75730. touchChanged: false,
  75731. valueChanged: false,
  75732. changed: false
  75733. };
  75734. _this._buttons = new Array(vrGamepad.buttons.length);
  75735. _this.hand = vrGamepad.hand;
  75736. return _this;
  75737. }
  75738. /**
  75739. * Fired when a controller button's state has changed
  75740. * @param callback the callback containing the button that was modified
  75741. */
  75742. WebVRController.prototype.onButtonStateChange = function (callback) {
  75743. this._onButtonStateChange = callback;
  75744. };
  75745. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  75746. /**
  75747. * The default controller model for the controller
  75748. */
  75749. get: function () {
  75750. return this._defaultModel;
  75751. },
  75752. enumerable: true,
  75753. configurable: true
  75754. });
  75755. /**
  75756. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  75757. */
  75758. WebVRController.prototype.update = function () {
  75759. _super.prototype.update.call(this);
  75760. for (var index = 0; index < this._buttons.length; index++) {
  75761. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  75762. }
  75763. ;
  75764. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  75765. this.pad.x = this.leftStick.x;
  75766. this.pad.y = this.leftStick.y;
  75767. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  75768. }
  75769. };
  75770. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  75771. if (!newState) {
  75772. newState = {
  75773. pressed: false,
  75774. touched: false,
  75775. value: 0
  75776. };
  75777. }
  75778. if (!currentState) {
  75779. this._buttons[buttonIndex] = {
  75780. pressed: newState.pressed,
  75781. touched: newState.touched,
  75782. value: newState.value
  75783. };
  75784. return;
  75785. }
  75786. this._checkChanges(newState, currentState);
  75787. if (this._changes.changed) {
  75788. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  75789. this._handleButtonChange(buttonIndex, newState, this._changes);
  75790. }
  75791. this._buttons[buttonIndex].pressed = newState.pressed;
  75792. this._buttons[buttonIndex].touched = newState.touched;
  75793. // oculus triggers are never 0, thou not touched.
  75794. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  75795. };
  75796. WebVRController.prototype._checkChanges = function (newState, currentState) {
  75797. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  75798. this._changes.touchChanged = newState.touched !== currentState.touched;
  75799. this._changes.valueChanged = newState.value !== currentState.value;
  75800. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  75801. return this._changes;
  75802. };
  75803. /**
  75804. * Disposes of th webVRCOntroller
  75805. */
  75806. WebVRController.prototype.dispose = function () {
  75807. _super.prototype.dispose.call(this);
  75808. this.onTriggerStateChangedObservable.clear();
  75809. this.onMainButtonStateChangedObservable.clear();
  75810. this.onSecondaryButtonStateChangedObservable.clear();
  75811. this.onPadStateChangedObservable.clear();
  75812. this.onPadValuesChangedObservable.clear();
  75813. };
  75814. return WebVRController;
  75815. }(BABYLON.PoseEnabledController));
  75816. BABYLON.WebVRController = WebVRController;
  75817. })(BABYLON || (BABYLON = {}));
  75818. //# sourceMappingURL=babylon.webVRController.js.map
  75819. var BABYLON;
  75820. (function (BABYLON) {
  75821. /**
  75822. * Oculus Touch Controller
  75823. */
  75824. var OculusTouchController = /** @class */ (function (_super) {
  75825. __extends(OculusTouchController, _super);
  75826. /**
  75827. * Creates a new OculusTouchController from a gamepad
  75828. * @param vrGamepad the gamepad that the controller should be created from
  75829. */
  75830. function OculusTouchController(vrGamepad) {
  75831. var _this = _super.call(this, vrGamepad) || this;
  75832. /**
  75833. * Fired when the secondary trigger on this controller is modified
  75834. */
  75835. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  75836. /**
  75837. * Fired when the thumb rest on this controller is modified
  75838. */
  75839. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  75840. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  75841. return _this;
  75842. }
  75843. /**
  75844. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75845. * @param scene scene in which to add meshes
  75846. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75847. */
  75848. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75849. var _this = this;
  75850. var meshName;
  75851. // Hand
  75852. if (this.hand === 'left') {
  75853. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  75854. }
  75855. else { // Right is the default if no hand is specified
  75856. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  75857. }
  75858. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  75859. /*
  75860. Parent Mesh name: oculus_touch_left
  75861. - body
  75862. - trigger
  75863. - thumbstick
  75864. - grip
  75865. - button_y
  75866. - button_x
  75867. - button_enter
  75868. */
  75869. _this._defaultModel = newMeshes[1];
  75870. _this.attachToMesh(_this._defaultModel);
  75871. if (meshLoaded) {
  75872. meshLoaded(_this._defaultModel);
  75873. }
  75874. });
  75875. };
  75876. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  75877. /**
  75878. * Fired when the A button on this controller is modified
  75879. */
  75880. get: function () {
  75881. if (this.hand === 'right') {
  75882. return this.onMainButtonStateChangedObservable;
  75883. }
  75884. else {
  75885. throw new Error('No A button on left hand');
  75886. }
  75887. },
  75888. enumerable: true,
  75889. configurable: true
  75890. });
  75891. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  75892. /**
  75893. * Fired when the B button on this controller is modified
  75894. */
  75895. get: function () {
  75896. if (this.hand === 'right') {
  75897. return this.onSecondaryButtonStateChangedObservable;
  75898. }
  75899. else {
  75900. throw new Error('No B button on left hand');
  75901. }
  75902. },
  75903. enumerable: true,
  75904. configurable: true
  75905. });
  75906. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  75907. /**
  75908. * Fired when the X button on this controller is modified
  75909. */
  75910. get: function () {
  75911. if (this.hand === 'left') {
  75912. return this.onMainButtonStateChangedObservable;
  75913. }
  75914. else {
  75915. throw new Error('No X button on right hand');
  75916. }
  75917. },
  75918. enumerable: true,
  75919. configurable: true
  75920. });
  75921. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  75922. /**
  75923. * Fired when the Y button on this controller is modified
  75924. */
  75925. get: function () {
  75926. if (this.hand === 'left') {
  75927. return this.onSecondaryButtonStateChangedObservable;
  75928. }
  75929. else {
  75930. throw new Error('No Y button on right hand');
  75931. }
  75932. },
  75933. enumerable: true,
  75934. configurable: true
  75935. });
  75936. /**
  75937. * Called once for each button that changed state since the last frame
  75938. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  75939. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  75940. * 2) secondary trigger (same)
  75941. * 3) A (right) X (left), touch, pressed = value
  75942. * 4) B / Y
  75943. * 5) thumb rest
  75944. * @param buttonIdx Which button index changed
  75945. * @param state New state of the button
  75946. * @param changes Which properties on the state changed since last frame
  75947. */
  75948. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75949. var notifyObject = state; //{ state: state, changes: changes };
  75950. var triggerDirection = this.hand === 'right' ? -1 : 1;
  75951. switch (buttonIdx) {
  75952. case 0:
  75953. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75954. return;
  75955. case 1: // index trigger
  75956. if (this._defaultModel) {
  75957. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  75958. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  75959. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  75960. }
  75961. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75962. return;
  75963. case 2: // secondary trigger
  75964. if (this._defaultModel) {
  75965. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  75966. }
  75967. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  75968. return;
  75969. case 3:
  75970. if (this._defaultModel) {
  75971. if (notifyObject.pressed) {
  75972. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  75973. }
  75974. else {
  75975. (this._defaultModel.getChildren()[1]).position.y = 0;
  75976. }
  75977. }
  75978. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75979. return;
  75980. case 4:
  75981. if (this._defaultModel) {
  75982. if (notifyObject.pressed) {
  75983. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75984. }
  75985. else {
  75986. (this._defaultModel.getChildren()[2]).position.y = 0;
  75987. }
  75988. }
  75989. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75990. return;
  75991. case 5:
  75992. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  75993. return;
  75994. }
  75995. };
  75996. /**
  75997. * Base Url for the controller model.
  75998. */
  75999. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  76000. /**
  76001. * File name for the left controller model.
  76002. */
  76003. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  76004. /**
  76005. * File name for the right controller model.
  76006. */
  76007. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  76008. return OculusTouchController;
  76009. }(BABYLON.WebVRController));
  76010. BABYLON.OculusTouchController = OculusTouchController;
  76011. })(BABYLON || (BABYLON = {}));
  76012. //# sourceMappingURL=babylon.oculusTouchController.js.map
  76013. var BABYLON;
  76014. (function (BABYLON) {
  76015. /**
  76016. * Vive Controller
  76017. */
  76018. var ViveController = /** @class */ (function (_super) {
  76019. __extends(ViveController, _super);
  76020. /**
  76021. * Creates a new ViveController from a gamepad
  76022. * @param vrGamepad the gamepad that the controller should be created from
  76023. */
  76024. function ViveController(vrGamepad) {
  76025. var _this = _super.call(this, vrGamepad) || this;
  76026. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  76027. _this._invertLeftStickY = true;
  76028. return _this;
  76029. }
  76030. /**
  76031. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76032. * @param scene scene in which to add meshes
  76033. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76034. */
  76035. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76036. var _this = this;
  76037. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  76038. /*
  76039. Parent Mesh name: ViveWand
  76040. - body
  76041. - r_gripper
  76042. - l_gripper
  76043. - menu_button
  76044. - system_button
  76045. - trackpad
  76046. - trigger
  76047. - LED
  76048. */
  76049. _this._defaultModel = newMeshes[1];
  76050. _this.attachToMesh(_this._defaultModel);
  76051. if (meshLoaded) {
  76052. meshLoaded(_this._defaultModel);
  76053. }
  76054. });
  76055. };
  76056. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  76057. /**
  76058. * Fired when the left button on this controller is modified
  76059. */
  76060. get: function () {
  76061. return this.onMainButtonStateChangedObservable;
  76062. },
  76063. enumerable: true,
  76064. configurable: true
  76065. });
  76066. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  76067. /**
  76068. * Fired when the right button on this controller is modified
  76069. */
  76070. get: function () {
  76071. return this.onMainButtonStateChangedObservable;
  76072. },
  76073. enumerable: true,
  76074. configurable: true
  76075. });
  76076. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  76077. /**
  76078. * Fired when the menu button on this controller is modified
  76079. */
  76080. get: function () {
  76081. return this.onSecondaryButtonStateChangedObservable;
  76082. },
  76083. enumerable: true,
  76084. configurable: true
  76085. });
  76086. /**
  76087. * Called once for each button that changed state since the last frame
  76088. * Vive mapping:
  76089. * 0: touchpad
  76090. * 1: trigger
  76091. * 2: left AND right buttons
  76092. * 3: menu button
  76093. * @param buttonIdx Which button index changed
  76094. * @param state New state of the button
  76095. * @param changes Which properties on the state changed since last frame
  76096. */
  76097. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76098. var notifyObject = state; //{ state: state, changes: changes };
  76099. switch (buttonIdx) {
  76100. case 0:
  76101. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76102. return;
  76103. case 1: // index trigger
  76104. if (this._defaultModel) {
  76105. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  76106. }
  76107. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76108. return;
  76109. case 2: // left AND right button
  76110. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76111. return;
  76112. case 3:
  76113. if (this._defaultModel) {
  76114. if (notifyObject.pressed) {
  76115. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76116. }
  76117. else {
  76118. (this._defaultModel.getChildren()[2]).position.y = 0;
  76119. }
  76120. }
  76121. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76122. return;
  76123. }
  76124. };
  76125. /**
  76126. * Base Url for the controller model.
  76127. */
  76128. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  76129. /**
  76130. * File name for the controller model.
  76131. */
  76132. ViveController.MODEL_FILENAME = 'wand.babylon';
  76133. return ViveController;
  76134. }(BABYLON.WebVRController));
  76135. BABYLON.ViveController = ViveController;
  76136. })(BABYLON || (BABYLON = {}));
  76137. //# sourceMappingURL=babylon.viveController.js.map
  76138. var BABYLON;
  76139. (function (BABYLON) {
  76140. /**
  76141. * Generic Controller
  76142. */
  76143. var GenericController = /** @class */ (function (_super) {
  76144. __extends(GenericController, _super);
  76145. /**
  76146. * Creates a new GenericController from a gamepad
  76147. * @param vrGamepad the gamepad that the controller should be created from
  76148. */
  76149. function GenericController(vrGamepad) {
  76150. return _super.call(this, vrGamepad) || this;
  76151. }
  76152. /**
  76153. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76154. * @param scene scene in which to add meshes
  76155. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76156. */
  76157. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76158. var _this = this;
  76159. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  76160. _this._defaultModel = newMeshes[1];
  76161. _this.attachToMesh(_this._defaultModel);
  76162. if (meshLoaded) {
  76163. meshLoaded(_this._defaultModel);
  76164. }
  76165. });
  76166. };
  76167. /**
  76168. * Called once for each button that changed state since the last frame
  76169. * @param buttonIdx Which button index changed
  76170. * @param state New state of the button
  76171. * @param changes Which properties on the state changed since last frame
  76172. */
  76173. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76174. console.log("Button id: " + buttonIdx + "state: ");
  76175. console.dir(state);
  76176. };
  76177. /**
  76178. * Base Url for the controller model.
  76179. */
  76180. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76181. /**
  76182. * File name for the controller model.
  76183. */
  76184. GenericController.MODEL_FILENAME = 'generic.babylon';
  76185. return GenericController;
  76186. }(BABYLON.WebVRController));
  76187. BABYLON.GenericController = GenericController;
  76188. })(BABYLON || (BABYLON = {}));
  76189. //# sourceMappingURL=babylon.genericController.js.map
  76190. var BABYLON;
  76191. (function (BABYLON) {
  76192. /**
  76193. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  76194. */
  76195. var LoadedMeshInfo = /** @class */ (function () {
  76196. function LoadedMeshInfo() {
  76197. /**
  76198. * Map of the button meshes contained in the controller
  76199. */
  76200. this.buttonMeshes = {};
  76201. /**
  76202. * Map of the axis meshes contained in the controller
  76203. */
  76204. this.axisMeshes = {};
  76205. }
  76206. return LoadedMeshInfo;
  76207. }());
  76208. /**
  76209. * Defines the WindowsMotionController object that the state of the windows motion controller
  76210. */
  76211. var WindowsMotionController = /** @class */ (function (_super) {
  76212. __extends(WindowsMotionController, _super);
  76213. /**
  76214. * Creates a new WindowsMotionController from a gamepad
  76215. * @param vrGamepad the gamepad that the controller should be created from
  76216. */
  76217. function WindowsMotionController(vrGamepad) {
  76218. var _this = _super.call(this, vrGamepad) || this;
  76219. _this._mapping = {
  76220. // Semantic button names
  76221. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  76222. // A mapping of the button name to glTF model node name
  76223. // that should be transformed by button value.
  76224. buttonMeshNames: {
  76225. 'trigger': 'SELECT',
  76226. 'menu': 'MENU',
  76227. 'grip': 'GRASP',
  76228. 'thumbstick': 'THUMBSTICK_PRESS',
  76229. 'trackpad': 'TOUCHPAD_PRESS'
  76230. },
  76231. // This mapping is used to translate from the Motion Controller to Babylon semantics
  76232. buttonObservableNames: {
  76233. 'trigger': 'onTriggerStateChangedObservable',
  76234. 'menu': 'onSecondaryButtonStateChangedObservable',
  76235. 'grip': 'onMainButtonStateChangedObservable',
  76236. 'thumbstick': 'onPadStateChangedObservable',
  76237. 'trackpad': 'onTrackpadChangedObservable'
  76238. },
  76239. // A mapping of the axis name to glTF model node name
  76240. // that should be transformed by axis value.
  76241. // This array mirrors the browserGamepad.axes array, such that
  76242. // the mesh corresponding to axis 0 is in this array index 0.
  76243. axisMeshNames: [
  76244. 'THUMBSTICK_X',
  76245. 'THUMBSTICK_Y',
  76246. 'TOUCHPAD_TOUCH_X',
  76247. 'TOUCHPAD_TOUCH_Y'
  76248. ],
  76249. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  76250. };
  76251. /**
  76252. * Fired when the trackpad on this controller is clicked
  76253. */
  76254. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  76255. /**
  76256. * Fired when the trackpad on this controller is modified
  76257. */
  76258. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  76259. /**
  76260. * The current x and y values of this controller's trackpad
  76261. */
  76262. _this.trackpad = { x: 0, y: 0 };
  76263. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  76264. _this._loadedMeshInfo = null;
  76265. return _this;
  76266. }
  76267. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  76268. /**
  76269. * Fired when the trigger on this controller is modified
  76270. */
  76271. get: function () {
  76272. return this.onTriggerStateChangedObservable;
  76273. },
  76274. enumerable: true,
  76275. configurable: true
  76276. });
  76277. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  76278. /**
  76279. * Fired when the menu button on this controller is modified
  76280. */
  76281. get: function () {
  76282. return this.onSecondaryButtonStateChangedObservable;
  76283. },
  76284. enumerable: true,
  76285. configurable: true
  76286. });
  76287. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  76288. /**
  76289. * Fired when the grip button on this controller is modified
  76290. */
  76291. get: function () {
  76292. return this.onMainButtonStateChangedObservable;
  76293. },
  76294. enumerable: true,
  76295. configurable: true
  76296. });
  76297. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  76298. /**
  76299. * Fired when the thumbstick button on this controller is modified
  76300. */
  76301. get: function () {
  76302. return this.onPadStateChangedObservable;
  76303. },
  76304. enumerable: true,
  76305. configurable: true
  76306. });
  76307. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  76308. /**
  76309. * Fired when the touchpad button on this controller is modified
  76310. */
  76311. get: function () {
  76312. return this.onTrackpadChangedObservable;
  76313. },
  76314. enumerable: true,
  76315. configurable: true
  76316. });
  76317. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  76318. /**
  76319. * Fired when the touchpad values on this controller are modified
  76320. */
  76321. get: function () {
  76322. return this.onTrackpadValuesChangedObservable;
  76323. },
  76324. enumerable: true,
  76325. configurable: true
  76326. });
  76327. WindowsMotionController.prototype._updateTrackpad = function () {
  76328. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  76329. this.trackpad.x = this.browserGamepad["axes"][2];
  76330. this.trackpad.y = this.browserGamepad["axes"][3];
  76331. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  76332. }
  76333. };
  76334. /**
  76335. * Called once per frame by the engine.
  76336. */
  76337. WindowsMotionController.prototype.update = function () {
  76338. _super.prototype.update.call(this);
  76339. if (this.browserGamepad.axes) {
  76340. this._updateTrackpad();
  76341. // Only need to animate axes if there is a loaded mesh
  76342. if (this._loadedMeshInfo) {
  76343. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  76344. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  76345. }
  76346. }
  76347. }
  76348. };
  76349. /**
  76350. * Called once for each button that changed state since the last frame
  76351. * @param buttonIdx Which button index changed
  76352. * @param state New state of the button
  76353. * @param changes Which properties on the state changed since last frame
  76354. */
  76355. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76356. var buttonName = this._mapping.buttons[buttonIdx];
  76357. if (!buttonName) {
  76358. return;
  76359. }
  76360. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  76361. this._updateTrackpad();
  76362. // Only emit events for buttons that we know how to map from index to name
  76363. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  76364. if (observable) {
  76365. observable.notifyObservers(state);
  76366. }
  76367. this._lerpButtonTransform(buttonName, state.value);
  76368. };
  76369. /**
  76370. * Moves the buttons on the controller mesh based on their current state
  76371. * @param buttonName the name of the button to move
  76372. * @param buttonValue the value of the button which determines the buttons new position
  76373. */
  76374. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  76375. // If there is no loaded mesh, there is nothing to transform.
  76376. if (!this._loadedMeshInfo) {
  76377. return;
  76378. }
  76379. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  76380. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76381. return;
  76382. }
  76383. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  76384. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  76385. };
  76386. /**
  76387. * Moves the axis on the controller mesh based on its current state
  76388. * @param axis the index of the axis
  76389. * @param axisValue the value of the axis which determines the meshes new position
  76390. * @hidden
  76391. */
  76392. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  76393. if (!this._loadedMeshInfo) {
  76394. return;
  76395. }
  76396. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  76397. if (!meshInfo) {
  76398. return;
  76399. }
  76400. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76401. return;
  76402. }
  76403. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  76404. var lerpValue = axisValue * 0.5 + 0.5;
  76405. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  76406. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  76407. };
  76408. /**
  76409. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76410. * @param scene scene in which to add meshes
  76411. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76412. */
  76413. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  76414. var _this = this;
  76415. if (forceDefault === void 0) { forceDefault = false; }
  76416. var path;
  76417. var filename;
  76418. // Checking if GLB loader is present
  76419. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  76420. // Determine the device specific folder based on the ID suffix
  76421. var device = 'default';
  76422. if (this.id && !forceDefault) {
  76423. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  76424. device = ((match && match[0]) || device);
  76425. }
  76426. // Hand
  76427. if (this.hand === 'left') {
  76428. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  76429. }
  76430. else { // Right is the default if no hand is specified
  76431. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  76432. }
  76433. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  76434. }
  76435. else {
  76436. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  76437. path = BABYLON.GenericController.MODEL_BASE_URL;
  76438. filename = BABYLON.GenericController.MODEL_FILENAME;
  76439. }
  76440. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  76441. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  76442. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  76443. if (!_this._loadedMeshInfo) {
  76444. return;
  76445. }
  76446. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  76447. _this.attachToMesh(_this._defaultModel);
  76448. if (meshLoaded) {
  76449. meshLoaded(_this._defaultModel);
  76450. }
  76451. }, null, function (scene, message) {
  76452. BABYLON.Tools.Log(message);
  76453. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  76454. if (!forceDefault) {
  76455. _this.initControllerMesh(scene, meshLoaded, true);
  76456. }
  76457. });
  76458. };
  76459. /**
  76460. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  76461. * can be transformed by button presses and axes values, based on this._mapping.
  76462. *
  76463. * @param scene scene in which the meshes exist
  76464. * @param meshes list of meshes that make up the controller model to process
  76465. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  76466. */
  76467. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  76468. var loadedMeshInfo = null;
  76469. // Create a new mesh to contain the glTF hierarchy
  76470. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  76471. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  76472. var childMesh = null;
  76473. for (var i = 0; i < meshes.length; i++) {
  76474. var mesh = meshes[i];
  76475. if (!mesh.parent) {
  76476. // Exclude controller meshes from picking results
  76477. mesh.isPickable = false;
  76478. // Handle root node, attach to the new parentMesh
  76479. childMesh = mesh;
  76480. break;
  76481. }
  76482. }
  76483. if (childMesh) {
  76484. childMesh.setParent(parentMesh);
  76485. // Create our mesh info. Note that this method will always return non-null.
  76486. loadedMeshInfo = this.createMeshInfo(parentMesh);
  76487. }
  76488. else {
  76489. BABYLON.Tools.Warn('Could not find root node in model file.');
  76490. }
  76491. return loadedMeshInfo;
  76492. };
  76493. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  76494. var loadedMeshInfo = new LoadedMeshInfo();
  76495. var i;
  76496. loadedMeshInfo.rootNode = rootNode;
  76497. // Reset the caches
  76498. loadedMeshInfo.buttonMeshes = {};
  76499. loadedMeshInfo.axisMeshes = {};
  76500. // Button Meshes
  76501. for (i = 0; i < this._mapping.buttons.length; i++) {
  76502. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  76503. if (!buttonMeshName) {
  76504. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  76505. continue;
  76506. }
  76507. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  76508. if (!buttonMesh) {
  76509. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  76510. continue;
  76511. }
  76512. var buttonMeshInfo = {
  76513. index: i,
  76514. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  76515. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  76516. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  76517. };
  76518. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  76519. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  76520. }
  76521. else {
  76522. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  76523. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  76524. '(VALUE: ' + !!buttonMeshInfo.value +
  76525. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  76526. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  76527. ')');
  76528. }
  76529. }
  76530. // Axis Meshes
  76531. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  76532. var axisMeshName = this._mapping.axisMeshNames[i];
  76533. if (!axisMeshName) {
  76534. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  76535. continue;
  76536. }
  76537. var axisMesh = getChildByName(rootNode, axisMeshName);
  76538. if (!axisMesh) {
  76539. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  76540. continue;
  76541. }
  76542. var axisMeshInfo = {
  76543. index: i,
  76544. value: getImmediateChildByName(axisMesh, 'VALUE'),
  76545. min: getImmediateChildByName(axisMesh, 'MIN'),
  76546. max: getImmediateChildByName(axisMesh, 'MAX')
  76547. };
  76548. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  76549. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  76550. }
  76551. else {
  76552. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  76553. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  76554. '(VALUE: ' + !!axisMeshInfo.value +
  76555. ', MIN: ' + !!axisMeshInfo.min +
  76556. ', MAX:' + !!axisMeshInfo.max +
  76557. ')');
  76558. }
  76559. }
  76560. // Pointing Ray
  76561. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  76562. if (!loadedMeshInfo.pointingPoseNode) {
  76563. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  76564. }
  76565. else {
  76566. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  76567. }
  76568. return loadedMeshInfo;
  76569. // Look through all children recursively. This will return null if no mesh exists with the given name.
  76570. function getChildByName(node, name) {
  76571. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  76572. }
  76573. // Look through only immediate children. This will return null if no mesh exists with the given name.
  76574. function getImmediateChildByName(node, name) {
  76575. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  76576. }
  76577. };
  76578. /**
  76579. * Gets the ray of the controller in the direction the controller is pointing
  76580. * @param length the length the resulting ray should be
  76581. * @returns a ray in the direction the controller is pointing
  76582. */
  76583. WindowsMotionController.prototype.getForwardRay = function (length) {
  76584. if (length === void 0) { length = 100; }
  76585. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  76586. return _super.prototype.getForwardRay.call(this, length);
  76587. }
  76588. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  76589. var origin = m.getTranslation();
  76590. var forward = new BABYLON.Vector3(0, 0, -1);
  76591. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76592. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76593. return new BABYLON.Ray(origin, direction, length);
  76594. };
  76595. /**
  76596. * Disposes of the controller
  76597. */
  76598. WindowsMotionController.prototype.dispose = function () {
  76599. _super.prototype.dispose.call(this);
  76600. this.onTrackpadChangedObservable.clear();
  76601. };
  76602. /**
  76603. * The base url used to load the left and right controller models
  76604. */
  76605. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  76606. /**
  76607. * The name of the left controller model file
  76608. */
  76609. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  76610. /**
  76611. * The name of the right controller model file
  76612. */
  76613. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  76614. /**
  76615. * The controller name prefix for this controller type
  76616. */
  76617. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  76618. /**
  76619. * The controller id pattern for this controller type
  76620. */
  76621. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  76622. return WindowsMotionController;
  76623. }(BABYLON.WebVRController));
  76624. BABYLON.WindowsMotionController = WindowsMotionController;
  76625. })(BABYLON || (BABYLON = {}));
  76626. //# sourceMappingURL=babylon.windowsMotionController.js.map
  76627. var BABYLON;
  76628. (function (BABYLON) {
  76629. /**
  76630. * Gear VR Controller
  76631. */
  76632. var GearVRController = /** @class */ (function (_super) {
  76633. __extends(GearVRController, _super);
  76634. /**
  76635. * Creates a new GearVRController from a gamepad
  76636. * @param vrGamepad the gamepad that the controller should be created from
  76637. */
  76638. function GearVRController(vrGamepad) {
  76639. var _this = _super.call(this, vrGamepad) || this;
  76640. _this._maxRotationDistFromHeadset = Math.PI / 5;
  76641. _this._draggedRoomRotation = 0;
  76642. _this._tmpVector = new BABYLON.Vector3();
  76643. _this._buttonIndexToObservableNameMap = [
  76644. 'onTrackpadChangedObservable',
  76645. 'onTriggerStateChangedObservable' // Trigger
  76646. ];
  76647. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  76648. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  76649. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  76650. return _this;
  76651. }
  76652. /**
  76653. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76654. * @param poseData raw pose fromthe device
  76655. */
  76656. GearVRController.prototype.updateFromDevice = function (poseData) {
  76657. _super.prototype.updateFromDevice.call(this, poseData);
  76658. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  76659. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  76660. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  76661. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  76662. // Find the radian distance away that the headset is from the controllers rotation
  76663. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  76664. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  76665. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  76666. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  76667. this._draggedRoomRotation += rotationAmount;
  76668. // Rotate controller around headset
  76669. var sin = Math.sin(-rotationAmount);
  76670. var cos = Math.cos(-rotationAmount);
  76671. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  76672. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  76673. }
  76674. }
  76675. }
  76676. };
  76677. /**
  76678. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76679. * @param scene scene in which to add meshes
  76680. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76681. */
  76682. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76683. var _this = this;
  76684. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  76685. // Offset the controller so it will rotate around the users wrist
  76686. var mesh = new BABYLON.Mesh("", scene);
  76687. newMeshes[1].parent = mesh;
  76688. newMeshes[1].position.z = -0.15;
  76689. _this._defaultModel = mesh;
  76690. _this.attachToMesh(_this._defaultModel);
  76691. if (meshLoaded) {
  76692. meshLoaded(_this._defaultModel);
  76693. }
  76694. });
  76695. };
  76696. /**
  76697. * Called once for each button that changed state since the last frame
  76698. * @param buttonIdx Which button index changed
  76699. * @param state New state of the button
  76700. * @param changes Which properties on the state changed since last frame
  76701. */
  76702. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76703. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  76704. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  76705. // Only emit events for buttons that we know how to map from index to observable
  76706. var observable = this[observableName];
  76707. if (observable) {
  76708. observable.notifyObservers(state);
  76709. }
  76710. }
  76711. };
  76712. /**
  76713. * Base Url for the controller model.
  76714. */
  76715. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76716. /**
  76717. * File name for the controller model.
  76718. */
  76719. GearVRController.MODEL_FILENAME = 'generic.babylon';
  76720. /**
  76721. * Gamepad Id prefix used to identify this controller.
  76722. */
  76723. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  76724. return GearVRController;
  76725. }(BABYLON.WebVRController));
  76726. BABYLON.GearVRController = GearVRController;
  76727. })(BABYLON || (BABYLON = {}));
  76728. //# sourceMappingURL=babylon.gearVRController.js.map
  76729. var BABYLON;
  76730. (function (BABYLON) {
  76731. /**
  76732. * Google Daydream controller
  76733. */
  76734. var DaydreamController = /** @class */ (function (_super) {
  76735. __extends(DaydreamController, _super);
  76736. /**
  76737. * Creates a new DaydreamController from a gamepad
  76738. * @param vrGamepad the gamepad that the controller should be created from
  76739. */
  76740. function DaydreamController(vrGamepad) {
  76741. var _this = _super.call(this, vrGamepad) || this;
  76742. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  76743. return _this;
  76744. }
  76745. /**
  76746. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76747. * @param scene scene in which to add meshes
  76748. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76749. */
  76750. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76751. var _this = this;
  76752. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  76753. _this._defaultModel = newMeshes[1];
  76754. _this.attachToMesh(_this._defaultModel);
  76755. if (meshLoaded) {
  76756. meshLoaded(_this._defaultModel);
  76757. }
  76758. });
  76759. };
  76760. /**
  76761. * Called once for each button that changed state since the last frame
  76762. * @param buttonIdx Which button index changed
  76763. * @param state New state of the button
  76764. * @param changes Which properties on the state changed since last frame
  76765. */
  76766. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76767. // Daydream controller only has 1 GamepadButton (on the trackpad).
  76768. if (buttonIdx === 0) {
  76769. var observable = this.onTriggerStateChangedObservable;
  76770. if (observable) {
  76771. observable.notifyObservers(state);
  76772. }
  76773. }
  76774. else {
  76775. // If the app or home buttons are ever made available
  76776. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  76777. }
  76778. };
  76779. /**
  76780. * Base Url for the controller model.
  76781. */
  76782. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76783. /**
  76784. * File name for the controller model.
  76785. */
  76786. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  76787. /**
  76788. * Gamepad Id prefix used to identify Daydream Controller.
  76789. */
  76790. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  76791. return DaydreamController;
  76792. }(BABYLON.WebVRController));
  76793. BABYLON.DaydreamController = DaydreamController;
  76794. })(BABYLON || (BABYLON = {}));
  76795. //# sourceMappingURL=babylon.daydreamController.js.map
  76796. var BABYLON;
  76797. (function (BABYLON) {
  76798. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  76799. get: function () {
  76800. if (!this._gamepadManager) {
  76801. this._gamepadManager = new BABYLON.GamepadManager(this);
  76802. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  76803. if (!component) {
  76804. component = new GamepadSystemSceneComponent(this);
  76805. this._addComponent(component);
  76806. }
  76807. }
  76808. return this._gamepadManager;
  76809. },
  76810. enumerable: true,
  76811. configurable: true
  76812. });
  76813. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  76814. this.add(new BABYLON.FreeCameraGamepadInput());
  76815. return this;
  76816. };
  76817. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  76818. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  76819. return this;
  76820. };
  76821. /**
  76822. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  76823. */
  76824. var GamepadSystemSceneComponent = /** @class */ (function () {
  76825. /**
  76826. * Creates a new instance of the component for the given scene
  76827. * @param scene Defines the scene to register the component in
  76828. */
  76829. function GamepadSystemSceneComponent(scene) {
  76830. /**
  76831. * The component name helpfull to identify the component in the list of scene components.
  76832. */
  76833. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  76834. this.scene = scene;
  76835. }
  76836. /**
  76837. * Registers the component in a given scene
  76838. */
  76839. GamepadSystemSceneComponent.prototype.register = function () {
  76840. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  76841. };
  76842. /**
  76843. * Rebuilds the elements related to this component in case of
  76844. * context lost for instance.
  76845. */
  76846. GamepadSystemSceneComponent.prototype.rebuild = function () {
  76847. // Nothing to do for gamepads
  76848. };
  76849. /**
  76850. * Disposes the component and the associated ressources
  76851. */
  76852. GamepadSystemSceneComponent.prototype.dispose = function () {
  76853. var gamepadManager = this.scene._gamepadManager;
  76854. if (gamepadManager) {
  76855. gamepadManager.dispose();
  76856. this.scene._gamepadManager = null;
  76857. }
  76858. };
  76859. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  76860. var gamepadManager = this.scene._gamepadManager;
  76861. if (gamepadManager && gamepadManager._isMonitoring) {
  76862. gamepadManager._checkGamepadsStatus();
  76863. }
  76864. };
  76865. return GamepadSystemSceneComponent;
  76866. }());
  76867. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  76868. })(BABYLON || (BABYLON = {}));
  76869. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  76870. var BABYLON;
  76871. (function (BABYLON) {
  76872. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  76873. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  76874. });
  76875. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  76876. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  76877. });
  76878. var FollowCamera = /** @class */ (function (_super) {
  76879. __extends(FollowCamera, _super);
  76880. function FollowCamera(name, position, scene, lockedTarget) {
  76881. if (lockedTarget === void 0) { lockedTarget = null; }
  76882. var _this = _super.call(this, name, position, scene) || this;
  76883. _this.radius = 12;
  76884. _this.rotationOffset = 0;
  76885. _this.heightOffset = 4;
  76886. _this.cameraAcceleration = 0.05;
  76887. _this.maxCameraSpeed = 20;
  76888. _this.lockedTarget = lockedTarget;
  76889. return _this;
  76890. }
  76891. FollowCamera.prototype.getRadians = function (degrees) {
  76892. return degrees * Math.PI / 180;
  76893. };
  76894. FollowCamera.prototype.follow = function (cameraTarget) {
  76895. if (!cameraTarget)
  76896. return;
  76897. var yRotation;
  76898. if (cameraTarget.rotationQuaternion) {
  76899. var rotMatrix = new BABYLON.Matrix();
  76900. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  76901. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  76902. }
  76903. else {
  76904. yRotation = cameraTarget.rotation.y;
  76905. }
  76906. var radians = this.getRadians(this.rotationOffset) + yRotation;
  76907. var targetPosition = cameraTarget.getAbsolutePosition();
  76908. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  76909. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  76910. var dx = targetX - this.position.x;
  76911. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  76912. var dz = (targetZ) - this.position.z;
  76913. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  76914. var vy = dy * this.cameraAcceleration;
  76915. var vz = dz * this.cameraAcceleration * 2;
  76916. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  76917. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76918. }
  76919. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  76920. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76921. }
  76922. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  76923. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76924. }
  76925. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  76926. this.setTarget(targetPosition);
  76927. };
  76928. /** @hidden */
  76929. FollowCamera.prototype._checkInputs = function () {
  76930. _super.prototype._checkInputs.call(this);
  76931. if (this.lockedTarget) {
  76932. this.follow(this.lockedTarget);
  76933. }
  76934. };
  76935. FollowCamera.prototype.getClassName = function () {
  76936. return "FollowCamera";
  76937. };
  76938. __decorate([
  76939. BABYLON.serialize()
  76940. ], FollowCamera.prototype, "radius", void 0);
  76941. __decorate([
  76942. BABYLON.serialize()
  76943. ], FollowCamera.prototype, "rotationOffset", void 0);
  76944. __decorate([
  76945. BABYLON.serialize()
  76946. ], FollowCamera.prototype, "heightOffset", void 0);
  76947. __decorate([
  76948. BABYLON.serialize()
  76949. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  76950. __decorate([
  76951. BABYLON.serialize()
  76952. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  76953. __decorate([
  76954. BABYLON.serializeAsMeshReference("lockedTargetId")
  76955. ], FollowCamera.prototype, "lockedTarget", void 0);
  76956. return FollowCamera;
  76957. }(BABYLON.TargetCamera));
  76958. BABYLON.FollowCamera = FollowCamera;
  76959. var ArcFollowCamera = /** @class */ (function (_super) {
  76960. __extends(ArcFollowCamera, _super);
  76961. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  76962. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  76963. _this.alpha = alpha;
  76964. _this.beta = beta;
  76965. _this.radius = radius;
  76966. _this.target = target;
  76967. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  76968. _this.follow();
  76969. return _this;
  76970. }
  76971. ArcFollowCamera.prototype.follow = function () {
  76972. if (!this.target) {
  76973. return;
  76974. }
  76975. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  76976. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  76977. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  76978. var targetPosition = this.target.getAbsolutePosition();
  76979. this.position = targetPosition.add(this._cartesianCoordinates);
  76980. this.setTarget(targetPosition);
  76981. };
  76982. /** @hidden */
  76983. ArcFollowCamera.prototype._checkInputs = function () {
  76984. _super.prototype._checkInputs.call(this);
  76985. this.follow();
  76986. };
  76987. ArcFollowCamera.prototype.getClassName = function () {
  76988. return "ArcFollowCamera";
  76989. };
  76990. return ArcFollowCamera;
  76991. }(BABYLON.TargetCamera));
  76992. BABYLON.ArcFollowCamera = ArcFollowCamera;
  76993. })(BABYLON || (BABYLON = {}));
  76994. //# sourceMappingURL=babylon.followCamera.js.map
  76995. var BABYLON;
  76996. (function (BABYLON) {
  76997. // We're mainly based on the logic defined into the FreeCamera code
  76998. var UniversalCamera = /** @class */ (function (_super) {
  76999. __extends(UniversalCamera, _super);
  77000. //-- end properties for backward compatibility for inputs
  77001. function UniversalCamera(name, position, scene) {
  77002. var _this = _super.call(this, name, position, scene) || this;
  77003. _this.inputs.addGamepad();
  77004. return _this;
  77005. }
  77006. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  77007. //-- Begin properties for backward compatibility for inputs
  77008. get: function () {
  77009. var gamepad = this.inputs.attached["gamepad"];
  77010. if (gamepad)
  77011. return gamepad.gamepadAngularSensibility;
  77012. return 0;
  77013. },
  77014. set: function (value) {
  77015. var gamepad = this.inputs.attached["gamepad"];
  77016. if (gamepad)
  77017. gamepad.gamepadAngularSensibility = value;
  77018. },
  77019. enumerable: true,
  77020. configurable: true
  77021. });
  77022. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  77023. get: function () {
  77024. var gamepad = this.inputs.attached["gamepad"];
  77025. if (gamepad)
  77026. return gamepad.gamepadMoveSensibility;
  77027. return 0;
  77028. },
  77029. set: function (value) {
  77030. var gamepad = this.inputs.attached["gamepad"];
  77031. if (gamepad)
  77032. gamepad.gamepadMoveSensibility = value;
  77033. },
  77034. enumerable: true,
  77035. configurable: true
  77036. });
  77037. UniversalCamera.prototype.getClassName = function () {
  77038. return "UniversalCamera";
  77039. };
  77040. return UniversalCamera;
  77041. }(BABYLON.TouchCamera));
  77042. BABYLON.UniversalCamera = UniversalCamera;
  77043. })(BABYLON || (BABYLON = {}));
  77044. //# sourceMappingURL=babylon.universalCamera.js.map
  77045. var BABYLON;
  77046. (function (BABYLON) {
  77047. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  77048. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  77049. });
  77050. // We're mainly based on the logic defined into the FreeCamera code
  77051. var GamepadCamera = /** @class */ (function (_super) {
  77052. __extends(GamepadCamera, _super);
  77053. //-- end properties for backward compatibility for inputs
  77054. function GamepadCamera(name, position, scene) {
  77055. return _super.call(this, name, position, scene) || this;
  77056. }
  77057. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  77058. //-- Begin properties for backward compatibility for inputs
  77059. get: function () {
  77060. var gamepad = this.inputs.attached["gamepad"];
  77061. if (gamepad)
  77062. return gamepad.gamepadAngularSensibility;
  77063. return 0;
  77064. },
  77065. set: function (value) {
  77066. var gamepad = this.inputs.attached["gamepad"];
  77067. if (gamepad)
  77068. gamepad.gamepadAngularSensibility = value;
  77069. },
  77070. enumerable: true,
  77071. configurable: true
  77072. });
  77073. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  77074. get: function () {
  77075. var gamepad = this.inputs.attached["gamepad"];
  77076. if (gamepad)
  77077. return gamepad.gamepadMoveSensibility;
  77078. return 0;
  77079. },
  77080. set: function (value) {
  77081. var gamepad = this.inputs.attached["gamepad"];
  77082. if (gamepad)
  77083. gamepad.gamepadMoveSensibility = value;
  77084. },
  77085. enumerable: true,
  77086. configurable: true
  77087. });
  77088. GamepadCamera.prototype.getClassName = function () {
  77089. return "GamepadCamera";
  77090. };
  77091. return GamepadCamera;
  77092. }(BABYLON.UniversalCamera));
  77093. BABYLON.GamepadCamera = GamepadCamera;
  77094. })(BABYLON || (BABYLON = {}));
  77095. //# sourceMappingURL=babylon.gamepadCamera.js.map
  77096. var BABYLON;
  77097. (function (BABYLON) {
  77098. var PostProcessRenderPipelineManager = /** @class */ (function () {
  77099. function PostProcessRenderPipelineManager() {
  77100. this._renderPipelines = {};
  77101. }
  77102. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  77103. this._renderPipelines[renderPipeline._name] = renderPipeline;
  77104. };
  77105. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  77106. if (unique === void 0) { unique = false; }
  77107. var renderPipeline = this._renderPipelines[renderPipelineName];
  77108. if (!renderPipeline) {
  77109. return;
  77110. }
  77111. renderPipeline._attachCameras(cameras, unique);
  77112. };
  77113. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  77114. var renderPipeline = this._renderPipelines[renderPipelineName];
  77115. if (!renderPipeline) {
  77116. return;
  77117. }
  77118. renderPipeline._detachCameras(cameras);
  77119. };
  77120. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77121. var renderPipeline = this._renderPipelines[renderPipelineName];
  77122. if (!renderPipeline) {
  77123. return;
  77124. }
  77125. renderPipeline._enableEffect(renderEffectName, cameras);
  77126. };
  77127. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77128. var renderPipeline = this._renderPipelines[renderPipelineName];
  77129. if (!renderPipeline) {
  77130. return;
  77131. }
  77132. renderPipeline._disableEffect(renderEffectName, cameras);
  77133. };
  77134. PostProcessRenderPipelineManager.prototype.update = function () {
  77135. for (var renderPipelineName in this._renderPipelines) {
  77136. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77137. var pipeline = this._renderPipelines[renderPipelineName];
  77138. if (!pipeline.isSupported) {
  77139. pipeline.dispose();
  77140. delete this._renderPipelines[renderPipelineName];
  77141. }
  77142. else {
  77143. pipeline._update();
  77144. }
  77145. }
  77146. }
  77147. };
  77148. /** @hidden */
  77149. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  77150. for (var renderPipelineName in this._renderPipelines) {
  77151. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77152. var pipeline = this._renderPipelines[renderPipelineName];
  77153. pipeline._rebuild();
  77154. }
  77155. }
  77156. };
  77157. PostProcessRenderPipelineManager.prototype.dispose = function () {
  77158. for (var renderPipelineName in this._renderPipelines) {
  77159. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77160. var pipeline = this._renderPipelines[renderPipelineName];
  77161. pipeline.dispose();
  77162. }
  77163. }
  77164. };
  77165. return PostProcessRenderPipelineManager;
  77166. }());
  77167. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  77168. })(BABYLON || (BABYLON = {}));
  77169. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  77170. var BABYLON;
  77171. (function (BABYLON) {
  77172. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  77173. get: function () {
  77174. if (!this._postProcessRenderPipelineManager) {
  77175. // Register the G Buffer component to the scene.
  77176. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  77177. if (!component) {
  77178. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  77179. this._addComponent(component);
  77180. }
  77181. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  77182. }
  77183. return this._postProcessRenderPipelineManager;
  77184. },
  77185. enumerable: true,
  77186. configurable: true
  77187. });
  77188. /**
  77189. * Defines the Render Pipeline scene component responsible to rendering pipelines
  77190. */
  77191. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  77192. /**
  77193. * Creates a new instance of the component for the given scene
  77194. * @param scene Defines the scene to register the component in
  77195. */
  77196. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  77197. /**
  77198. * The component name helpfull to identify the component in the list of scene components.
  77199. */
  77200. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  77201. this.scene = scene;
  77202. }
  77203. /**
  77204. * Registers the component in a given scene
  77205. */
  77206. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  77207. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  77208. };
  77209. /**
  77210. * Rebuilds the elements related to this component in case of
  77211. * context lost for instance.
  77212. */
  77213. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  77214. if (this.scene._postProcessRenderPipelineManager) {
  77215. this.scene._postProcessRenderPipelineManager._rebuild();
  77216. }
  77217. };
  77218. /**
  77219. * Disposes the component and the associated ressources
  77220. */
  77221. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  77222. if (this.scene._postProcessRenderPipelineManager) {
  77223. this.scene._postProcessRenderPipelineManager.dispose();
  77224. }
  77225. };
  77226. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77227. if (this.scene._postProcessRenderPipelineManager) {
  77228. this.scene._postProcessRenderPipelineManager.update();
  77229. }
  77230. };
  77231. return PostProcessRenderPipelineManagerSceneComponent;
  77232. }());
  77233. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  77234. })(BABYLON || (BABYLON = {}));
  77235. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  77236. var BABYLON;
  77237. (function (BABYLON) {
  77238. /**
  77239. * This represents a set of one or more post processes in Babylon.
  77240. * A post process can be used to apply a shader to a texture after it is rendered.
  77241. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  77242. */
  77243. var PostProcessRenderEffect = /** @class */ (function () {
  77244. /**
  77245. * Instantiates a post process render effect.
  77246. * A post process can be used to apply a shader to a texture after it is rendered.
  77247. * @param engine The engine the effect is tied to
  77248. * @param name The name of the effect
  77249. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  77250. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  77251. */
  77252. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  77253. this._name = name;
  77254. this._singleInstance = singleInstance || true;
  77255. this._getPostProcesses = getPostProcesses;
  77256. this._cameras = {};
  77257. this._indicesForCamera = {};
  77258. this._postProcesses = {};
  77259. }
  77260. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  77261. /**
  77262. * Checks if all the post processes in the effect are supported.
  77263. */
  77264. get: function () {
  77265. for (var index in this._postProcesses) {
  77266. if (this._postProcesses.hasOwnProperty(index)) {
  77267. var pps = this._postProcesses[index];
  77268. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  77269. if (!pps[ppIndex].isSupported) {
  77270. return false;
  77271. }
  77272. }
  77273. }
  77274. }
  77275. return true;
  77276. },
  77277. enumerable: true,
  77278. configurable: true
  77279. });
  77280. /**
  77281. * Updates the current state of the effect
  77282. * @hidden
  77283. */
  77284. PostProcessRenderEffect.prototype._update = function () {
  77285. };
  77286. /**
  77287. * Attaches the effect on cameras
  77288. * @param cameras The camera to attach to.
  77289. * @hidden
  77290. */
  77291. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  77292. var _this = this;
  77293. var cameraKey;
  77294. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77295. if (!cams) {
  77296. return;
  77297. }
  77298. for (var i = 0; i < cams.length; i++) {
  77299. var camera = cams[i];
  77300. var cameraName = camera.name;
  77301. if (this._singleInstance) {
  77302. cameraKey = 0;
  77303. }
  77304. else {
  77305. cameraKey = cameraName;
  77306. }
  77307. if (!this._postProcesses[cameraKey]) {
  77308. var postProcess = this._getPostProcesses();
  77309. if (postProcess) {
  77310. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  77311. }
  77312. }
  77313. if (!this._indicesForCamera[cameraName]) {
  77314. this._indicesForCamera[cameraName] = [];
  77315. }
  77316. this._postProcesses[cameraKey].forEach(function (postProcess) {
  77317. var index = camera.attachPostProcess(postProcess);
  77318. _this._indicesForCamera[cameraName].push(index);
  77319. });
  77320. if (!this._cameras[cameraName]) {
  77321. this._cameras[cameraName] = camera;
  77322. }
  77323. }
  77324. };
  77325. /**
  77326. * Detatches the effect on cameras
  77327. * @param cameras The camera to detatch from.
  77328. * @hidden
  77329. */
  77330. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  77331. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77332. if (!cams) {
  77333. return;
  77334. }
  77335. for (var i = 0; i < cams.length; i++) {
  77336. var camera = cams[i];
  77337. var cameraName = camera.name;
  77338. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77339. camera.detachPostProcess(postProcess);
  77340. });
  77341. if (this._cameras[cameraName]) {
  77342. //this._indicesForCamera.splice(index, 1);
  77343. this._cameras[cameraName] = null;
  77344. }
  77345. }
  77346. };
  77347. /**
  77348. * Enables the effect on given cameras
  77349. * @param cameras The camera to enable.
  77350. * @hidden
  77351. */
  77352. PostProcessRenderEffect.prototype._enable = function (cameras) {
  77353. var _this = this;
  77354. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77355. if (!cams) {
  77356. return;
  77357. }
  77358. for (var i = 0; i < cams.length; i++) {
  77359. var camera = cams[i];
  77360. var cameraName = camera.name;
  77361. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  77362. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  77363. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77364. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  77365. });
  77366. }
  77367. }
  77368. }
  77369. };
  77370. /**
  77371. * Disables the effect on the given cameras
  77372. * @param cameras The camera to disable.
  77373. * @hidden
  77374. */
  77375. PostProcessRenderEffect.prototype._disable = function (cameras) {
  77376. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77377. if (!cams) {
  77378. return;
  77379. }
  77380. for (var i = 0; i < cams.length; i++) {
  77381. var camera = cams[i];
  77382. var cameraName = camera.name;
  77383. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77384. camera.detachPostProcess(postProcess);
  77385. });
  77386. }
  77387. };
  77388. /**
  77389. * Gets a list of the post processes contained in the effect.
  77390. * @param camera The camera to get the post processes on.
  77391. * @returns The list of the post processes in the effect.
  77392. */
  77393. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  77394. if (this._singleInstance) {
  77395. return this._postProcesses[0];
  77396. }
  77397. else {
  77398. if (!camera) {
  77399. return null;
  77400. }
  77401. return this._postProcesses[camera.name];
  77402. }
  77403. };
  77404. return PostProcessRenderEffect;
  77405. }());
  77406. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  77407. })(BABYLON || (BABYLON = {}));
  77408. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  77409. var BABYLON;
  77410. (function (BABYLON) {
  77411. var PostProcessRenderPipeline = /** @class */ (function () {
  77412. function PostProcessRenderPipeline(engine, name) {
  77413. this.engine = engine;
  77414. this._name = name;
  77415. this._renderEffects = {};
  77416. this._renderEffectsForIsolatedPass = new Array();
  77417. this._cameras = [];
  77418. }
  77419. PostProcessRenderPipeline.prototype.getClassName = function () {
  77420. return "PostProcessRenderPipeline";
  77421. };
  77422. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  77423. get: function () {
  77424. for (var renderEffectName in this._renderEffects) {
  77425. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77426. if (!this._renderEffects[renderEffectName].isSupported) {
  77427. return false;
  77428. }
  77429. }
  77430. }
  77431. return true;
  77432. },
  77433. enumerable: true,
  77434. configurable: true
  77435. });
  77436. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  77437. this._renderEffects[renderEffect._name] = renderEffect;
  77438. };
  77439. // private
  77440. /** @hidden */
  77441. PostProcessRenderPipeline.prototype._rebuild = function () {
  77442. };
  77443. /** @hidden */
  77444. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  77445. var renderEffects = this._renderEffects[renderEffectName];
  77446. if (!renderEffects) {
  77447. return;
  77448. }
  77449. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77450. };
  77451. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  77452. var renderEffects = this._renderEffects[renderEffectName];
  77453. if (!renderEffects) {
  77454. return;
  77455. }
  77456. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77457. };
  77458. /** @hidden */
  77459. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  77460. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77461. if (!cams) {
  77462. return;
  77463. }
  77464. var indicesToDelete = [];
  77465. var i;
  77466. for (i = 0; i < cams.length; i++) {
  77467. var camera = cams[i];
  77468. var cameraName = camera.name;
  77469. if (this._cameras.indexOf(camera) === -1) {
  77470. this._cameras[cameraName] = camera;
  77471. }
  77472. else if (unique) {
  77473. indicesToDelete.push(i);
  77474. }
  77475. }
  77476. for (i = 0; i < indicesToDelete.length; i++) {
  77477. cameras.splice(indicesToDelete[i], 1);
  77478. }
  77479. for (var renderEffectName in this._renderEffects) {
  77480. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77481. this._renderEffects[renderEffectName]._attachCameras(cams);
  77482. }
  77483. }
  77484. };
  77485. /** @hidden */
  77486. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  77487. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77488. if (!cams) {
  77489. return;
  77490. }
  77491. for (var renderEffectName in this._renderEffects) {
  77492. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77493. this._renderEffects[renderEffectName]._detachCameras(cams);
  77494. }
  77495. }
  77496. for (var i = 0; i < cams.length; i++) {
  77497. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  77498. }
  77499. };
  77500. /** @hidden */
  77501. PostProcessRenderPipeline.prototype._update = function () {
  77502. for (var renderEffectName in this._renderEffects) {
  77503. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77504. this._renderEffects[renderEffectName]._update();
  77505. }
  77506. }
  77507. for (var i = 0; i < this._cameras.length; i++) {
  77508. var cameraName = this._cameras[i].name;
  77509. if (this._renderEffectsForIsolatedPass[cameraName]) {
  77510. this._renderEffectsForIsolatedPass[cameraName]._update();
  77511. }
  77512. }
  77513. };
  77514. /** @hidden */
  77515. PostProcessRenderPipeline.prototype._reset = function () {
  77516. this._renderEffects = {};
  77517. this._renderEffectsForIsolatedPass = new Array();
  77518. };
  77519. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  77520. // 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)
  77521. var effectKeys = Object.keys(this._renderEffects);
  77522. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  77523. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  77524. if (postProcesses) {
  77525. postProcesses[0].samples = sampleCount;
  77526. return true;
  77527. }
  77528. }
  77529. return false;
  77530. };
  77531. PostProcessRenderPipeline.prototype.dispose = function () {
  77532. // Must be implemented by children
  77533. };
  77534. __decorate([
  77535. BABYLON.serialize()
  77536. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  77537. return PostProcessRenderPipeline;
  77538. }());
  77539. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  77540. })(BABYLON || (BABYLON = {}));
  77541. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  77542. var BABYLON;
  77543. (function (BABYLON) {
  77544. /**
  77545. * This represents a depth renderer in Babylon.
  77546. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  77547. */
  77548. var DepthRenderer = /** @class */ (function () {
  77549. /**
  77550. * Instantiates a depth renderer
  77551. * @param scene The scene the renderer belongs to
  77552. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  77553. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  77554. */
  77555. function DepthRenderer(scene, type, camera) {
  77556. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  77557. if (camera === void 0) { camera = null; }
  77558. var _this = this;
  77559. /**
  77560. * Specifiess that the depth renderer will only be used within
  77561. * the camera it is created for.
  77562. * This can help forcing its rendering during the camera processing.
  77563. */
  77564. this.useOnlyInActiveCamera = false;
  77565. this._scene = scene;
  77566. // Register the G Buffer component to the scene.
  77567. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  77568. if (!component) {
  77569. component = new BABYLON.DepthRendererSceneComponent(scene);
  77570. scene._addComponent(component);
  77571. }
  77572. this._camera = camera;
  77573. var engine = scene.getEngine();
  77574. // Render target
  77575. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  77576. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77577. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77578. this._depthMap.refreshRate = 1;
  77579. this._depthMap.renderParticles = false;
  77580. this._depthMap.renderList = null;
  77581. // Camera to get depth map from to support multiple concurrent cameras
  77582. this._depthMap.activeCamera = this._camera;
  77583. this._depthMap.ignoreCameraViewport = true;
  77584. this._depthMap.useCameraPostProcesses = false;
  77585. // set default depth value to 1.0 (far away)
  77586. this._depthMap.onClearObservable.add(function (engine) {
  77587. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  77588. });
  77589. // Custom render function
  77590. var renderSubMesh = function (subMesh) {
  77591. var mesh = subMesh.getRenderingMesh();
  77592. var scene = _this._scene;
  77593. var engine = scene.getEngine();
  77594. var material = subMesh.getMaterial();
  77595. if (!material) {
  77596. return;
  77597. }
  77598. // Culling and reverse (right handed system)
  77599. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77600. // Managing instances
  77601. var batch = mesh._getInstancesRenderList(subMesh._id);
  77602. if (batch.mustReturn) {
  77603. return;
  77604. }
  77605. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77606. var camera = _this._camera || scene.activeCamera;
  77607. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  77608. engine.enableEffect(_this._effect);
  77609. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77610. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77611. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  77612. // Alpha test
  77613. if (material && material.needAlphaTesting()) {
  77614. var alphaTexture = material.getAlphaTestTexture();
  77615. if (alphaTexture) {
  77616. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77617. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77618. }
  77619. }
  77620. // Bones
  77621. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77622. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77623. }
  77624. // Draw
  77625. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77626. }
  77627. };
  77628. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77629. var index;
  77630. if (depthOnlySubMeshes.length) {
  77631. engine.setColorWrite(false);
  77632. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77633. renderSubMesh(depthOnlySubMeshes.data[index]);
  77634. }
  77635. engine.setColorWrite(true);
  77636. }
  77637. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77638. renderSubMesh(opaqueSubMeshes.data[index]);
  77639. }
  77640. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77641. renderSubMesh(alphaTestSubMeshes.data[index]);
  77642. }
  77643. };
  77644. }
  77645. /**
  77646. * Creates the depth rendering effect and checks if the effect is ready.
  77647. * @param subMesh The submesh to be used to render the depth map of
  77648. * @param useInstances If multiple world instances should be used
  77649. * @returns if the depth renderer is ready to render the depth map
  77650. */
  77651. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  77652. var material = subMesh.getMaterial();
  77653. if (material.disableDepthWrite) {
  77654. return false;
  77655. }
  77656. var defines = [];
  77657. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77658. var mesh = subMesh.getMesh();
  77659. // Alpha test
  77660. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  77661. defines.push("#define ALPHATEST");
  77662. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77663. attribs.push(BABYLON.VertexBuffer.UVKind);
  77664. defines.push("#define UV1");
  77665. }
  77666. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77667. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77668. defines.push("#define UV2");
  77669. }
  77670. }
  77671. // Bones
  77672. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77673. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77674. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77675. if (mesh.numBoneInfluencers > 4) {
  77676. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77677. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77678. }
  77679. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77680. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77681. }
  77682. else {
  77683. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77684. }
  77685. // Instances
  77686. if (useInstances) {
  77687. defines.push("#define INSTANCES");
  77688. attribs.push("world0");
  77689. attribs.push("world1");
  77690. attribs.push("world2");
  77691. attribs.push("world3");
  77692. }
  77693. // Get correct effect
  77694. var join = defines.join("\n");
  77695. if (this._cachedDefines !== join) {
  77696. this._cachedDefines = join;
  77697. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  77698. }
  77699. return this._effect.isReady();
  77700. };
  77701. /**
  77702. * Gets the texture which the depth map will be written to.
  77703. * @returns The depth map texture
  77704. */
  77705. DepthRenderer.prototype.getDepthMap = function () {
  77706. return this._depthMap;
  77707. };
  77708. /**
  77709. * Disposes of the depth renderer.
  77710. */
  77711. DepthRenderer.prototype.dispose = function () {
  77712. this._depthMap.dispose();
  77713. };
  77714. return DepthRenderer;
  77715. }());
  77716. BABYLON.DepthRenderer = DepthRenderer;
  77717. })(BABYLON || (BABYLON = {}));
  77718. //# sourceMappingURL=babylon.depthRenderer.js.map
  77719. var BABYLON;
  77720. (function (BABYLON) {
  77721. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  77722. camera = camera || this.activeCamera;
  77723. if (!camera) {
  77724. throw "No camera available to enable depth renderer";
  77725. }
  77726. if (!this._depthRenderer) {
  77727. this._depthRenderer = {};
  77728. }
  77729. if (!this._depthRenderer[camera.id]) {
  77730. var textureType = 0;
  77731. if (this.getEngine().getCaps().textureHalfFloatRender) {
  77732. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77733. }
  77734. else if (this.getEngine().getCaps().textureFloatRender) {
  77735. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77736. }
  77737. else {
  77738. throw "Depth renderer does not support int texture type";
  77739. }
  77740. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  77741. }
  77742. return this._depthRenderer[camera.id];
  77743. };
  77744. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  77745. camera = camera || this.activeCamera;
  77746. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  77747. return;
  77748. }
  77749. this._depthRenderer[camera.id].dispose();
  77750. delete this._depthRenderer[camera.id];
  77751. };
  77752. /**
  77753. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  77754. * in several rendering techniques.
  77755. */
  77756. var DepthRendererSceneComponent = /** @class */ (function () {
  77757. /**
  77758. * Creates a new instance of the component for the given scene
  77759. * @param scene Defines the scene to register the component in
  77760. */
  77761. function DepthRendererSceneComponent(scene) {
  77762. /**
  77763. * The component name helpfull to identify the component in the list of scene components.
  77764. */
  77765. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  77766. this.scene = scene;
  77767. }
  77768. /**
  77769. * Registers the component in a given scene
  77770. */
  77771. DepthRendererSceneComponent.prototype.register = function () {
  77772. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  77773. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  77774. };
  77775. /**
  77776. * Rebuilds the elements related to this component in case of
  77777. * context lost for instance.
  77778. */
  77779. DepthRendererSceneComponent.prototype.rebuild = function () {
  77780. // Nothing to do for this component
  77781. };
  77782. /**
  77783. * Disposes the component and the associated ressources
  77784. */
  77785. DepthRendererSceneComponent.prototype.dispose = function () {
  77786. for (var key in this.scene._depthRenderer) {
  77787. this.scene._depthRenderer[key].dispose();
  77788. }
  77789. };
  77790. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77791. if (this.scene._depthRenderer) {
  77792. for (var key in this.scene._depthRenderer) {
  77793. var depthRenderer = this.scene._depthRenderer[key];
  77794. if (!depthRenderer.useOnlyInActiveCamera) {
  77795. renderTargets.push(depthRenderer.getDepthMap());
  77796. }
  77797. }
  77798. }
  77799. };
  77800. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  77801. if (this.scene._depthRenderer) {
  77802. for (var key in this.scene._depthRenderer) {
  77803. var depthRenderer = this.scene._depthRenderer[key];
  77804. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  77805. renderTargets.push(depthRenderer.getDepthMap());
  77806. }
  77807. }
  77808. }
  77809. };
  77810. return DepthRendererSceneComponent;
  77811. }());
  77812. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  77813. })(BABYLON || (BABYLON = {}));
  77814. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  77815. var BABYLON;
  77816. (function (BABYLON) {
  77817. /**
  77818. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77819. */
  77820. var GeometryBufferRenderer = /** @class */ (function () {
  77821. /**
  77822. * Creates a new G Buffer for the scene
  77823. * @param scene The scene the buffer belongs to
  77824. * @param ratio How big is the buffer related to the main canvas.
  77825. */
  77826. function GeometryBufferRenderer(scene, ratio) {
  77827. if (ratio === void 0) { ratio = 1; }
  77828. this._enablePosition = false;
  77829. this._scene = scene;
  77830. this._ratio = ratio;
  77831. // Register the G Buffer component to the scene.
  77832. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  77833. if (!component) {
  77834. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  77835. scene._addComponent(component);
  77836. }
  77837. // Render target
  77838. this._createRenderTargets();
  77839. }
  77840. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77841. /**
  77842. * Set the render list (meshes to be rendered) used in the G buffer.
  77843. */
  77844. set: function (meshes) {
  77845. this._multiRenderTarget.renderList = meshes;
  77846. },
  77847. enumerable: true,
  77848. configurable: true
  77849. });
  77850. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77851. /**
  77852. * Gets wether or not G buffer are supported by the running hardware.
  77853. * This requires draw buffer supports
  77854. */
  77855. get: function () {
  77856. return this._multiRenderTarget.isSupported;
  77857. },
  77858. enumerable: true,
  77859. configurable: true
  77860. });
  77861. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77862. /**
  77863. * Gets wether or not position are enabled for the G buffer.
  77864. */
  77865. get: function () {
  77866. return this._enablePosition;
  77867. },
  77868. /**
  77869. * Sets wether or not position are enabled for the G buffer.
  77870. */
  77871. set: function (enable) {
  77872. this._enablePosition = enable;
  77873. this.dispose();
  77874. this._createRenderTargets();
  77875. },
  77876. enumerable: true,
  77877. configurable: true
  77878. });
  77879. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77880. /**
  77881. * Gets the scene associated with the buffer.
  77882. */
  77883. get: function () {
  77884. return this._scene;
  77885. },
  77886. enumerable: true,
  77887. configurable: true
  77888. });
  77889. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77890. /**
  77891. * Gets the ratio used by the buffer during its creation.
  77892. * How big is the buffer related to the main canvas.
  77893. */
  77894. get: function () {
  77895. return this._ratio;
  77896. },
  77897. enumerable: true,
  77898. configurable: true
  77899. });
  77900. /**
  77901. * Checks wether everything is ready to render a submesh to the G buffer.
  77902. * @param subMesh the submesh to check readiness for
  77903. * @param useInstances is the mesh drawn using instance or not
  77904. * @returns true if ready otherwise false
  77905. */
  77906. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77907. var material = subMesh.getMaterial();
  77908. if (material && material.disableDepthWrite) {
  77909. return false;
  77910. }
  77911. var defines = [];
  77912. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77913. var mesh = subMesh.getMesh();
  77914. // Alpha test
  77915. if (material && material.needAlphaTesting()) {
  77916. defines.push("#define ALPHATEST");
  77917. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77918. attribs.push(BABYLON.VertexBuffer.UVKind);
  77919. defines.push("#define UV1");
  77920. }
  77921. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77922. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77923. defines.push("#define UV2");
  77924. }
  77925. }
  77926. // Buffers
  77927. if (this._enablePosition) {
  77928. defines.push("#define POSITION");
  77929. }
  77930. // Bones
  77931. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77932. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77933. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77934. if (mesh.numBoneInfluencers > 4) {
  77935. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77936. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77937. }
  77938. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77939. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77940. }
  77941. else {
  77942. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77943. }
  77944. // Instances
  77945. if (useInstances) {
  77946. defines.push("#define INSTANCES");
  77947. attribs.push("world0");
  77948. attribs.push("world1");
  77949. attribs.push("world2");
  77950. attribs.push("world3");
  77951. }
  77952. // Get correct effect
  77953. var join = defines.join("\n");
  77954. if (this._cachedDefines !== join) {
  77955. this._cachedDefines = join;
  77956. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77957. }
  77958. return this._effect.isReady();
  77959. };
  77960. /**
  77961. * Gets the current underlying G Buffer.
  77962. * @returns the buffer
  77963. */
  77964. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77965. return this._multiRenderTarget;
  77966. };
  77967. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77968. /**
  77969. * Gets the number of samples used to render the buffer (anti aliasing).
  77970. */
  77971. get: function () {
  77972. return this._multiRenderTarget.samples;
  77973. },
  77974. /**
  77975. * Sets the number of samples used to render the buffer (anti aliasing).
  77976. */
  77977. set: function (value) {
  77978. this._multiRenderTarget.samples = value;
  77979. },
  77980. enumerable: true,
  77981. configurable: true
  77982. });
  77983. /**
  77984. * Disposes the renderer and frees up associated resources.
  77985. */
  77986. GeometryBufferRenderer.prototype.dispose = function () {
  77987. this.getGBuffer().dispose();
  77988. };
  77989. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77990. var _this = this;
  77991. var engine = this._scene.getEngine();
  77992. var count = this._enablePosition ? 3 : 2;
  77993. 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 });
  77994. if (!this.isSupported) {
  77995. return;
  77996. }
  77997. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77998. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77999. this._multiRenderTarget.refreshRate = 1;
  78000. this._multiRenderTarget.renderParticles = false;
  78001. this._multiRenderTarget.renderList = null;
  78002. // set default depth value to 1.0 (far away)
  78003. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78004. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78005. });
  78006. // Custom render function
  78007. var renderSubMesh = function (subMesh) {
  78008. var mesh = subMesh.getRenderingMesh();
  78009. var scene = _this._scene;
  78010. var engine = scene.getEngine();
  78011. var material = subMesh.getMaterial();
  78012. if (!material) {
  78013. return;
  78014. }
  78015. // Culling
  78016. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78017. // Managing instances
  78018. var batch = mesh._getInstancesRenderList(subMesh._id);
  78019. if (batch.mustReturn) {
  78020. return;
  78021. }
  78022. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78023. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78024. engine.enableEffect(_this._effect);
  78025. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78026. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78027. _this._effect.setMatrix("view", scene.getViewMatrix());
  78028. // Alpha test
  78029. if (material && material.needAlphaTesting()) {
  78030. var alphaTexture = material.getAlphaTestTexture();
  78031. if (alphaTexture) {
  78032. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78033. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78034. }
  78035. }
  78036. // Bones
  78037. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78038. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78039. }
  78040. // Draw
  78041. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78042. }
  78043. };
  78044. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78045. var index;
  78046. if (depthOnlySubMeshes.length) {
  78047. engine.setColorWrite(false);
  78048. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78049. renderSubMesh(depthOnlySubMeshes.data[index]);
  78050. }
  78051. engine.setColorWrite(true);
  78052. }
  78053. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78054. renderSubMesh(opaqueSubMeshes.data[index]);
  78055. }
  78056. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78057. renderSubMesh(alphaTestSubMeshes.data[index]);
  78058. }
  78059. };
  78060. };
  78061. return GeometryBufferRenderer;
  78062. }());
  78063. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78064. })(BABYLON || (BABYLON = {}));
  78065. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78066. var BABYLON;
  78067. (function (BABYLON) {
  78068. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  78069. get: function () {
  78070. this._geometryBufferRenderer;
  78071. },
  78072. set: function (value) {
  78073. if (value && value.isSupported) {
  78074. this._geometryBufferRenderer = value;
  78075. }
  78076. ;
  78077. },
  78078. enumerable: true,
  78079. configurable: true
  78080. });
  78081. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  78082. if (ratio === void 0) { ratio = 1; }
  78083. if (this._geometryBufferRenderer) {
  78084. return this._geometryBufferRenderer;
  78085. }
  78086. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  78087. if (!this._geometryBufferRenderer.isSupported) {
  78088. this._geometryBufferRenderer = null;
  78089. }
  78090. return this._geometryBufferRenderer;
  78091. };
  78092. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  78093. if (!this._geometryBufferRenderer) {
  78094. return;
  78095. }
  78096. this._geometryBufferRenderer.dispose();
  78097. this._geometryBufferRenderer = null;
  78098. };
  78099. /**
  78100. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  78101. * in several rendering techniques.
  78102. */
  78103. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  78104. /**
  78105. * Creates a new instance of the component for the given scene
  78106. * @param scene Defines the scene to register the component in
  78107. */
  78108. function GeometryBufferRendererSceneComponent(scene) {
  78109. /**
  78110. * The component name helpfull to identify the component in the list of scene components.
  78111. */
  78112. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  78113. this.scene = scene;
  78114. }
  78115. /**
  78116. * Registers the component in a given scene
  78117. */
  78118. GeometryBufferRendererSceneComponent.prototype.register = function () {
  78119. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  78120. };
  78121. /**
  78122. * Rebuilds the elements related to this component in case of
  78123. * context lost for instance.
  78124. */
  78125. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  78126. // Nothing to do for this component
  78127. };
  78128. /**
  78129. * Disposes the component and the associated ressources
  78130. */
  78131. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  78132. // Nothing to do for this component
  78133. };
  78134. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78135. if (this.scene._geometryBufferRenderer) {
  78136. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  78137. }
  78138. };
  78139. return GeometryBufferRendererSceneComponent;
  78140. }());
  78141. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  78142. })(BABYLON || (BABYLON = {}));
  78143. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  78144. var BABYLON;
  78145. (function (BABYLON) {
  78146. var SSAORenderingPipeline = /** @class */ (function (_super) {
  78147. __extends(SSAORenderingPipeline, _super);
  78148. /**
  78149. * @constructor
  78150. * @param {string} name - The rendering pipeline name
  78151. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78152. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  78153. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78154. */
  78155. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  78156. var _this = _super.call(this, scene.getEngine(), name) || this;
  78157. // Members
  78158. /**
  78159. * The PassPostProcess id in the pipeline that contains the original scene color
  78160. */
  78161. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78162. /**
  78163. * The SSAO PostProcess id in the pipeline
  78164. */
  78165. _this.SSAORenderEffect = "SSAORenderEffect";
  78166. /**
  78167. * The horizontal blur PostProcess id in the pipeline
  78168. */
  78169. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78170. /**
  78171. * The vertical blur PostProcess id in the pipeline
  78172. */
  78173. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78174. /**
  78175. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78176. */
  78177. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78178. /**
  78179. * The output strength of the SSAO post-process. Default value is 1.0.
  78180. */
  78181. _this.totalStrength = 1.0;
  78182. /**
  78183. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  78184. */
  78185. _this.radius = 0.0001;
  78186. /**
  78187. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  78188. * Must not be equal to fallOff and superior to fallOff.
  78189. * Default value is 0.975
  78190. */
  78191. _this.area = 0.0075;
  78192. /**
  78193. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  78194. * Must not be equal to area and inferior to area.
  78195. * Default value is 0.0
  78196. */
  78197. _this.fallOff = 0.000001;
  78198. /**
  78199. * The base color of the SSAO post-process
  78200. * The final result is "base + ssao" between [0, 1]
  78201. */
  78202. _this.base = 0.5;
  78203. _this._firstUpdate = true;
  78204. _this._scene = scene;
  78205. // Set up assets
  78206. _this._createRandomTexture();
  78207. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78208. var ssaoRatio = ratio.ssaoRatio || ratio;
  78209. var combineRatio = ratio.combineRatio || ratio;
  78210. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78211. _this._createSSAOPostProcess(ssaoRatio);
  78212. _this._createBlurPostProcess(ssaoRatio);
  78213. _this._createSSAOCombinePostProcess(combineRatio);
  78214. // Set up pipeline
  78215. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78216. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78217. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78218. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78219. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78220. // Finish
  78221. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78222. if (cameras)
  78223. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78224. return _this;
  78225. }
  78226. // Public Methods
  78227. /**
  78228. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78229. */
  78230. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78231. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78232. for (var i = 0; i < this._scene.cameras.length; i++) {
  78233. var camera = this._scene.cameras[i];
  78234. this._originalColorPostProcess.dispose(camera);
  78235. this._ssaoPostProcess.dispose(camera);
  78236. this._blurHPostProcess.dispose(camera);
  78237. this._blurVPostProcess.dispose(camera);
  78238. this._ssaoCombinePostProcess.dispose(camera);
  78239. }
  78240. this._randomTexture.dispose();
  78241. if (disableDepthRender)
  78242. this._scene.disableDepthRenderer();
  78243. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78244. _super.prototype.dispose.call(this);
  78245. };
  78246. // Private Methods
  78247. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  78248. var _this = this;
  78249. var size = 16;
  78250. 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);
  78251. 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);
  78252. this._blurHPostProcess.onActivateObservable.add(function () {
  78253. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  78254. _this._blurHPostProcess.kernel = size * dw;
  78255. });
  78256. this._blurVPostProcess.onActivateObservable.add(function () {
  78257. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  78258. _this._blurVPostProcess.kernel = size * dw;
  78259. });
  78260. };
  78261. /** @hidden */
  78262. SSAORenderingPipeline.prototype._rebuild = function () {
  78263. this._firstUpdate = true;
  78264. _super.prototype._rebuild.call(this);
  78265. };
  78266. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78267. var _this = this;
  78268. var numSamples = 16;
  78269. var sampleSphere = [
  78270. 0.5381, 0.1856, -0.4319,
  78271. 0.1379, 0.2486, 0.4430,
  78272. 0.3371, 0.5679, -0.0057,
  78273. -0.6999, -0.0451, -0.0019,
  78274. 0.0689, -0.1598, -0.8547,
  78275. 0.0560, 0.0069, -0.1843,
  78276. -0.0146, 0.1402, 0.0762,
  78277. 0.0100, -0.1924, -0.0344,
  78278. -0.3577, -0.5301, -0.4358,
  78279. -0.3169, 0.1063, 0.0158,
  78280. 0.0103, -0.5869, 0.0046,
  78281. -0.0897, -0.4940, 0.3287,
  78282. 0.7119, -0.0154, -0.0918,
  78283. -0.0533, 0.0596, -0.5411,
  78284. 0.0352, -0.0631, 0.5460,
  78285. -0.4776, 0.2847, -0.0271
  78286. ];
  78287. var samplesFactor = 1.0 / numSamples;
  78288. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  78289. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78290. "area", "fallOff", "base", "range", "viewport"
  78291. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78292. this._ssaoPostProcess.onApply = function (effect) {
  78293. if (_this._firstUpdate) {
  78294. effect.setArray3("sampleSphere", sampleSphere);
  78295. effect.setFloat("samplesFactor", samplesFactor);
  78296. effect.setFloat("randTextureTiles", 4.0);
  78297. }
  78298. effect.setFloat("totalStrength", _this.totalStrength);
  78299. effect.setFloat("radius", _this.radius);
  78300. effect.setFloat("area", _this.area);
  78301. effect.setFloat("fallOff", _this.fallOff);
  78302. effect.setFloat("base", _this.base);
  78303. effect.setTexture("textureSampler", _this._depthTexture);
  78304. effect.setTexture("randomSampler", _this._randomTexture);
  78305. };
  78306. };
  78307. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78308. var _this = this;
  78309. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78310. this._ssaoCombinePostProcess.onApply = function (effect) {
  78311. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  78312. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78313. };
  78314. };
  78315. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  78316. var size = 512;
  78317. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78318. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78319. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78320. var context = this._randomTexture.getContext();
  78321. var rand = function (min, max) {
  78322. return Math.random() * (max - min) + min;
  78323. };
  78324. var randVector = BABYLON.Vector3.Zero();
  78325. for (var x = 0; x < size; x++) {
  78326. for (var y = 0; y < size; y++) {
  78327. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  78328. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  78329. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  78330. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78331. context.fillRect(x, y, 1, 1);
  78332. }
  78333. }
  78334. this._randomTexture.update(false);
  78335. };
  78336. __decorate([
  78337. BABYLON.serialize()
  78338. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  78339. __decorate([
  78340. BABYLON.serialize()
  78341. ], SSAORenderingPipeline.prototype, "radius", void 0);
  78342. __decorate([
  78343. BABYLON.serialize()
  78344. ], SSAORenderingPipeline.prototype, "area", void 0);
  78345. __decorate([
  78346. BABYLON.serialize()
  78347. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  78348. __decorate([
  78349. BABYLON.serialize()
  78350. ], SSAORenderingPipeline.prototype, "base", void 0);
  78351. return SSAORenderingPipeline;
  78352. }(BABYLON.PostProcessRenderPipeline));
  78353. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  78354. })(BABYLON || (BABYLON = {}));
  78355. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  78356. var BABYLON;
  78357. (function (BABYLON) {
  78358. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  78359. __extends(SSAO2RenderingPipeline, _super);
  78360. /**
  78361. * @constructor
  78362. * @param {string} name - The rendering pipeline name
  78363. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78364. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  78365. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78366. */
  78367. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  78368. var _this = _super.call(this, scene.getEngine(), name) || this;
  78369. // Members
  78370. /**
  78371. * The PassPostProcess id in the pipeline that contains the original scene color
  78372. */
  78373. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78374. /**
  78375. * The SSAO PostProcess id in the pipeline
  78376. */
  78377. _this.SSAORenderEffect = "SSAORenderEffect";
  78378. /**
  78379. * The horizontal blur PostProcess id in the pipeline
  78380. */
  78381. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78382. /**
  78383. * The vertical blur PostProcess id in the pipeline
  78384. */
  78385. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78386. /**
  78387. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78388. */
  78389. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78390. /**
  78391. * The output strength of the SSAO post-process. Default value is 1.0.
  78392. */
  78393. _this.totalStrength = 1.0;
  78394. /**
  78395. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  78396. */
  78397. _this.maxZ = 100.0;
  78398. /**
  78399. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  78400. */
  78401. _this.minZAspect = 0.2;
  78402. _this._samples = 8;
  78403. _this._textureSamples = 1;
  78404. /**
  78405. * Are we using bilateral blur ?
  78406. */
  78407. _this._expensiveBlur = true;
  78408. /**
  78409. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  78410. */
  78411. _this.radius = 2.0;
  78412. /**
  78413. * The base color of the SSAO post-process
  78414. * The final result is "base + ssao" between [0, 1]
  78415. */
  78416. _this.base = 0;
  78417. _this._firstUpdate = true;
  78418. _this._bits = new Uint32Array(1);
  78419. _this._scene = scene;
  78420. _this._ratio = ratio;
  78421. if (!_this.isSupported) {
  78422. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  78423. return _this;
  78424. }
  78425. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  78426. var blurRatio = _this._ratio.blurRatio || ratio;
  78427. // Set up assets
  78428. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  78429. _this._createRandomTexture();
  78430. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  78431. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  78432. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78433. _this._originalColorPostProcess.samples = _this.textureSamples;
  78434. _this._createSSAOPostProcess(1.0);
  78435. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  78436. _this._createSSAOCombinePostProcess(blurRatio);
  78437. // Set up pipeline
  78438. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78439. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78440. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78441. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78442. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78443. // Finish
  78444. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78445. if (cameras)
  78446. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78447. return _this;
  78448. }
  78449. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  78450. get: function () {
  78451. return this._samples;
  78452. },
  78453. /**
  78454. * Number of samples used for the SSAO calculations. Default value is 8
  78455. */
  78456. set: function (n) {
  78457. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  78458. this._samples = n;
  78459. this._sampleSphere = this._generateHemisphere();
  78460. this._firstUpdate = true;
  78461. },
  78462. enumerable: true,
  78463. configurable: true
  78464. });
  78465. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  78466. get: function () {
  78467. return this._textureSamples;
  78468. },
  78469. /**
  78470. * Number of samples to use for antialiasing
  78471. */
  78472. set: function (n) {
  78473. this._textureSamples = n;
  78474. this._originalColorPostProcess.samples = n;
  78475. this._blurHPostProcess.samples = n;
  78476. this._blurVPostProcess.samples = n;
  78477. this._ssaoPostProcess.samples = n;
  78478. this._ssaoCombinePostProcess.samples = n;
  78479. },
  78480. enumerable: true,
  78481. configurable: true
  78482. });
  78483. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  78484. get: function () {
  78485. return this._expensiveBlur;
  78486. },
  78487. set: function (b) {
  78488. 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"]);
  78489. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  78490. this._expensiveBlur = b;
  78491. this._firstUpdate = true;
  78492. },
  78493. enumerable: true,
  78494. configurable: true
  78495. });
  78496. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  78497. /**
  78498. * Support test.
  78499. */
  78500. get: function () {
  78501. var engine = BABYLON.Engine.LastCreatedEngine;
  78502. if (!engine) {
  78503. return false;
  78504. }
  78505. return engine.getCaps().drawBuffersExtension;
  78506. },
  78507. enumerable: true,
  78508. configurable: true
  78509. });
  78510. // Public Methods
  78511. /**
  78512. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78513. */
  78514. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  78515. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  78516. for (var i = 0; i < this._scene.cameras.length; i++) {
  78517. var camera = this._scene.cameras[i];
  78518. this._originalColorPostProcess.dispose(camera);
  78519. this._ssaoPostProcess.dispose(camera);
  78520. this._blurHPostProcess.dispose(camera);
  78521. this._blurVPostProcess.dispose(camera);
  78522. this._ssaoCombinePostProcess.dispose(camera);
  78523. }
  78524. this._randomTexture.dispose();
  78525. if (disableGeometryBufferRenderer)
  78526. this._scene.disableGeometryBufferRenderer();
  78527. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78528. _super.prototype.dispose.call(this);
  78529. };
  78530. // Private Methods
  78531. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  78532. var _this = this;
  78533. this._samplerOffsets = [];
  78534. var expensive = this.expensiveBlur;
  78535. for (var i = -8; i < 8; i++) {
  78536. this._samplerOffsets.push(i * 2 + 0.5);
  78537. }
  78538. 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");
  78539. this._blurHPostProcess.onApply = function (effect) {
  78540. if (!_this._scene.activeCamera) {
  78541. return;
  78542. }
  78543. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  78544. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78545. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78546. effect.setFloat("radius", _this.radius);
  78547. effect.setTexture("depthSampler", _this._depthTexture);
  78548. if (_this._firstUpdate) {
  78549. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78550. }
  78551. };
  78552. 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");
  78553. this._blurVPostProcess.onApply = function (effect) {
  78554. if (!_this._scene.activeCamera) {
  78555. return;
  78556. }
  78557. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  78558. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78559. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78560. effect.setFloat("radius", _this.radius);
  78561. effect.setTexture("depthSampler", _this._depthTexture);
  78562. if (_this._firstUpdate) {
  78563. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78564. _this._firstUpdate = false;
  78565. }
  78566. };
  78567. this._blurHPostProcess.samples = this.textureSamples;
  78568. this._blurVPostProcess.samples = this.textureSamples;
  78569. };
  78570. /** @hidden */
  78571. SSAO2RenderingPipeline.prototype._rebuild = function () {
  78572. this._firstUpdate = true;
  78573. _super.prototype._rebuild.call(this);
  78574. };
  78575. //Van der Corput radical inverse
  78576. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  78577. this._bits[0] = i;
  78578. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  78579. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  78580. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  78581. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  78582. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  78583. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  78584. };
  78585. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  78586. return [i / n, this._radicalInverse_VdC(i)];
  78587. };
  78588. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  78589. var phi = v * 2.0 * Math.PI;
  78590. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  78591. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  78592. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  78593. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  78594. };
  78595. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  78596. var numSamples = this.samples;
  78597. var result = [];
  78598. var vector;
  78599. var i = 0;
  78600. while (i < numSamples) {
  78601. if (numSamples < 16) {
  78602. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  78603. }
  78604. else {
  78605. var rand = this._hammersley(i, numSamples);
  78606. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  78607. }
  78608. result.push(vector.x, vector.y, vector.z);
  78609. i++;
  78610. }
  78611. return result;
  78612. };
  78613. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78614. var _this = this;
  78615. var numSamples = this.samples;
  78616. this._sampleSphere = this._generateHemisphere();
  78617. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  78618. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78619. "base", "range", "projection", "near", "far", "texelSize",
  78620. "xViewport", "yViewport", "maxZ", "minZAspect"
  78621. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78622. this._ssaoPostProcess.onApply = function (effect) {
  78623. if (_this._firstUpdate) {
  78624. effect.setArray3("sampleSphere", _this._sampleSphere);
  78625. effect.setFloat("randTextureTiles", 32.0);
  78626. }
  78627. if (!_this._scene.activeCamera) {
  78628. return;
  78629. }
  78630. effect.setFloat("samplesFactor", 1 / _this.samples);
  78631. effect.setFloat("totalStrength", _this.totalStrength);
  78632. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  78633. effect.setFloat("radius", _this.radius);
  78634. effect.setFloat("maxZ", _this.maxZ);
  78635. effect.setFloat("minZAspect", _this.minZAspect);
  78636. effect.setFloat("base", _this.base);
  78637. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78638. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78639. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  78640. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  78641. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  78642. effect.setTexture("textureSampler", _this._depthTexture);
  78643. effect.setTexture("normalSampler", _this._normalTexture);
  78644. effect.setTexture("randomSampler", _this._randomTexture);
  78645. };
  78646. this._ssaoPostProcess.samples = this.textureSamples;
  78647. };
  78648. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78649. var _this = this;
  78650. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78651. this._ssaoCombinePostProcess.onApply = function (effect) {
  78652. var viewport = _this._scene.activeCamera.viewport;
  78653. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  78654. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78655. };
  78656. this._ssaoCombinePostProcess.samples = this.textureSamples;
  78657. };
  78658. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  78659. var size = 128;
  78660. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78661. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78662. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78663. var context = this._randomTexture.getContext();
  78664. var rand = function (min, max) {
  78665. return Math.random() * (max - min) + min;
  78666. };
  78667. var randVector = BABYLON.Vector3.Zero();
  78668. for (var x = 0; x < size; x++) {
  78669. for (var y = 0; y < size; y++) {
  78670. randVector.x = rand(0.0, 1.0);
  78671. randVector.y = rand(0.0, 1.0);
  78672. randVector.z = 0.0;
  78673. randVector.normalize();
  78674. randVector.scaleInPlace(255);
  78675. randVector.x = Math.floor(randVector.x);
  78676. randVector.y = Math.floor(randVector.y);
  78677. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78678. context.fillRect(x, y, 1, 1);
  78679. }
  78680. }
  78681. this._randomTexture.update(false);
  78682. };
  78683. /**
  78684. * Serialize the rendering pipeline (Used when exporting)
  78685. * @returns the serialized object
  78686. */
  78687. SSAO2RenderingPipeline.prototype.serialize = function () {
  78688. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78689. serializationObject.customType = "SSAO2RenderingPipeline";
  78690. return serializationObject;
  78691. };
  78692. /**
  78693. * Parse the serialized pipeline
  78694. * @param source Source pipeline.
  78695. * @param scene The scene to load the pipeline to.
  78696. * @param rootUrl The URL of the serialized pipeline.
  78697. * @returns An instantiated pipeline from the serialized object.
  78698. */
  78699. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  78700. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78701. };
  78702. __decorate([
  78703. BABYLON.serialize()
  78704. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  78705. __decorate([
  78706. BABYLON.serialize()
  78707. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  78708. __decorate([
  78709. BABYLON.serialize()
  78710. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  78711. __decorate([
  78712. BABYLON.serialize("samples")
  78713. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  78714. __decorate([
  78715. BABYLON.serialize("textureSamples")
  78716. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  78717. __decorate([
  78718. BABYLON.serialize()
  78719. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  78720. __decorate([
  78721. BABYLON.serialize("expensiveBlur")
  78722. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  78723. __decorate([
  78724. BABYLON.serialize()
  78725. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  78726. __decorate([
  78727. BABYLON.serialize()
  78728. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  78729. return SSAO2RenderingPipeline;
  78730. }(BABYLON.PostProcessRenderPipeline));
  78731. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  78732. })(BABYLON || (BABYLON = {}));
  78733. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  78734. // BABYLON.JS Chromatic Aberration GLSL Shader
  78735. // Author: Olivier Guyot
  78736. // Separates very slightly R, G and B colors on the edges of the screen
  78737. // Inspired by Francois Tarlier & Martins Upitis
  78738. var BABYLON;
  78739. (function (BABYLON) {
  78740. var LensRenderingPipeline = /** @class */ (function (_super) {
  78741. __extends(LensRenderingPipeline, _super);
  78742. /**
  78743. * @constructor
  78744. *
  78745. * Effect parameters are as follow:
  78746. * {
  78747. * chromatic_aberration: number; // from 0 to x (1 for realism)
  78748. * edge_blur: number; // from 0 to x (1 for realism)
  78749. * distortion: number; // from 0 to x (1 for realism)
  78750. * grain_amount: number; // from 0 to 1
  78751. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  78752. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  78753. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  78754. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  78755. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  78756. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  78757. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  78758. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  78759. * }
  78760. * Note: if an effect parameter is unset, effect is disabled
  78761. *
  78762. * @param {string} name - The rendering pipeline name
  78763. * @param {object} parameters - An object containing all parameters (see above)
  78764. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78765. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  78766. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78767. */
  78768. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  78769. if (ratio === void 0) { ratio = 1.0; }
  78770. var _this = _super.call(this, scene.getEngine(), name) || this;
  78771. // Lens effects can be of the following:
  78772. // - chromatic aberration (slight shift of RGB colors)
  78773. // - blur on the edge of the lens
  78774. // - lens distortion
  78775. // - depth-of-field blur & highlights enhancing
  78776. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  78777. // - grain effect (noise or custom texture)
  78778. // Two additional texture samplers are needed:
  78779. // - depth map (for depth-of-field)
  78780. // - grain texture
  78781. /**
  78782. * The chromatic aberration PostProcess id in the pipeline
  78783. */
  78784. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  78785. /**
  78786. * The highlights enhancing PostProcess id in the pipeline
  78787. */
  78788. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  78789. /**
  78790. * The depth-of-field PostProcess id in the pipeline
  78791. */
  78792. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  78793. _this._scene = scene;
  78794. // Fetch texture samplers
  78795. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78796. if (parameters.grain_texture) {
  78797. _this._grainTexture = parameters.grain_texture;
  78798. }
  78799. else {
  78800. _this._createGrainTexture();
  78801. }
  78802. // save parameters
  78803. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  78804. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  78805. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  78806. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  78807. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  78808. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  78809. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  78810. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  78811. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  78812. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  78813. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  78814. // Create effects
  78815. _this._createChromaticAberrationPostProcess(ratio);
  78816. _this._createHighlightsPostProcess(ratio);
  78817. _this._createDepthOfFieldPostProcess(ratio / 4);
  78818. // Set up pipeline
  78819. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  78820. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  78821. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  78822. if (_this._highlightsGain === -1) {
  78823. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  78824. }
  78825. // Finish
  78826. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78827. if (cameras) {
  78828. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78829. }
  78830. return _this;
  78831. }
  78832. // public methods (self explanatory)
  78833. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  78834. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  78835. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  78836. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  78837. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  78838. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  78839. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  78840. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  78841. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  78842. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  78843. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  78844. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  78845. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  78846. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  78847. };
  78848. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  78849. this._highlightsPostProcess.updateEffect();
  78850. };
  78851. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  78852. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  78853. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  78854. this._highlightsGain = amount;
  78855. };
  78856. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  78857. if (this._highlightsGain === -1) {
  78858. this._highlightsGain = 1.0;
  78859. }
  78860. this._highlightsThreshold = amount;
  78861. };
  78862. LensRenderingPipeline.prototype.disableHighlights = function () {
  78863. this._highlightsGain = -1;
  78864. };
  78865. /**
  78866. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  78867. */
  78868. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78869. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78870. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78871. this._chromaticAberrationPostProcess = null;
  78872. this._highlightsPostProcess = null;
  78873. this._depthOfFieldPostProcess = null;
  78874. this._grainTexture.dispose();
  78875. if (disableDepthRender)
  78876. this._scene.disableDepthRenderer();
  78877. };
  78878. // colors shifting and distortion
  78879. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  78880. var _this = this;
  78881. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  78882. [], // samplers
  78883. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78884. this._chromaticAberrationPostProcess.onApply = function (effect) {
  78885. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  78886. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78887. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78888. effect.setFloat('radialIntensity', 1);
  78889. effect.setFloat2('direction', 17, 17);
  78890. effect.setFloat2('centerPosition', 0.5, 0.5);
  78891. };
  78892. };
  78893. // highlights enhancing
  78894. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  78895. var _this = this;
  78896. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  78897. [], // samplers
  78898. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  78899. this._highlightsPostProcess.onApply = function (effect) {
  78900. effect.setFloat('gain', _this._highlightsGain);
  78901. effect.setFloat('threshold', _this._highlightsThreshold);
  78902. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  78903. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78904. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78905. };
  78906. };
  78907. // colors shifting and distortion
  78908. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  78909. var _this = this;
  78910. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  78911. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  78912. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  78913. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78914. this._depthOfFieldPostProcess.onApply = function (effect) {
  78915. effect.setTexture("depthSampler", _this._depthTexture);
  78916. effect.setTexture("grainSampler", _this._grainTexture);
  78917. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  78918. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  78919. effect.setFloat('grain_amount', _this._grainAmount);
  78920. effect.setBool('blur_noise', _this._blurNoise);
  78921. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78922. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78923. effect.setFloat('distortion', _this._distortion);
  78924. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  78925. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  78926. effect.setFloat('aperture', _this._dofAperture);
  78927. effect.setFloat('darken', _this._dofDarken);
  78928. effect.setFloat('edge_blur', _this._edgeBlur);
  78929. effect.setBool('highlights', (_this._highlightsGain !== -1));
  78930. if (_this._scene.activeCamera) {
  78931. effect.setFloat('near', _this._scene.activeCamera.minZ);
  78932. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  78933. }
  78934. };
  78935. };
  78936. // creates a black and white random noise texture, 512x512
  78937. LensRenderingPipeline.prototype._createGrainTexture = function () {
  78938. var size = 512;
  78939. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78940. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78941. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78942. var context = this._grainTexture.getContext();
  78943. var rand = function (min, max) {
  78944. return Math.random() * (max - min) + min;
  78945. };
  78946. var value;
  78947. for (var x = 0; x < size; x++) {
  78948. for (var y = 0; y < size; y++) {
  78949. value = Math.floor(rand(0.42, 0.58) * 255);
  78950. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  78951. context.fillRect(x, y, 1, 1);
  78952. }
  78953. }
  78954. this._grainTexture.update(false);
  78955. };
  78956. return LensRenderingPipeline;
  78957. }(BABYLON.PostProcessRenderPipeline));
  78958. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  78959. })(BABYLON || (BABYLON = {}));
  78960. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  78961. var BABYLON;
  78962. (function (BABYLON) {
  78963. var StandardRenderingPipeline = /** @class */ (function (_super) {
  78964. __extends(StandardRenderingPipeline, _super);
  78965. /**
  78966. * @constructor
  78967. * @param {string} name - The rendering pipeline name
  78968. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78969. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  78970. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  78971. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78972. */
  78973. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  78974. if (originalPostProcess === void 0) { originalPostProcess = null; }
  78975. var _this = _super.call(this, scene.getEngine(), name) || this;
  78976. /**
  78977. * Post-process used to down scale an image x4
  78978. */
  78979. _this.downSampleX4PostProcess = null;
  78980. /**
  78981. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  78982. */
  78983. _this.brightPassPostProcess = null;
  78984. /**
  78985. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  78986. */
  78987. _this.blurHPostProcesses = [];
  78988. /**
  78989. * Post-process array storing all the vertical blur post-processes used by the pipeline
  78990. */
  78991. _this.blurVPostProcesses = [];
  78992. /**
  78993. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  78994. */
  78995. _this.textureAdderPostProcess = null;
  78996. /**
  78997. * Post-process used to create volumetric lighting effect
  78998. */
  78999. _this.volumetricLightPostProcess = null;
  79000. /**
  79001. * Post-process used to smooth the previous volumetric light post-process on the X axis
  79002. */
  79003. _this.volumetricLightSmoothXPostProcess = null;
  79004. /**
  79005. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  79006. */
  79007. _this.volumetricLightSmoothYPostProcess = null;
  79008. /**
  79009. * Post-process used to merge the volumetric light effect and the real scene color
  79010. */
  79011. _this.volumetricLightMergePostProces = null;
  79012. /**
  79013. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  79014. */
  79015. _this.volumetricLightFinalPostProcess = null;
  79016. /**
  79017. * Base post-process used to calculate the average luminance of the final image for HDR
  79018. */
  79019. _this.luminancePostProcess = null;
  79020. /**
  79021. * Post-processes used to create down sample post-processes in order to get
  79022. * the average luminance of the final image for HDR
  79023. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  79024. */
  79025. _this.luminanceDownSamplePostProcesses = [];
  79026. /**
  79027. * Post-process used to create a HDR effect (light adaptation)
  79028. */
  79029. _this.hdrPostProcess = null;
  79030. /**
  79031. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  79032. */
  79033. _this.textureAdderFinalPostProcess = null;
  79034. /**
  79035. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  79036. */
  79037. _this.lensFlareFinalPostProcess = null;
  79038. /**
  79039. * Post-process used to merge the final HDR post-process and the real scene color
  79040. */
  79041. _this.hdrFinalPostProcess = null;
  79042. /**
  79043. * Post-process used to create a lens flare effect
  79044. */
  79045. _this.lensFlarePostProcess = null;
  79046. /**
  79047. * Post-process that merges the result of the lens flare post-process and the real scene color
  79048. */
  79049. _this.lensFlareComposePostProcess = null;
  79050. /**
  79051. * Post-process used to create a motion blur effect
  79052. */
  79053. _this.motionBlurPostProcess = null;
  79054. /**
  79055. * Post-process used to create a depth of field effect
  79056. */
  79057. _this.depthOfFieldPostProcess = null;
  79058. /**
  79059. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  79060. */
  79061. _this.fxaaPostProcess = null;
  79062. // Values
  79063. /**
  79064. * Represents the brightness threshold in order to configure the illuminated surfaces
  79065. */
  79066. _this.brightThreshold = 1.0;
  79067. /**
  79068. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  79069. */
  79070. _this.blurWidth = 512.0;
  79071. /**
  79072. * Sets if the blur for highlighted surfaces must be only horizontal
  79073. */
  79074. _this.horizontalBlur = false;
  79075. /**
  79076. * Sets the overall exposure used by the pipeline
  79077. */
  79078. _this.exposure = 1.0;
  79079. /**
  79080. * Texture used typically to simulate "dirty" on camera lens
  79081. */
  79082. _this.lensTexture = null;
  79083. /**
  79084. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  79085. */
  79086. _this.volumetricLightCoefficient = 0.2;
  79087. /**
  79088. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  79089. */
  79090. _this.volumetricLightPower = 4.0;
  79091. /**
  79092. * Used the set the blur intensity to smooth the volumetric lights
  79093. */
  79094. _this.volumetricLightBlurScale = 64.0;
  79095. /**
  79096. * Light (spot or directional) used to generate the volumetric lights rays
  79097. * The source light must have a shadow generate so the pipeline can get its
  79098. * depth map
  79099. */
  79100. _this.sourceLight = null;
  79101. /**
  79102. * For eye adaptation, represents the minimum luminance the eye can see
  79103. */
  79104. _this.hdrMinimumLuminance = 1.0;
  79105. /**
  79106. * For eye adaptation, represents the decrease luminance speed
  79107. */
  79108. _this.hdrDecreaseRate = 0.5;
  79109. /**
  79110. * For eye adaptation, represents the increase luminance speed
  79111. */
  79112. _this.hdrIncreaseRate = 0.5;
  79113. /**
  79114. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  79115. */
  79116. _this.lensColorTexture = null;
  79117. /**
  79118. * The overall strengh for the lens flare effect
  79119. */
  79120. _this.lensFlareStrength = 20.0;
  79121. /**
  79122. * Dispersion coefficient for lens flare ghosts
  79123. */
  79124. _this.lensFlareGhostDispersal = 1.4;
  79125. /**
  79126. * Main lens flare halo width
  79127. */
  79128. _this.lensFlareHaloWidth = 0.7;
  79129. /**
  79130. * Based on the lens distortion effect, defines how much the lens flare result
  79131. * is distorted
  79132. */
  79133. _this.lensFlareDistortionStrength = 16.0;
  79134. /**
  79135. * Lens star texture must be used to simulate rays on the flares and is available
  79136. * in the documentation
  79137. */
  79138. _this.lensStarTexture = null;
  79139. /**
  79140. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  79141. * flare effect by taking account of the dirt texture
  79142. */
  79143. _this.lensFlareDirtTexture = null;
  79144. /**
  79145. * Represents the focal length for the depth of field effect
  79146. */
  79147. _this.depthOfFieldDistance = 10.0;
  79148. /**
  79149. * Represents the blur intensity for the blurred part of the depth of field effect
  79150. */
  79151. _this.depthOfFieldBlurWidth = 64.0;
  79152. /**
  79153. * For motion blur, defines how much the image is blurred by the movement
  79154. */
  79155. _this.motionStrength = 1.0;
  79156. /**
  79157. * List of animations for the pipeline (IAnimatable implementation)
  79158. */
  79159. _this.animations = [];
  79160. _this._currentDepthOfFieldSource = null;
  79161. _this._hdrCurrentLuminance = 1.0;
  79162. // Getters and setters
  79163. _this._bloomEnabled = false;
  79164. _this._depthOfFieldEnabled = false;
  79165. _this._vlsEnabled = false;
  79166. _this._lensFlareEnabled = false;
  79167. _this._hdrEnabled = false;
  79168. _this._motionBlurEnabled = false;
  79169. _this._fxaaEnabled = false;
  79170. _this._motionBlurSamples = 64.0;
  79171. _this._volumetricLightStepsCount = 50.0;
  79172. _this._samples = 1;
  79173. _this._cameras = cameras || [];
  79174. // Initialize
  79175. _this._scene = scene;
  79176. _this._basePostProcess = originalPostProcess;
  79177. _this._ratio = ratio;
  79178. // Misc
  79179. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79180. // Finish
  79181. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79182. _this._buildPipeline();
  79183. return _this;
  79184. }
  79185. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  79186. /**
  79187. * Specifies if the bloom pipeline is enabled
  79188. */
  79189. get: function () {
  79190. return this._bloomEnabled;
  79191. },
  79192. set: function (enabled) {
  79193. if (this._bloomEnabled === enabled) {
  79194. return;
  79195. }
  79196. this._bloomEnabled = enabled;
  79197. this._buildPipeline();
  79198. },
  79199. enumerable: true,
  79200. configurable: true
  79201. });
  79202. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  79203. /**
  79204. * Specifies if the depth of field pipeline is enabed
  79205. */
  79206. get: function () {
  79207. return this._depthOfFieldEnabled;
  79208. },
  79209. set: function (enabled) {
  79210. if (this._depthOfFieldEnabled === enabled) {
  79211. return;
  79212. }
  79213. this._depthOfFieldEnabled = enabled;
  79214. this._buildPipeline();
  79215. },
  79216. enumerable: true,
  79217. configurable: true
  79218. });
  79219. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  79220. /**
  79221. * Specifies if the lens flare pipeline is enabed
  79222. */
  79223. get: function () {
  79224. return this._lensFlareEnabled;
  79225. },
  79226. set: function (enabled) {
  79227. if (this._lensFlareEnabled === enabled) {
  79228. return;
  79229. }
  79230. this._lensFlareEnabled = enabled;
  79231. this._buildPipeline();
  79232. },
  79233. enumerable: true,
  79234. configurable: true
  79235. });
  79236. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  79237. /**
  79238. * Specifies if the HDR pipeline is enabled
  79239. */
  79240. get: function () {
  79241. return this._hdrEnabled;
  79242. },
  79243. set: function (enabled) {
  79244. if (this._hdrEnabled === enabled) {
  79245. return;
  79246. }
  79247. this._hdrEnabled = enabled;
  79248. this._buildPipeline();
  79249. },
  79250. enumerable: true,
  79251. configurable: true
  79252. });
  79253. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  79254. /**
  79255. * Specifies if the volumetric lights scattering effect is enabled
  79256. */
  79257. get: function () {
  79258. return this._vlsEnabled;
  79259. },
  79260. set: function (enabled) {
  79261. if (this._vlsEnabled === enabled) {
  79262. return;
  79263. }
  79264. if (enabled) {
  79265. var geometry = this._scene.enableGeometryBufferRenderer();
  79266. if (!geometry) {
  79267. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  79268. return;
  79269. }
  79270. }
  79271. this._vlsEnabled = enabled;
  79272. this._buildPipeline();
  79273. },
  79274. enumerable: true,
  79275. configurable: true
  79276. });
  79277. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  79278. /**
  79279. * Specifies if the motion blur effect is enabled
  79280. */
  79281. get: function () {
  79282. return this._motionBlurEnabled;
  79283. },
  79284. set: function (enabled) {
  79285. if (this._motionBlurEnabled === enabled) {
  79286. return;
  79287. }
  79288. this._motionBlurEnabled = enabled;
  79289. this._buildPipeline();
  79290. },
  79291. enumerable: true,
  79292. configurable: true
  79293. });
  79294. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  79295. /**
  79296. * Specifies if anti-aliasing is enabled
  79297. */
  79298. get: function () {
  79299. return this._fxaaEnabled;
  79300. },
  79301. set: function (enabled) {
  79302. if (this._fxaaEnabled === enabled) {
  79303. return;
  79304. }
  79305. this._fxaaEnabled = enabled;
  79306. this._buildPipeline();
  79307. },
  79308. enumerable: true,
  79309. configurable: true
  79310. });
  79311. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  79312. /**
  79313. * Specifies the number of steps used to calculate the volumetric lights
  79314. * Typically in interval [50, 200]
  79315. */
  79316. get: function () {
  79317. return this._volumetricLightStepsCount;
  79318. },
  79319. set: function (count) {
  79320. if (this.volumetricLightPostProcess) {
  79321. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  79322. }
  79323. this._volumetricLightStepsCount = count;
  79324. },
  79325. enumerable: true,
  79326. configurable: true
  79327. });
  79328. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  79329. /**
  79330. * Specifies the number of samples used for the motion blur effect
  79331. * Typically in interval [16, 64]
  79332. */
  79333. get: function () {
  79334. return this._motionBlurSamples;
  79335. },
  79336. set: function (samples) {
  79337. if (this.motionBlurPostProcess) {
  79338. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  79339. }
  79340. this._motionBlurSamples = samples;
  79341. },
  79342. enumerable: true,
  79343. configurable: true
  79344. });
  79345. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  79346. /**
  79347. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79348. */
  79349. get: function () {
  79350. return this._samples;
  79351. },
  79352. set: function (sampleCount) {
  79353. if (this._samples === sampleCount) {
  79354. return;
  79355. }
  79356. this._samples = sampleCount;
  79357. this._buildPipeline();
  79358. },
  79359. enumerable: true,
  79360. configurable: true
  79361. });
  79362. StandardRenderingPipeline.prototype._buildPipeline = function () {
  79363. var _this = this;
  79364. var ratio = this._ratio;
  79365. var scene = this._scene;
  79366. this._disposePostProcesses();
  79367. this._reset();
  79368. // Create pass post-process
  79369. if (!this._basePostProcess) {
  79370. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  79371. this.originalPostProcess.onApply = function (effect) {
  79372. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  79373. };
  79374. }
  79375. else {
  79376. this.originalPostProcess = this._basePostProcess;
  79377. }
  79378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  79379. this._currentDepthOfFieldSource = this.originalPostProcess;
  79380. if (this._bloomEnabled) {
  79381. // Create down sample X4 post-process
  79382. this._createDownSampleX4PostProcess(scene, ratio / 2);
  79383. // Create bright pass post-process
  79384. this._createBrightPassPostProcess(scene, ratio / 2);
  79385. // Create gaussian blur post-processes (down sampling blurs)
  79386. this._createBlurPostProcesses(scene, ratio / 4, 1);
  79387. // Create texture adder post-process
  79388. this._createTextureAdderPostProcess(scene, ratio);
  79389. // Create depth-of-field source post-process
  79390. 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);
  79391. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  79392. }
  79393. if (this._vlsEnabled) {
  79394. // Create volumetric light
  79395. this._createVolumetricLightPostProcess(scene, ratio);
  79396. // Create volumetric light final post-process
  79397. 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);
  79398. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  79399. }
  79400. if (this._lensFlareEnabled) {
  79401. // Create lens flare post-process
  79402. this._createLensFlarePostProcess(scene, ratio);
  79403. // Create depth-of-field source post-process post lens-flare and disable it now
  79404. 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);
  79405. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  79406. }
  79407. if (this._hdrEnabled) {
  79408. // Create luminance
  79409. this._createLuminancePostProcesses(scene, this._floatTextureType);
  79410. // Create HDR
  79411. this._createHdrPostProcess(scene, ratio);
  79412. // Create depth-of-field source post-process post hdr and disable it now
  79413. 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);
  79414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  79415. }
  79416. if (this._depthOfFieldEnabled) {
  79417. // Create gaussian blur used by depth-of-field
  79418. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  79419. // Create depth-of-field post-process
  79420. this._createDepthOfFieldPostProcess(scene, ratio);
  79421. }
  79422. if (this._motionBlurEnabled) {
  79423. // Create motion blur post-process
  79424. this._createMotionBlurPostProcess(scene, ratio);
  79425. }
  79426. if (this._fxaaEnabled) {
  79427. // Create fxaa post-process
  79428. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79429. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  79430. }
  79431. if (this._cameras !== null) {
  79432. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79433. }
  79434. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  79435. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79436. }
  79437. };
  79438. // Down Sample X4 Post-Processs
  79439. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  79440. var _this = this;
  79441. var downSampleX4Offsets = new Array(32);
  79442. 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);
  79443. this.downSampleX4PostProcess.onApply = function (effect) {
  79444. var id = 0;
  79445. var width = _this.downSampleX4PostProcess.width;
  79446. var height = _this.downSampleX4PostProcess.height;
  79447. for (var i = -2; i < 2; i++) {
  79448. for (var j = -2; j < 2; j++) {
  79449. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  79450. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  79451. id += 2;
  79452. }
  79453. }
  79454. effect.setArray2("dsOffsets", downSampleX4Offsets);
  79455. };
  79456. // Add to pipeline
  79457. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  79458. };
  79459. // Brightpass Post-Process
  79460. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  79461. var _this = this;
  79462. var brightOffsets = new Array(8);
  79463. 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);
  79464. this.brightPassPostProcess.onApply = function (effect) {
  79465. var sU = (1.0 / _this.brightPassPostProcess.width);
  79466. var sV = (1.0 / _this.brightPassPostProcess.height);
  79467. brightOffsets[0] = -0.5 * sU;
  79468. brightOffsets[1] = 0.5 * sV;
  79469. brightOffsets[2] = 0.5 * sU;
  79470. brightOffsets[3] = 0.5 * sV;
  79471. brightOffsets[4] = -0.5 * sU;
  79472. brightOffsets[5] = -0.5 * sV;
  79473. brightOffsets[6] = 0.5 * sU;
  79474. brightOffsets[7] = -0.5 * sV;
  79475. effect.setArray2("dsOffsets", brightOffsets);
  79476. effect.setFloat("brightThreshold", _this.brightThreshold);
  79477. };
  79478. // Add to pipeline
  79479. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  79480. };
  79481. // Create blur H&V post-processes
  79482. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  79483. var _this = this;
  79484. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  79485. var engine = scene.getEngine();
  79486. 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);
  79487. 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);
  79488. blurX.onActivateObservable.add(function () {
  79489. var dw = blurX.width / engine.getRenderWidth();
  79490. blurX.kernel = _this[blurWidthKey] * dw;
  79491. });
  79492. blurY.onActivateObservable.add(function () {
  79493. var dw = blurY.height / engine.getRenderHeight();
  79494. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  79495. });
  79496. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  79497. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  79498. this.blurHPostProcesses.push(blurX);
  79499. this.blurVPostProcesses.push(blurY);
  79500. };
  79501. // Create texture adder post-process
  79502. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  79503. var _this = this;
  79504. 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);
  79505. this.textureAdderPostProcess.onApply = function (effect) {
  79506. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  79507. effect.setTexture("lensSampler", _this.lensTexture);
  79508. effect.setFloat("exposure", _this.exposure);
  79509. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  79510. };
  79511. // Add to pipeline
  79512. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  79513. };
  79514. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  79515. var _this = this;
  79516. var geometryRenderer = scene.enableGeometryBufferRenderer();
  79517. geometryRenderer.enablePosition = true;
  79518. var geometry = geometryRenderer.getGBuffer();
  79519. // Base post-process
  79520. 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));
  79521. var depthValues = BABYLON.Vector2.Zero();
  79522. this.volumetricLightPostProcess.onApply = function (effect) {
  79523. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  79524. var generator = _this.sourceLight.getShadowGenerator();
  79525. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  79526. effect.setTexture("positionSampler", geometry.textures[2]);
  79527. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  79528. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  79529. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  79530. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  79531. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  79532. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  79533. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  79534. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  79535. effect.setVector2("depthValues", depthValues);
  79536. }
  79537. };
  79538. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  79539. // Smooth
  79540. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  79541. // Merge
  79542. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  79543. this.volumetricLightMergePostProces.onApply = function (effect) {
  79544. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  79545. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  79546. };
  79547. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  79548. };
  79549. // Create luminance
  79550. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  79551. var _this = this;
  79552. // Create luminance
  79553. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  79554. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  79555. var offsets = [];
  79556. this.luminancePostProcess.onApply = function (effect) {
  79557. var sU = (1.0 / _this.luminancePostProcess.width);
  79558. var sV = (1.0 / _this.luminancePostProcess.height);
  79559. offsets[0] = -0.5 * sU;
  79560. offsets[1] = 0.5 * sV;
  79561. offsets[2] = 0.5 * sU;
  79562. offsets[3] = 0.5 * sV;
  79563. offsets[4] = -0.5 * sU;
  79564. offsets[5] = -0.5 * sV;
  79565. offsets[6] = 0.5 * sU;
  79566. offsets[7] = -0.5 * sV;
  79567. effect.setArray2("lumOffsets", offsets);
  79568. };
  79569. // Add to pipeline
  79570. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  79571. // Create down sample luminance
  79572. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  79573. var size = Math.pow(3, i);
  79574. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  79575. if (i === 0) {
  79576. defines += "#define FINAL_DOWN_SAMPLER";
  79577. }
  79578. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  79579. this.luminanceDownSamplePostProcesses.push(postProcess);
  79580. }
  79581. // Create callbacks and add effects
  79582. var lastLuminance = this.luminancePostProcess;
  79583. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  79584. var downSampleOffsets = new Array(18);
  79585. pp.onApply = function (effect) {
  79586. if (!lastLuminance) {
  79587. return;
  79588. }
  79589. var id = 0;
  79590. for (var x = -1; x < 2; x++) {
  79591. for (var y = -1; y < 2; y++) {
  79592. downSampleOffsets[id] = x / lastLuminance.width;
  79593. downSampleOffsets[id + 1] = y / lastLuminance.height;
  79594. id += 2;
  79595. }
  79596. }
  79597. effect.setArray2("dsOffsets", downSampleOffsets);
  79598. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  79599. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79600. lastLuminance = _this.luminancePostProcess;
  79601. }
  79602. else {
  79603. lastLuminance = pp;
  79604. }
  79605. };
  79606. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79607. pp.onAfterRender = function (effect) {
  79608. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  79609. 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);
  79610. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  79611. };
  79612. }
  79613. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  79614. });
  79615. };
  79616. // Create HDR post-process
  79617. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  79618. var _this = this;
  79619. 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);
  79620. var outputLiminance = 1;
  79621. var time = 0;
  79622. var lastTime = 0;
  79623. this.hdrPostProcess.onApply = function (effect) {
  79624. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  79625. time += scene.getEngine().getDeltaTime();
  79626. if (outputLiminance < 0) {
  79627. outputLiminance = _this._hdrCurrentLuminance;
  79628. }
  79629. else {
  79630. var dt = (lastTime - time) / 1000.0;
  79631. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  79632. outputLiminance += _this.hdrDecreaseRate * dt;
  79633. }
  79634. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  79635. outputLiminance -= _this.hdrIncreaseRate * dt;
  79636. }
  79637. else {
  79638. outputLiminance = _this._hdrCurrentLuminance;
  79639. }
  79640. }
  79641. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  79642. effect.setFloat("averageLuminance", outputLiminance);
  79643. lastTime = time;
  79644. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  79645. };
  79646. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  79647. };
  79648. // Create lens flare post-process
  79649. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  79650. var _this = this;
  79651. 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);
  79652. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  79653. this._createBlurPostProcesses(scene, ratio / 4, 2);
  79654. 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);
  79655. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  79656. var resolution = new BABYLON.Vector2(0, 0);
  79657. // Lens flare
  79658. this.lensFlarePostProcess.onApply = function (effect) {
  79659. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  79660. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  79661. effect.setFloat("strength", _this.lensFlareStrength);
  79662. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  79663. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  79664. // Shift
  79665. resolution.x = _this.lensFlarePostProcess.width;
  79666. resolution.y = _this.lensFlarePostProcess.height;
  79667. effect.setVector2("resolution", resolution);
  79668. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  79669. };
  79670. // Compose
  79671. 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);
  79672. 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);
  79673. this.lensFlareComposePostProcess.onApply = function (effect) {
  79674. if (!_this._scene.activeCamera) {
  79675. return;
  79676. }
  79677. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79678. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  79679. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  79680. // Lens start rotation matrix
  79681. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  79682. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  79683. 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));
  79684. camRot *= 4.0;
  79685. 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);
  79686. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  79687. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  79688. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  79689. };
  79690. };
  79691. // Create depth-of-field post-process
  79692. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  79693. var _this = this;
  79694. 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);
  79695. this.depthOfFieldPostProcess.onApply = function (effect) {
  79696. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79697. effect.setTexture("depthSampler", _this._getDepthTexture());
  79698. effect.setFloat("distance", _this.depthOfFieldDistance);
  79699. };
  79700. // Add to pipeline
  79701. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  79702. };
  79703. // Create motion blur post-process
  79704. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  79705. var _this = this;
  79706. 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);
  79707. var motionScale = 0;
  79708. var prevViewProjection = BABYLON.Matrix.Identity();
  79709. var invViewProjection = BABYLON.Matrix.Identity();
  79710. var viewProjection = BABYLON.Matrix.Identity();
  79711. var screenSize = BABYLON.Vector2.Zero();
  79712. this.motionBlurPostProcess.onApply = function (effect) {
  79713. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  79714. viewProjection.invertToRef(invViewProjection);
  79715. effect.setMatrix("inverseViewProjection", invViewProjection);
  79716. effect.setMatrix("prevViewProjection", prevViewProjection);
  79717. prevViewProjection = viewProjection;
  79718. screenSize.x = _this.motionBlurPostProcess.width;
  79719. screenSize.y = _this.motionBlurPostProcess.height;
  79720. effect.setVector2("screenSize", screenSize);
  79721. motionScale = scene.getEngine().getFps() / 60.0;
  79722. effect.setFloat("motionScale", motionScale);
  79723. effect.setFloat("motionStrength", _this.motionStrength);
  79724. effect.setTexture("depthSampler", _this._getDepthTexture());
  79725. };
  79726. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  79727. };
  79728. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  79729. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  79730. var renderer = this._scene.enableGeometryBufferRenderer();
  79731. return renderer.getGBuffer().textures[0];
  79732. }
  79733. return this._scene.enableDepthRenderer().getDepthMap();
  79734. };
  79735. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  79736. for (var i = 0; i < this._cameras.length; i++) {
  79737. var camera = this._cameras[i];
  79738. if (this.originalPostProcess) {
  79739. this.originalPostProcess.dispose(camera);
  79740. }
  79741. if (this.downSampleX4PostProcess) {
  79742. this.downSampleX4PostProcess.dispose(camera);
  79743. }
  79744. if (this.brightPassPostProcess) {
  79745. this.brightPassPostProcess.dispose(camera);
  79746. }
  79747. if (this.textureAdderPostProcess) {
  79748. this.textureAdderPostProcess.dispose(camera);
  79749. }
  79750. if (this.textureAdderFinalPostProcess) {
  79751. this.textureAdderFinalPostProcess.dispose(camera);
  79752. }
  79753. if (this.volumetricLightPostProcess) {
  79754. this.volumetricLightPostProcess.dispose(camera);
  79755. }
  79756. if (this.volumetricLightSmoothXPostProcess) {
  79757. this.volumetricLightSmoothXPostProcess.dispose(camera);
  79758. }
  79759. if (this.volumetricLightSmoothYPostProcess) {
  79760. this.volumetricLightSmoothYPostProcess.dispose(camera);
  79761. }
  79762. if (this.volumetricLightMergePostProces) {
  79763. this.volumetricLightMergePostProces.dispose(camera);
  79764. }
  79765. if (this.volumetricLightFinalPostProcess) {
  79766. this.volumetricLightFinalPostProcess.dispose(camera);
  79767. }
  79768. if (this.lensFlarePostProcess) {
  79769. this.lensFlarePostProcess.dispose(camera);
  79770. }
  79771. if (this.lensFlareComposePostProcess) {
  79772. this.lensFlareComposePostProcess.dispose(camera);
  79773. }
  79774. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  79775. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  79776. }
  79777. if (this.luminancePostProcess) {
  79778. this.luminancePostProcess.dispose(camera);
  79779. }
  79780. if (this.hdrPostProcess) {
  79781. this.hdrPostProcess.dispose(camera);
  79782. }
  79783. if (this.hdrFinalPostProcess) {
  79784. this.hdrFinalPostProcess.dispose(camera);
  79785. }
  79786. if (this.depthOfFieldPostProcess) {
  79787. this.depthOfFieldPostProcess.dispose(camera);
  79788. }
  79789. if (this.motionBlurPostProcess) {
  79790. this.motionBlurPostProcess.dispose(camera);
  79791. }
  79792. if (this.fxaaPostProcess) {
  79793. this.fxaaPostProcess.dispose(camera);
  79794. }
  79795. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  79796. this.blurHPostProcesses[j].dispose(camera);
  79797. }
  79798. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  79799. this.blurVPostProcesses[j].dispose(camera);
  79800. }
  79801. }
  79802. this.originalPostProcess = null;
  79803. this.downSampleX4PostProcess = null;
  79804. this.brightPassPostProcess = null;
  79805. this.textureAdderPostProcess = null;
  79806. this.textureAdderFinalPostProcess = null;
  79807. this.volumetricLightPostProcess = null;
  79808. this.volumetricLightSmoothXPostProcess = null;
  79809. this.volumetricLightSmoothYPostProcess = null;
  79810. this.volumetricLightMergePostProces = null;
  79811. this.volumetricLightFinalPostProcess = null;
  79812. this.lensFlarePostProcess = null;
  79813. this.lensFlareComposePostProcess = null;
  79814. this.luminancePostProcess = null;
  79815. this.hdrPostProcess = null;
  79816. this.hdrFinalPostProcess = null;
  79817. this.depthOfFieldPostProcess = null;
  79818. this.motionBlurPostProcess = null;
  79819. this.fxaaPostProcess = null;
  79820. this.luminanceDownSamplePostProcesses = [];
  79821. this.blurHPostProcesses = [];
  79822. this.blurVPostProcesses = [];
  79823. };
  79824. /**
  79825. * Dispose of the pipeline and stop all post processes
  79826. */
  79827. StandardRenderingPipeline.prototype.dispose = function () {
  79828. this._disposePostProcesses();
  79829. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79830. _super.prototype.dispose.call(this);
  79831. };
  79832. /**
  79833. * Serialize the rendering pipeline (Used when exporting)
  79834. * @returns the serialized object
  79835. */
  79836. StandardRenderingPipeline.prototype.serialize = function () {
  79837. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79838. if (this.sourceLight) {
  79839. serializationObject.sourceLightId = this.sourceLight.id;
  79840. }
  79841. serializationObject.customType = "StandardRenderingPipeline";
  79842. return serializationObject;
  79843. };
  79844. /**
  79845. * Parse the serialized pipeline
  79846. * @param source Source pipeline.
  79847. * @param scene The scene to load the pipeline to.
  79848. * @param rootUrl The URL of the serialized pipeline.
  79849. * @returns An instantiated pipeline from the serialized object.
  79850. */
  79851. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  79852. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79853. if (source.sourceLightId) {
  79854. p.sourceLight = scene.getLightByID(source.sourceLightId);
  79855. }
  79856. return p;
  79857. };
  79858. // Luminance steps
  79859. StandardRenderingPipeline.LuminanceSteps = 6;
  79860. __decorate([
  79861. BABYLON.serialize()
  79862. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  79863. __decorate([
  79864. BABYLON.serialize()
  79865. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  79866. __decorate([
  79867. BABYLON.serialize()
  79868. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  79869. __decorate([
  79870. BABYLON.serialize()
  79871. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  79872. __decorate([
  79873. BABYLON.serializeAsTexture("lensTexture")
  79874. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  79875. __decorate([
  79876. BABYLON.serialize()
  79877. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  79878. __decorate([
  79879. BABYLON.serialize()
  79880. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  79881. __decorate([
  79882. BABYLON.serialize()
  79883. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  79884. __decorate([
  79885. BABYLON.serialize()
  79886. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  79887. __decorate([
  79888. BABYLON.serialize()
  79889. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  79890. __decorate([
  79891. BABYLON.serialize()
  79892. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  79893. __decorate([
  79894. BABYLON.serializeAsTexture("lensColorTexture")
  79895. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  79896. __decorate([
  79897. BABYLON.serialize()
  79898. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  79899. __decorate([
  79900. BABYLON.serialize()
  79901. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  79902. __decorate([
  79903. BABYLON.serialize()
  79904. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  79905. __decorate([
  79906. BABYLON.serialize()
  79907. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  79908. __decorate([
  79909. BABYLON.serializeAsTexture("lensStarTexture")
  79910. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  79911. __decorate([
  79912. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  79913. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  79914. __decorate([
  79915. BABYLON.serialize()
  79916. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  79917. __decorate([
  79918. BABYLON.serialize()
  79919. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  79920. __decorate([
  79921. BABYLON.serialize()
  79922. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  79923. __decorate([
  79924. BABYLON.serialize()
  79925. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  79926. __decorate([
  79927. BABYLON.serialize()
  79928. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  79929. __decorate([
  79930. BABYLON.serialize()
  79931. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  79932. __decorate([
  79933. BABYLON.serialize()
  79934. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  79935. __decorate([
  79936. BABYLON.serialize()
  79937. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  79938. __decorate([
  79939. BABYLON.serialize()
  79940. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  79941. __decorate([
  79942. BABYLON.serialize()
  79943. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  79944. __decorate([
  79945. BABYLON.serialize()
  79946. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  79947. __decorate([
  79948. BABYLON.serialize()
  79949. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  79950. __decorate([
  79951. BABYLON.serialize()
  79952. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  79953. __decorate([
  79954. BABYLON.serialize()
  79955. ], StandardRenderingPipeline.prototype, "samples", null);
  79956. return StandardRenderingPipeline;
  79957. }(BABYLON.PostProcessRenderPipeline));
  79958. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  79959. })(BABYLON || (BABYLON = {}));
  79960. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  79961. var BABYLON;
  79962. (function (BABYLON) {
  79963. var FxaaPostProcess = /** @class */ (function (_super) {
  79964. __extends(FxaaPostProcess, _super);
  79965. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79966. if (camera === void 0) { camera = null; }
  79967. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79968. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  79969. var defines = _this._getDefines();
  79970. _this.updateEffect(defines);
  79971. _this.onApplyObservable.add(function (effect) {
  79972. var texelSize = _this.texelSize;
  79973. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  79974. });
  79975. return _this;
  79976. }
  79977. FxaaPostProcess.prototype._getDefines = function () {
  79978. var engine = this.getEngine();
  79979. if (!engine) {
  79980. return null;
  79981. }
  79982. var glInfo = engine.getGlInfo();
  79983. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  79984. return "#define MALI 1\n";
  79985. }
  79986. return null;
  79987. };
  79988. return FxaaPostProcess;
  79989. }(BABYLON.PostProcess));
  79990. BABYLON.FxaaPostProcess = FxaaPostProcess;
  79991. })(BABYLON || (BABYLON = {}));
  79992. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  79993. var BABYLON;
  79994. (function (BABYLON) {
  79995. /**
  79996. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  79997. */
  79998. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  79999. __extends(ChromaticAberrationPostProcess, _super);
  80000. /**
  80001. * Creates a new instance ChromaticAberrationPostProcess
  80002. * @param name The name of the effect.
  80003. * @param screenWidth The width of the screen to apply the effect on.
  80004. * @param screenHeight The height of the screen to apply the effect on.
  80005. * @param options The required width/height ratio to downsize to before computing the render pass.
  80006. * @param camera The camera to apply the render pass to.
  80007. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80008. * @param engine The engine which the post process will be applied. (default: current engine)
  80009. * @param reusable If the post process can be reused on the same frame. (default: false)
  80010. * @param textureType Type of textures used when performing the post process. (default: 0)
  80011. * @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)
  80012. */
  80013. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80014. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80015. if (blockCompilation === void 0) { blockCompilation = false; }
  80016. 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;
  80017. /**
  80018. * The amount of seperation of rgb channels (default: 30)
  80019. */
  80020. _this.aberrationAmount = 30;
  80021. /**
  80022. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  80023. */
  80024. _this.radialIntensity = 0;
  80025. /**
  80026. * 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))
  80027. */
  80028. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  80029. /**
  80030. * 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))
  80031. */
  80032. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  80033. _this.onApplyObservable.add(function (effect) {
  80034. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  80035. effect.setFloat('screen_width', screenWidth);
  80036. effect.setFloat('screen_height', screenHeight);
  80037. effect.setFloat('radialIntensity', _this.radialIntensity);
  80038. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  80039. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  80040. });
  80041. return _this;
  80042. }
  80043. return ChromaticAberrationPostProcess;
  80044. }(BABYLON.PostProcess));
  80045. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  80046. })(BABYLON || (BABYLON = {}));
  80047. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  80048. var BABYLON;
  80049. (function (BABYLON) {
  80050. /**
  80051. * The GrainPostProcess adds noise to the image at mid luminance levels
  80052. */
  80053. var GrainPostProcess = /** @class */ (function (_super) {
  80054. __extends(GrainPostProcess, _super);
  80055. /**
  80056. * Creates a new instance of @see GrainPostProcess
  80057. * @param name The name of the effect.
  80058. * @param options The required width/height ratio to downsize to before computing the render pass.
  80059. * @param camera The camera to apply the render pass to.
  80060. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80061. * @param engine The engine which the post process will be applied. (default: current engine)
  80062. * @param reusable If the post process can be reused on the same frame. (default: false)
  80063. * @param textureType Type of textures used when performing the post process. (default: 0)
  80064. * @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)
  80065. */
  80066. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80067. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80068. if (blockCompilation === void 0) { blockCompilation = false; }
  80069. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80070. /**
  80071. * The intensity of the grain added (default: 30)
  80072. */
  80073. _this.intensity = 30;
  80074. /**
  80075. * If the grain should be randomized on every frame
  80076. */
  80077. _this.animated = false;
  80078. _this.onApplyObservable.add(function (effect) {
  80079. effect.setFloat('intensity', _this.intensity);
  80080. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  80081. });
  80082. return _this;
  80083. }
  80084. return GrainPostProcess;
  80085. }(BABYLON.PostProcess));
  80086. BABYLON.GrainPostProcess = GrainPostProcess;
  80087. })(BABYLON || (BABYLON = {}));
  80088. //# sourceMappingURL=babylon.grainPostProcess.js.map
  80089. var BABYLON;
  80090. (function (BABYLON) {
  80091. /**
  80092. * The SharpenPostProcess applies a sharpen kernel to every pixel
  80093. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80094. */
  80095. var SharpenPostProcess = /** @class */ (function (_super) {
  80096. __extends(SharpenPostProcess, _super);
  80097. /**
  80098. * Creates a new instance ConvolutionPostProcess
  80099. * @param name The name of the effect.
  80100. * @param options The required width/height ratio to downsize to before computing the render pass.
  80101. * @param camera The camera to apply the render pass to.
  80102. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80103. * @param engine The engine which the post process will be applied. (default: current engine)
  80104. * @param reusable If the post process can be reused on the same frame. (default: false)
  80105. * @param textureType Type of textures used when performing the post process. (default: 0)
  80106. * @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)
  80107. */
  80108. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80109. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80110. if (blockCompilation === void 0) { blockCompilation = false; }
  80111. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80112. /**
  80113. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  80114. */
  80115. _this.colorAmount = 1.0;
  80116. /**
  80117. * How much sharpness should be applied (default: 0.3)
  80118. */
  80119. _this.edgeAmount = 0.3;
  80120. _this.onApply = function (effect) {
  80121. effect.setFloat2("screenSize", _this.width, _this.height);
  80122. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  80123. };
  80124. return _this;
  80125. }
  80126. return SharpenPostProcess;
  80127. }(BABYLON.PostProcess));
  80128. BABYLON.SharpenPostProcess = SharpenPostProcess;
  80129. })(BABYLON || (BABYLON = {}));
  80130. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  80131. var BABYLON;
  80132. (function (BABYLON) {
  80133. /**
  80134. * The Blur Post Process which blurs an image based on a kernel and direction.
  80135. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  80136. */
  80137. var BlurPostProcess = /** @class */ (function (_super) {
  80138. __extends(BlurPostProcess, _super);
  80139. /**
  80140. * Creates a new instance BlurPostProcess
  80141. * @param name The name of the effect.
  80142. * @param direction The direction in which to blur the image.
  80143. * @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.
  80144. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  80145. * @param camera The camera to apply the render pass to.
  80146. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80147. * @param engine The engine which the post process will be applied. (default: current engine)
  80148. * @param reusable If the post process can be reused on the same frame. (default: false)
  80149. * @param textureType Type of textures used when performing the post process. (default: 0)
  80150. * @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)
  80151. */
  80152. function BlurPostProcess(name,
  80153. /** The direction in which to blur the image. */
  80154. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  80155. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80156. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80157. if (defines === void 0) { defines = ""; }
  80158. if (blockCompilation === void 0) { blockCompilation = false; }
  80159. 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;
  80160. _this.direction = direction;
  80161. _this.blockCompilation = blockCompilation;
  80162. _this._packedFloat = false;
  80163. _this._staticDefines = "";
  80164. _this._staticDefines = defines;
  80165. _this.onApplyObservable.add(function (effect) {
  80166. if (_this._outputTexture) {
  80167. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  80168. }
  80169. else {
  80170. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  80171. }
  80172. });
  80173. _this.kernel = kernel;
  80174. return _this;
  80175. }
  80176. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  80177. /**
  80178. * Gets the length in pixels of the blur sample region
  80179. */
  80180. get: function () {
  80181. return this._idealKernel;
  80182. },
  80183. /**
  80184. * Sets the length in pixels of the blur sample region
  80185. */
  80186. set: function (v) {
  80187. if (this._idealKernel === v) {
  80188. return;
  80189. }
  80190. v = Math.max(v, 1);
  80191. this._idealKernel = v;
  80192. this._kernel = this._nearestBestKernel(v);
  80193. if (!this.blockCompilation) {
  80194. this._updateParameters();
  80195. }
  80196. },
  80197. enumerable: true,
  80198. configurable: true
  80199. });
  80200. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  80201. /**
  80202. * Gets wether or not the blur is unpacking/repacking floats
  80203. */
  80204. get: function () {
  80205. return this._packedFloat;
  80206. },
  80207. /**
  80208. * Sets wether or not the blur needs to unpack/repack floats
  80209. */
  80210. set: function (v) {
  80211. if (this._packedFloat === v) {
  80212. return;
  80213. }
  80214. this._packedFloat = v;
  80215. if (!this.blockCompilation) {
  80216. this._updateParameters();
  80217. }
  80218. },
  80219. enumerable: true,
  80220. configurable: true
  80221. });
  80222. /**
  80223. * Updates the effect with the current post process compile time values and recompiles the shader.
  80224. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80225. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80226. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80227. * @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
  80228. * @param onCompiled Called when the shader has been compiled.
  80229. * @param onError Called if there is an error when compiling a shader.
  80230. */
  80231. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80232. if (defines === void 0) { defines = null; }
  80233. if (uniforms === void 0) { uniforms = null; }
  80234. if (samplers === void 0) { samplers = null; }
  80235. this._updateParameters(onCompiled, onError);
  80236. };
  80237. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  80238. // Generate sampling offsets and weights
  80239. var N = this._kernel;
  80240. var centerIndex = (N - 1) / 2;
  80241. // Generate Gaussian sampling weights over kernel
  80242. var offsets = [];
  80243. var weights = [];
  80244. var totalWeight = 0;
  80245. for (var i = 0; i < N; i++) {
  80246. var u = i / (N - 1);
  80247. var w = this._gaussianWeight(u * 2.0 - 1);
  80248. offsets[i] = (i - centerIndex);
  80249. weights[i] = w;
  80250. totalWeight += w;
  80251. }
  80252. // Normalize weights
  80253. for (var i = 0; i < weights.length; i++) {
  80254. weights[i] /= totalWeight;
  80255. }
  80256. // Optimize: combine samples to take advantage of hardware linear sampling
  80257. // Walk from left to center, combining pairs (symmetrically)
  80258. var linearSamplingWeights = [];
  80259. var linearSamplingOffsets = [];
  80260. var linearSamplingMap = [];
  80261. for (var i = 0; i <= centerIndex; i += 2) {
  80262. var j = Math.min(i + 1, Math.floor(centerIndex));
  80263. var singleCenterSample = i === j;
  80264. if (singleCenterSample) {
  80265. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80266. }
  80267. else {
  80268. var sharedCell = j === centerIndex;
  80269. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  80270. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  80271. if (offsetLinear === 0) {
  80272. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80273. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  80274. }
  80275. else {
  80276. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  80277. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  80278. }
  80279. }
  80280. }
  80281. for (var i = 0; i < linearSamplingMap.length; i++) {
  80282. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  80283. linearSamplingWeights[i] = linearSamplingMap[i].w;
  80284. }
  80285. // Replace with optimized
  80286. offsets = linearSamplingOffsets;
  80287. weights = linearSamplingWeights;
  80288. // Generate shaders
  80289. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  80290. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  80291. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  80292. var defines = "";
  80293. defines += this._staticDefines;
  80294. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  80295. if (this._staticDefines.indexOf("DOF") != -1) {
  80296. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  80297. varyingCount--;
  80298. }
  80299. for (var i = 0; i < varyingCount; i++) {
  80300. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  80301. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  80302. }
  80303. var depCount = 0;
  80304. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  80305. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  80306. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  80307. depCount++;
  80308. }
  80309. if (this.packedFloat) {
  80310. defines += "#define PACKEDFLOAT 1";
  80311. }
  80312. this.blockCompilation = false;
  80313. _super.prototype.updateEffect.call(this, defines, null, null, {
  80314. varyingCount: varyingCount,
  80315. depCount: depCount
  80316. }, onCompiled, onError);
  80317. };
  80318. /**
  80319. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  80320. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  80321. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  80322. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  80323. * The gaps between physical kernels are compensated for in the weighting of the samples
  80324. * @param idealKernel Ideal blur kernel.
  80325. * @return Nearest best kernel.
  80326. */
  80327. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  80328. var v = Math.round(idealKernel);
  80329. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  80330. var k = _a[_i];
  80331. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  80332. return Math.max(k, 3);
  80333. }
  80334. }
  80335. return Math.max(v, 3);
  80336. };
  80337. /**
  80338. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  80339. * @param x The point on the Gaussian distribution to sample.
  80340. * @return the value of the Gaussian function at x.
  80341. */
  80342. BlurPostProcess.prototype._gaussianWeight = function (x) {
  80343. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  80344. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  80345. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  80346. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  80347. // truncated at around 1.3% of peak strength.
  80348. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  80349. var sigma = (1 / 3);
  80350. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  80351. var exponent = -((x * x) / (2.0 * sigma * sigma));
  80352. var weight = (1.0 / denominator) * Math.exp(exponent);
  80353. return weight;
  80354. };
  80355. /**
  80356. * Generates a string that can be used as a floating point number in GLSL.
  80357. * @param x Value to print.
  80358. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  80359. * @return GLSL float string.
  80360. */
  80361. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  80362. if (decimalFigures === void 0) { decimalFigures = 8; }
  80363. return x.toFixed(decimalFigures).replace(/0+$/, '');
  80364. };
  80365. return BlurPostProcess;
  80366. }(BABYLON.PostProcess));
  80367. BABYLON.BlurPostProcess = BlurPostProcess;
  80368. })(BABYLON || (BABYLON = {}));
  80369. //# sourceMappingURL=babylon.blurPostProcess.js.map
  80370. var BABYLON;
  80371. (function (BABYLON) {
  80372. /**
  80373. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  80374. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  80375. * based on samples that have a large difference in distance than the center pixel.
  80376. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80377. */
  80378. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  80379. __extends(DepthOfFieldBlurPostProcess, _super);
  80380. /**
  80381. * Creates a new instance CircleOfConfusionPostProcess
  80382. * @param name The name of the effect.
  80383. * @param scene The scene the effect belongs to.
  80384. * @param direction The direction the blur should be applied.
  80385. * @param kernel The size of the kernel used to blur.
  80386. * @param options The required width/height ratio to downsize to before computing the render pass.
  80387. * @param camera The camera to apply the render pass to.
  80388. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  80389. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  80390. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80391. * @param engine The engine which the post process will be applied. (default: current engine)
  80392. * @param reusable If the post process can be reused on the same frame. (default: false)
  80393. * @param textureType Type of textures used when performing the post process. (default: 0)
  80394. * @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)
  80395. */
  80396. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  80397. if (imageToBlur === void 0) { imageToBlur = null; }
  80398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80399. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80400. if (blockCompilation === void 0) { blockCompilation = false; }
  80401. 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;
  80402. _this.direction = direction;
  80403. _this.onApplyObservable.add(function (effect) {
  80404. if (imageToBlur != null) {
  80405. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  80406. }
  80407. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80408. if (scene.activeCamera) {
  80409. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80410. }
  80411. });
  80412. return _this;
  80413. }
  80414. return DepthOfFieldBlurPostProcess;
  80415. }(BABYLON.BlurPostProcess));
  80416. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  80417. })(BABYLON || (BABYLON = {}));
  80418. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  80419. var BABYLON;
  80420. (function (BABYLON) {
  80421. /**
  80422. * Options to be set when merging outputs from the default pipeline.
  80423. */
  80424. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  80425. function DepthOfFieldMergePostProcessOptions() {
  80426. }
  80427. return DepthOfFieldMergePostProcessOptions;
  80428. }());
  80429. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  80430. /**
  80431. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80432. */
  80433. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  80434. __extends(DepthOfFieldMergePostProcess, _super);
  80435. /**
  80436. * Creates a new instance of DepthOfFieldMergePostProcess
  80437. * @param name The name of the effect.
  80438. * @param originalFromInput Post process which's input will be used for the merge.
  80439. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  80440. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  80441. * @param options The required width/height ratio to downsize to before computing the render pass.
  80442. * @param camera The camera to apply the render pass to.
  80443. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80444. * @param engine The engine which the post process will be applied. (default: current engine)
  80445. * @param reusable If the post process can be reused on the same frame. (default: false)
  80446. * @param textureType Type of textures used when performing the post process. (default: 0)
  80447. * @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)
  80448. */
  80449. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80450. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80451. if (blockCompilation === void 0) { blockCompilation = false; }
  80452. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80453. _this.blurSteps = blurSteps;
  80454. _this.onApplyObservable.add(function (effect) {
  80455. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80456. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80457. blurSteps.forEach(function (step, index) {
  80458. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  80459. });
  80460. });
  80461. if (!blockCompilation) {
  80462. _this.updateEffect();
  80463. }
  80464. return _this;
  80465. }
  80466. /**
  80467. * Updates the effect with the current post process compile time values and recompiles the shader.
  80468. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80469. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80470. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80471. * @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
  80472. * @param onCompiled Called when the shader has been compiled.
  80473. * @param onError Called if there is an error when compiling a shader.
  80474. */
  80475. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80476. if (defines === void 0) { defines = null; }
  80477. if (uniforms === void 0) { uniforms = null; }
  80478. if (samplers === void 0) { samplers = null; }
  80479. if (!defines) {
  80480. defines = "";
  80481. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  80482. }
  80483. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  80484. };
  80485. return DepthOfFieldMergePostProcess;
  80486. }(BABYLON.PostProcess));
  80487. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  80488. })(BABYLON || (BABYLON = {}));
  80489. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  80490. var BABYLON;
  80491. (function (BABYLON) {
  80492. /**
  80493. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  80494. */
  80495. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  80496. __extends(CircleOfConfusionPostProcess, _super);
  80497. /**
  80498. * Creates a new instance CircleOfConfusionPostProcess
  80499. * @param name The name of the effect.
  80500. * @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.
  80501. * @param options The required width/height ratio to downsize to before computing the render pass.
  80502. * @param camera The camera to apply the render pass to.
  80503. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80504. * @param engine The engine which the post process will be applied. (default: current engine)
  80505. * @param reusable If the post process can be reused on the same frame. (default: false)
  80506. * @param textureType Type of textures used when performing the post process. (default: 0)
  80507. * @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)
  80508. */
  80509. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80510. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80511. if (blockCompilation === void 0) { blockCompilation = false; }
  80512. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80513. /**
  80514. * 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.
  80515. */
  80516. _this.lensSize = 50;
  80517. /**
  80518. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80519. */
  80520. _this.fStop = 1.4;
  80521. /**
  80522. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80523. */
  80524. _this.focusDistance = 2000;
  80525. /**
  80526. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  80527. */
  80528. _this.focalLength = 50;
  80529. _this._depthTexture = null;
  80530. _this._depthTexture = depthTexture;
  80531. _this.onApplyObservable.add(function (effect) {
  80532. if (!_this._depthTexture) {
  80533. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  80534. return;
  80535. }
  80536. effect.setTexture("depthSampler", _this._depthTexture);
  80537. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  80538. var aperture = _this.lensSize / _this.fStop;
  80539. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  80540. effect.setFloat('focusDistance', _this.focusDistance);
  80541. effect.setFloat('cocPrecalculation', cocPrecalculation);
  80542. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  80543. });
  80544. return _this;
  80545. }
  80546. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  80547. /**
  80548. * 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.
  80549. */
  80550. set: function (value) {
  80551. this._depthTexture = value;
  80552. },
  80553. enumerable: true,
  80554. configurable: true
  80555. });
  80556. return CircleOfConfusionPostProcess;
  80557. }(BABYLON.PostProcess));
  80558. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  80559. })(BABYLON || (BABYLON = {}));
  80560. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  80561. var BABYLON;
  80562. (function (BABYLON) {
  80563. /**
  80564. * Specifies the level of max blur that should be applied when using the depth of field effect
  80565. */
  80566. var DepthOfFieldEffectBlurLevel;
  80567. (function (DepthOfFieldEffectBlurLevel) {
  80568. /**
  80569. * Subtle blur
  80570. */
  80571. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  80572. /**
  80573. * Medium blur
  80574. */
  80575. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  80576. /**
  80577. * Large blur
  80578. */
  80579. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  80580. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  80581. ;
  80582. /**
  80583. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  80584. */
  80585. var DepthOfFieldEffect = /** @class */ (function (_super) {
  80586. __extends(DepthOfFieldEffect, _super);
  80587. /**
  80588. * Creates a new instance DepthOfFieldEffect
  80589. * @param scene The scene the effect belongs to.
  80590. * @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.
  80591. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80592. * @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)
  80593. */
  80594. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  80595. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  80596. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80597. if (blockCompilation === void 0) { blockCompilation = false; }
  80598. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  80599. return _this._effects;
  80600. }, true) || this;
  80601. /**
  80602. * @hidden Internal post processes in depth of field effect
  80603. */
  80604. _this._effects = [];
  80605. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  80606. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80607. // 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)
  80608. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  80609. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80610. _this._depthOfFieldBlurY = [];
  80611. _this._depthOfFieldBlurX = [];
  80612. var blurCount = 1;
  80613. var kernelSize = 15;
  80614. switch (blurLevel) {
  80615. case DepthOfFieldEffectBlurLevel.High: {
  80616. blurCount = 3;
  80617. kernelSize = 51;
  80618. break;
  80619. }
  80620. case DepthOfFieldEffectBlurLevel.Medium: {
  80621. blurCount = 2;
  80622. kernelSize = 31;
  80623. break;
  80624. }
  80625. default: {
  80626. kernelSize = 15;
  80627. blurCount = 1;
  80628. break;
  80629. }
  80630. }
  80631. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  80632. var ratio = 1.0;
  80633. for (var i = 0; i < blurCount; i++) {
  80634. 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);
  80635. blurY.autoClear = false;
  80636. ratio = 0.75 / Math.pow(2, i);
  80637. 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);
  80638. blurX.autoClear = false;
  80639. _this._depthOfFieldBlurY.push(blurY);
  80640. _this._depthOfFieldBlurX.push(blurX);
  80641. }
  80642. // Set all post processes on the effect.
  80643. _this._effects = [_this._circleOfConfusion];
  80644. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  80645. _this._effects.push(_this._depthOfFieldBlurY[i]);
  80646. _this._effects.push(_this._depthOfFieldBlurX[i]);
  80647. }
  80648. // Merge blurred images with original image based on circleOfConfusion
  80649. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80650. _this._dofMerge.autoClear = false;
  80651. _this._effects.push(_this._dofMerge);
  80652. return _this;
  80653. }
  80654. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  80655. get: function () {
  80656. return this._circleOfConfusion.focalLength;
  80657. },
  80658. /**
  80659. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  80660. */
  80661. set: function (value) {
  80662. this._circleOfConfusion.focalLength = value;
  80663. },
  80664. enumerable: true,
  80665. configurable: true
  80666. });
  80667. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  80668. get: function () {
  80669. return this._circleOfConfusion.fStop;
  80670. },
  80671. /**
  80672. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80673. */
  80674. set: function (value) {
  80675. this._circleOfConfusion.fStop = value;
  80676. },
  80677. enumerable: true,
  80678. configurable: true
  80679. });
  80680. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  80681. get: function () {
  80682. return this._circleOfConfusion.focusDistance;
  80683. },
  80684. /**
  80685. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80686. */
  80687. set: function (value) {
  80688. this._circleOfConfusion.focusDistance = value;
  80689. },
  80690. enumerable: true,
  80691. configurable: true
  80692. });
  80693. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  80694. get: function () {
  80695. return this._circleOfConfusion.lensSize;
  80696. },
  80697. /**
  80698. * 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.
  80699. */
  80700. set: function (value) {
  80701. this._circleOfConfusion.lensSize = value;
  80702. },
  80703. enumerable: true,
  80704. configurable: true
  80705. });
  80706. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  80707. /**
  80708. * 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.
  80709. */
  80710. set: function (value) {
  80711. this._circleOfConfusion.depthTexture = value;
  80712. },
  80713. enumerable: true,
  80714. configurable: true
  80715. });
  80716. /**
  80717. * Disposes each of the internal effects for a given camera.
  80718. * @param camera The camera to dispose the effect on.
  80719. */
  80720. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  80721. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80722. this._effects[effectIndex].dispose(camera);
  80723. }
  80724. };
  80725. /**
  80726. * @hidden Internal
  80727. */
  80728. DepthOfFieldEffect.prototype._updateEffects = function () {
  80729. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80730. this._effects[effectIndex].updateEffect();
  80731. }
  80732. };
  80733. /**
  80734. * Internal
  80735. * @returns if all the contained post processes are ready.
  80736. * @hidden
  80737. */
  80738. DepthOfFieldEffect.prototype._isReady = function () {
  80739. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80740. if (!this._effects[effectIndex].isReady()) {
  80741. return false;
  80742. }
  80743. }
  80744. return true;
  80745. };
  80746. return DepthOfFieldEffect;
  80747. }(BABYLON.PostProcessRenderEffect));
  80748. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  80749. })(BABYLON || (BABYLON = {}));
  80750. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  80751. var BABYLON;
  80752. (function (BABYLON) {
  80753. /**
  80754. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80755. */
  80756. var BloomMergePostProcess = /** @class */ (function (_super) {
  80757. __extends(BloomMergePostProcess, _super);
  80758. /**
  80759. * Creates a new instance of @see BloomMergePostProcess
  80760. * @param name The name of the effect.
  80761. * @param originalFromInput Post process which's input will be used for the merge.
  80762. * @param blurred Blurred highlights post process which's output will be used.
  80763. * @param weight Weight of the bloom to be added to the original input.
  80764. * @param options The required width/height ratio to downsize to before computing the render pass.
  80765. * @param camera The camera to apply the render pass to.
  80766. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80767. * @param engine The engine which the post process will be applied. (default: current engine)
  80768. * @param reusable If the post process can be reused on the same frame. (default: false)
  80769. * @param textureType Type of textures used when performing the post process. (default: 0)
  80770. * @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)
  80771. */
  80772. function BloomMergePostProcess(name, originalFromInput, blurred,
  80773. /** Weight of the bloom to be added to the original input. */
  80774. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80775. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80776. if (blockCompilation === void 0) { blockCompilation = false; }
  80777. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80778. _this.weight = weight;
  80779. _this.onApplyObservable.add(function (effect) {
  80780. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80781. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  80782. effect.setFloat("bloomWeight", _this.weight);
  80783. });
  80784. if (!blockCompilation) {
  80785. _this.updateEffect();
  80786. }
  80787. return _this;
  80788. }
  80789. return BloomMergePostProcess;
  80790. }(BABYLON.PostProcess));
  80791. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  80792. })(BABYLON || (BABYLON = {}));
  80793. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  80794. var BABYLON;
  80795. (function (BABYLON) {
  80796. /**
  80797. * 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.
  80798. */
  80799. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  80800. __extends(ExtractHighlightsPostProcess, _super);
  80801. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80802. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80803. if (blockCompilation === void 0) { blockCompilation = false; }
  80804. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80805. /**
  80806. * The luminance threshold, pixels below this value will be set to black.
  80807. */
  80808. _this.threshold = 0.9;
  80809. /** @hidden */
  80810. _this._exposure = 1;
  80811. /**
  80812. * Post process which has the input texture to be used when performing highlight extraction
  80813. * @hidden
  80814. */
  80815. _this._inputPostProcess = null;
  80816. _this.onApplyObservable.add(function (effect) {
  80817. if (_this._inputPostProcess) {
  80818. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  80819. }
  80820. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  80821. effect.setFloat('exposure', _this._exposure);
  80822. });
  80823. return _this;
  80824. }
  80825. return ExtractHighlightsPostProcess;
  80826. }(BABYLON.PostProcess));
  80827. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  80828. })(BABYLON || (BABYLON = {}));
  80829. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  80830. var BABYLON;
  80831. (function (BABYLON) {
  80832. /**
  80833. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  80834. */
  80835. var BloomEffect = /** @class */ (function (_super) {
  80836. __extends(BloomEffect, _super);
  80837. /**
  80838. * Creates a new instance of @see BloomEffect
  80839. * @param scene The scene the effect belongs to.
  80840. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  80841. * @param bloomKernel The size of the kernel to be used when applying the blur.
  80842. * @param bloomWeight The the strength of bloom.
  80843. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80844. * @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)
  80845. */
  80846. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  80847. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80848. if (blockCompilation === void 0) { blockCompilation = false; }
  80849. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  80850. return _this._effects;
  80851. }, true) || this;
  80852. _this.bloomScale = bloomScale;
  80853. /**
  80854. * @hidden Internal
  80855. */
  80856. _this._effects = [];
  80857. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80858. _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);
  80859. _this._blurX.alwaysForcePOT = true;
  80860. _this._blurX.autoClear = false;
  80861. _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);
  80862. _this._blurY.alwaysForcePOT = true;
  80863. _this._blurY.autoClear = false;
  80864. _this.kernel = bloomKernel;
  80865. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  80866. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80867. _this._merge.autoClear = false;
  80868. _this._effects.push(_this._merge);
  80869. return _this;
  80870. }
  80871. Object.defineProperty(BloomEffect.prototype, "threshold", {
  80872. /**
  80873. * The luminance threshold to find bright areas of the image to bloom.
  80874. */
  80875. get: function () {
  80876. return this._downscale.threshold;
  80877. },
  80878. set: function (value) {
  80879. this._downscale.threshold = value;
  80880. },
  80881. enumerable: true,
  80882. configurable: true
  80883. });
  80884. Object.defineProperty(BloomEffect.prototype, "weight", {
  80885. /**
  80886. * The strength of the bloom.
  80887. */
  80888. get: function () {
  80889. return this._merge.weight;
  80890. },
  80891. set: function (value) {
  80892. this._merge.weight = value;
  80893. },
  80894. enumerable: true,
  80895. configurable: true
  80896. });
  80897. Object.defineProperty(BloomEffect.prototype, "kernel", {
  80898. /**
  80899. * Specifies the size of the bloom blur kernel, relative to the final output size
  80900. */
  80901. get: function () {
  80902. return this._blurX.kernel / this.bloomScale;
  80903. },
  80904. set: function (value) {
  80905. this._blurX.kernel = value * this.bloomScale;
  80906. this._blurY.kernel = value * this.bloomScale;
  80907. },
  80908. enumerable: true,
  80909. configurable: true
  80910. });
  80911. /**
  80912. * Disposes each of the internal effects for a given camera.
  80913. * @param camera The camera to dispose the effect on.
  80914. */
  80915. BloomEffect.prototype.disposeEffects = function (camera) {
  80916. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80917. this._effects[effectIndex].dispose(camera);
  80918. }
  80919. };
  80920. /**
  80921. * @hidden Internal
  80922. */
  80923. BloomEffect.prototype._updateEffects = function () {
  80924. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80925. this._effects[effectIndex].updateEffect();
  80926. }
  80927. };
  80928. /**
  80929. * Internal
  80930. * @returns if all the contained post processes are ready.
  80931. * @hidden
  80932. */
  80933. BloomEffect.prototype._isReady = function () {
  80934. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80935. if (!this._effects[effectIndex].isReady()) {
  80936. return false;
  80937. }
  80938. }
  80939. return true;
  80940. };
  80941. return BloomEffect;
  80942. }(BABYLON.PostProcessRenderEffect));
  80943. BABYLON.BloomEffect = BloomEffect;
  80944. })(BABYLON || (BABYLON = {}));
  80945. //# sourceMappingURL=babylon.bloomEffect.js.map
  80946. var BABYLON;
  80947. (function (BABYLON) {
  80948. /**
  80949. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  80950. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  80951. */
  80952. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  80953. __extends(DefaultRenderingPipeline, _super);
  80954. /**
  80955. * @constructor
  80956. * @param {string} name - The rendering pipeline name (default: "")
  80957. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  80958. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  80959. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  80960. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  80961. */
  80962. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  80963. if (name === void 0) { name = ""; }
  80964. if (hdr === void 0) { hdr = true; }
  80965. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  80966. if (automaticBuild === void 0) { automaticBuild = true; }
  80967. var _this = _super.call(this, scene.getEngine(), name) || this;
  80968. _this._camerasToBeAttached = [];
  80969. /**
  80970. * ID of the sharpen post process,
  80971. */
  80972. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  80973. /**
  80974. * ID of the image processing post process;
  80975. */
  80976. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  80977. /**
  80978. * ID of the Fast Approximate Anti-Aliasing post process;
  80979. */
  80980. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  80981. /**
  80982. * ID of the chromatic aberration post process,
  80983. */
  80984. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  80985. /**
  80986. * ID of the grain post process
  80987. */
  80988. _this.GrainPostProcessId = "GrainPostProcessEffect";
  80989. /**
  80990. * Glow post process which adds a glow to emmisive areas of the image
  80991. */
  80992. _this._glowLayer = null;
  80993. /**
  80994. * Animations which can be used to tweak settings over a period of time
  80995. */
  80996. _this.animations = [];
  80997. _this._imageProcessingConfigurationObserver = null;
  80998. // Values
  80999. _this._sharpenEnabled = false;
  81000. _this._bloomEnabled = false;
  81001. _this._depthOfFieldEnabled = false;
  81002. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  81003. _this._fxaaEnabled = false;
  81004. _this._imageProcessingEnabled = true;
  81005. _this._bloomScale = 0.5;
  81006. _this._chromaticAberrationEnabled = false;
  81007. _this._grainEnabled = false;
  81008. _this._buildAllowed = true;
  81009. _this._resizeObserver = null;
  81010. _this._hardwareScaleLevel = 1.0;
  81011. _this._bloomKernel = 64;
  81012. /**
  81013. * Specifies the weight of the bloom in the final rendering
  81014. */
  81015. _this._bloomWeight = 0.15;
  81016. /**
  81017. * Specifies the luma threshold for the area that will be blurred by the bloom
  81018. */
  81019. _this._bloomThreshold = 0.9;
  81020. _this._samples = 1;
  81021. _this._hasCleared = false;
  81022. _this._prevPostProcess = null;
  81023. _this._prevPrevPostProcess = null;
  81024. _this._depthOfFieldSceneObserver = null;
  81025. _this._cameras = cameras || scene.cameras;
  81026. _this._cameras = _this._cameras.slice();
  81027. _this._camerasToBeAttached = _this._cameras.slice();
  81028. _this._buildAllowed = automaticBuild;
  81029. // Initialize
  81030. _this._scene = scene;
  81031. var caps = _this._scene.getEngine().getCaps();
  81032. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  81033. // Misc
  81034. if (_this._hdr) {
  81035. if (caps.textureHalfFloatRender) {
  81036. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81037. }
  81038. else if (caps.textureFloatRender) {
  81039. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81040. }
  81041. }
  81042. else {
  81043. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81044. }
  81045. // Attach
  81046. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81047. var engine = _this._scene.getEngine();
  81048. // Create post processes before hand so they can be modified before enabled.
  81049. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  81050. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81051. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  81052. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  81053. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  81054. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81055. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  81056. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81057. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  81058. _this._resizeObserver = engine.onResizeObservable.add(function () {
  81059. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  81060. _this.bloomKernel = _this.bloomKernel;
  81061. });
  81062. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  81063. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  81064. });
  81065. _this._buildPipeline();
  81066. return _this;
  81067. }
  81068. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  81069. get: function () {
  81070. return this._sharpenEnabled;
  81071. },
  81072. /**
  81073. * Enable or disable the sharpen process from the pipeline
  81074. */
  81075. set: function (enabled) {
  81076. if (this._sharpenEnabled === enabled) {
  81077. return;
  81078. }
  81079. this._sharpenEnabled = enabled;
  81080. this._buildPipeline();
  81081. },
  81082. enumerable: true,
  81083. configurable: true
  81084. });
  81085. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  81086. /**
  81087. * Specifies the size of the bloom blur kernel, relative to the final output size
  81088. */
  81089. get: function () {
  81090. return this._bloomKernel;
  81091. },
  81092. set: function (value) {
  81093. this._bloomKernel = value;
  81094. this.bloom.kernel = value / this._hardwareScaleLevel;
  81095. },
  81096. enumerable: true,
  81097. configurable: true
  81098. });
  81099. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  81100. get: function () {
  81101. return this._bloomWeight;
  81102. },
  81103. /**
  81104. * The strength of the bloom.
  81105. */
  81106. set: function (value) {
  81107. if (this._bloomWeight === value) {
  81108. return;
  81109. }
  81110. this.bloom.weight = value;
  81111. this._bloomWeight = value;
  81112. },
  81113. enumerable: true,
  81114. configurable: true
  81115. });
  81116. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  81117. get: function () {
  81118. return this._bloomThreshold;
  81119. },
  81120. /**
  81121. * The strength of the bloom.
  81122. */
  81123. set: function (value) {
  81124. if (this._bloomThreshold === value) {
  81125. return;
  81126. }
  81127. this.bloom.threshold = value;
  81128. this._bloomThreshold = value;
  81129. },
  81130. enumerable: true,
  81131. configurable: true
  81132. });
  81133. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  81134. get: function () {
  81135. return this._bloomScale;
  81136. },
  81137. /**
  81138. * The scale of the bloom, lower value will provide better performance.
  81139. */
  81140. set: function (value) {
  81141. if (this._bloomScale === value) {
  81142. return;
  81143. }
  81144. this._bloomScale = value;
  81145. // recreate bloom and dispose old as this setting is not dynamic
  81146. this._rebuildBloom();
  81147. this._buildPipeline();
  81148. },
  81149. enumerable: true,
  81150. configurable: true
  81151. });
  81152. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  81153. get: function () {
  81154. return this._bloomEnabled;
  81155. },
  81156. /**
  81157. * Enable or disable the bloom from the pipeline
  81158. */
  81159. set: function (enabled) {
  81160. if (this._bloomEnabled === enabled) {
  81161. return;
  81162. }
  81163. this._bloomEnabled = enabled;
  81164. this._buildPipeline();
  81165. },
  81166. enumerable: true,
  81167. configurable: true
  81168. });
  81169. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  81170. // recreate bloom and dispose old as this setting is not dynamic
  81171. var oldBloom = this.bloom;
  81172. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  81173. this.bloom.threshold = oldBloom.threshold;
  81174. for (var i = 0; i < this._cameras.length; i++) {
  81175. oldBloom.disposeEffects(this._cameras[i]);
  81176. }
  81177. };
  81178. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  81179. /**
  81180. * If the depth of field is enabled.
  81181. */
  81182. get: function () {
  81183. return this._depthOfFieldEnabled;
  81184. },
  81185. set: function (enabled) {
  81186. if (this._depthOfFieldEnabled === enabled) {
  81187. return;
  81188. }
  81189. this._depthOfFieldEnabled = enabled;
  81190. this._buildPipeline();
  81191. },
  81192. enumerable: true,
  81193. configurable: true
  81194. });
  81195. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  81196. /**
  81197. * Blur level of the depth of field effect. (Higher blur will effect performance)
  81198. */
  81199. get: function () {
  81200. return this._depthOfFieldBlurLevel;
  81201. },
  81202. set: function (value) {
  81203. if (this._depthOfFieldBlurLevel === value) {
  81204. return;
  81205. }
  81206. this._depthOfFieldBlurLevel = value;
  81207. // recreate dof and dispose old as this setting is not dynamic
  81208. var oldDof = this.depthOfField;
  81209. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  81210. this.depthOfField.focalLength = oldDof.focalLength;
  81211. this.depthOfField.focusDistance = oldDof.focusDistance;
  81212. this.depthOfField.fStop = oldDof.fStop;
  81213. this.depthOfField.lensSize = oldDof.lensSize;
  81214. for (var i = 0; i < this._cameras.length; i++) {
  81215. oldDof.disposeEffects(this._cameras[i]);
  81216. }
  81217. this._buildPipeline();
  81218. },
  81219. enumerable: true,
  81220. configurable: true
  81221. });
  81222. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  81223. get: function () {
  81224. return this._fxaaEnabled;
  81225. },
  81226. /**
  81227. * If the anti aliasing is enabled.
  81228. */
  81229. set: function (enabled) {
  81230. if (this._fxaaEnabled === enabled) {
  81231. return;
  81232. }
  81233. this._fxaaEnabled = enabled;
  81234. this._buildPipeline();
  81235. },
  81236. enumerable: true,
  81237. configurable: true
  81238. });
  81239. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  81240. get: function () {
  81241. return this._samples;
  81242. },
  81243. /**
  81244. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81245. */
  81246. set: function (sampleCount) {
  81247. if (this._samples === sampleCount) {
  81248. return;
  81249. }
  81250. this._samples = sampleCount;
  81251. this._buildPipeline();
  81252. },
  81253. enumerable: true,
  81254. configurable: true
  81255. });
  81256. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  81257. get: function () {
  81258. return this._imageProcessingEnabled;
  81259. },
  81260. /**
  81261. * If image processing is enabled.
  81262. */
  81263. set: function (enabled) {
  81264. if (this._imageProcessingEnabled === enabled) {
  81265. return;
  81266. }
  81267. this._imageProcessingEnabled = enabled;
  81268. this._buildPipeline();
  81269. },
  81270. enumerable: true,
  81271. configurable: true
  81272. });
  81273. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  81274. get: function () {
  81275. return this._glowLayer == null;
  81276. },
  81277. /**
  81278. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  81279. */
  81280. set: function (enabled) {
  81281. if (enabled && !this._glowLayer) {
  81282. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  81283. }
  81284. else if (!enabled && this._glowLayer) {
  81285. this._glowLayer.dispose();
  81286. this._glowLayer = null;
  81287. }
  81288. },
  81289. enumerable: true,
  81290. configurable: true
  81291. });
  81292. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  81293. get: function () {
  81294. return this._chromaticAberrationEnabled;
  81295. },
  81296. /**
  81297. * Enable or disable the chromaticAberration process from the pipeline
  81298. */
  81299. set: function (enabled) {
  81300. if (this._chromaticAberrationEnabled === enabled) {
  81301. return;
  81302. }
  81303. this._chromaticAberrationEnabled = enabled;
  81304. this._buildPipeline();
  81305. },
  81306. enumerable: true,
  81307. configurable: true
  81308. });
  81309. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  81310. get: function () {
  81311. return this._grainEnabled;
  81312. },
  81313. /**
  81314. * Enable or disable the grain process from the pipeline
  81315. */
  81316. set: function (enabled) {
  81317. if (this._grainEnabled === enabled) {
  81318. return;
  81319. }
  81320. this._grainEnabled = enabled;
  81321. this._buildPipeline();
  81322. },
  81323. enumerable: true,
  81324. configurable: true
  81325. });
  81326. /**
  81327. * Force the compilation of the entire pipeline.
  81328. */
  81329. DefaultRenderingPipeline.prototype.prepare = function () {
  81330. var previousState = this._buildAllowed;
  81331. this._buildAllowed = true;
  81332. this._buildPipeline();
  81333. this._buildAllowed = previousState;
  81334. };
  81335. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  81336. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  81337. if (this._hasCleared) {
  81338. postProcess.autoClear = false;
  81339. }
  81340. else {
  81341. postProcess.autoClear = true;
  81342. this._scene.autoClear = false;
  81343. this._hasCleared = true;
  81344. }
  81345. if (!skipTextureSharing) {
  81346. if (this._prevPrevPostProcess) {
  81347. postProcess.shareOutputWith(this._prevPrevPostProcess);
  81348. }
  81349. else {
  81350. postProcess.useOwnOutput();
  81351. }
  81352. if (this._prevPostProcess) {
  81353. this._prevPrevPostProcess = this._prevPostProcess;
  81354. }
  81355. this._prevPostProcess = postProcess;
  81356. }
  81357. };
  81358. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  81359. var _this = this;
  81360. if (!this._buildAllowed) {
  81361. return;
  81362. }
  81363. this._scene.autoClear = true;
  81364. var engine = this._scene.getEngine();
  81365. this._disposePostProcesses();
  81366. if (this._cameras !== null) {
  81367. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81368. // get back cameras to be used to reattach pipeline
  81369. this._cameras = this._camerasToBeAttached.slice();
  81370. }
  81371. this._reset();
  81372. this._prevPostProcess = null;
  81373. this._prevPrevPostProcess = null;
  81374. this._hasCleared = false;
  81375. if (this.depthOfFieldEnabled) {
  81376. // Multi camera suport
  81377. if (this._cameras.length > 1) {
  81378. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  81379. var camera = _a[_i];
  81380. var depthRenderer = this._scene.enableDepthRenderer(camera);
  81381. depthRenderer.useOnlyInActiveCamera = true;
  81382. }
  81383. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  81384. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  81385. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  81386. }
  81387. });
  81388. }
  81389. else {
  81390. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81391. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  81392. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  81393. }
  81394. if (!this.depthOfField._isReady()) {
  81395. this.depthOfField._updateEffects();
  81396. }
  81397. this.addEffect(this.depthOfField);
  81398. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  81399. }
  81400. else {
  81401. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81402. }
  81403. if (this.bloomEnabled) {
  81404. if (!this.bloom._isReady()) {
  81405. this.bloom._updateEffects();
  81406. }
  81407. this.addEffect(this.bloom);
  81408. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  81409. }
  81410. if (this._imageProcessingEnabled) {
  81411. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81412. if (this._hdr) {
  81413. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  81414. this._setAutoClearAndTextureSharing(this.imageProcessing);
  81415. }
  81416. else {
  81417. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  81418. }
  81419. }
  81420. if (this.sharpenEnabled) {
  81421. if (!this.sharpen.isReady()) {
  81422. this.sharpen.updateEffect();
  81423. }
  81424. this.addEffect(this._sharpenEffect);
  81425. this._setAutoClearAndTextureSharing(this.sharpen);
  81426. }
  81427. if (this.grainEnabled) {
  81428. if (!this.grain.isReady()) {
  81429. this.grain.updateEffect();
  81430. }
  81431. this.addEffect(this._grainEffect);
  81432. this._setAutoClearAndTextureSharing(this.grain);
  81433. }
  81434. if (this.chromaticAberrationEnabled) {
  81435. if (!this.chromaticAberration.isReady()) {
  81436. this.chromaticAberration.updateEffect();
  81437. }
  81438. this.addEffect(this._chromaticAberrationEffect);
  81439. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  81440. }
  81441. if (this.fxaaEnabled) {
  81442. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81443. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  81444. this._setAutoClearAndTextureSharing(this.fxaa, true);
  81445. }
  81446. if (this._cameras !== null) {
  81447. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81448. }
  81449. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  81450. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81451. }
  81452. };
  81453. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  81454. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  81455. for (var i = 0; i < this._cameras.length; i++) {
  81456. var camera = this._cameras[i];
  81457. if (this.imageProcessing) {
  81458. this.imageProcessing.dispose(camera);
  81459. }
  81460. if (this.fxaa) {
  81461. this.fxaa.dispose(camera);
  81462. }
  81463. // These are created in the constructor and should not be disposed on every pipeline change
  81464. if (disposeNonRecreated) {
  81465. if (this.sharpen) {
  81466. this.sharpen.dispose(camera);
  81467. }
  81468. if (this.depthOfField) {
  81469. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81470. this.depthOfField.disposeEffects(camera);
  81471. }
  81472. if (this.bloom) {
  81473. this.bloom.disposeEffects(camera);
  81474. }
  81475. if (this.chromaticAberration) {
  81476. this.chromaticAberration.dispose(camera);
  81477. }
  81478. if (this.grain) {
  81479. this.grain.dispose(camera);
  81480. }
  81481. if (this._glowLayer) {
  81482. this._glowLayer.dispose();
  81483. }
  81484. }
  81485. }
  81486. this.imageProcessing = null;
  81487. this.fxaa = null;
  81488. if (disposeNonRecreated) {
  81489. this.sharpen = null;
  81490. this._sharpenEffect = null;
  81491. this.depthOfField = null;
  81492. this.bloom = null;
  81493. this.chromaticAberration = null;
  81494. this._chromaticAberrationEffect = null;
  81495. this.grain = null;
  81496. this._grainEffect = null;
  81497. this._glowLayer = null;
  81498. }
  81499. };
  81500. /**
  81501. * Adds a camera to the pipeline
  81502. * @param camera the camera to be added
  81503. */
  81504. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  81505. this._camerasToBeAttached.push(camera);
  81506. this._buildPipeline();
  81507. };
  81508. /**
  81509. * Removes a camera from the pipeline
  81510. * @param camera the camera to remove
  81511. */
  81512. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  81513. var index = this._camerasToBeAttached.indexOf(camera);
  81514. this._camerasToBeAttached.splice(index, 1);
  81515. this._buildPipeline();
  81516. };
  81517. /**
  81518. * Dispose of the pipeline and stop all post processes
  81519. */
  81520. DefaultRenderingPipeline.prototype.dispose = function () {
  81521. this._disposePostProcesses(true);
  81522. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81523. this._scene.autoClear = true;
  81524. if (this._resizeObserver) {
  81525. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  81526. this._resizeObserver = null;
  81527. }
  81528. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  81529. _super.prototype.dispose.call(this);
  81530. };
  81531. /**
  81532. * Serialize the rendering pipeline (Used when exporting)
  81533. * @returns the serialized object
  81534. */
  81535. DefaultRenderingPipeline.prototype.serialize = function () {
  81536. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81537. serializationObject.customType = "DefaultRenderingPipeline";
  81538. return serializationObject;
  81539. };
  81540. /**
  81541. * Parse the serialized pipeline
  81542. * @param source Source pipeline.
  81543. * @param scene The scene to load the pipeline to.
  81544. * @param rootUrl The URL of the serialized pipeline.
  81545. * @returns An instantiated pipeline from the serialized object.
  81546. */
  81547. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81548. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  81549. };
  81550. __decorate([
  81551. BABYLON.serialize()
  81552. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  81553. __decorate([
  81554. BABYLON.serialize()
  81555. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  81556. __decorate([
  81557. BABYLON.serialize()
  81558. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  81559. __decorate([
  81560. BABYLON.serialize()
  81561. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  81562. __decorate([
  81563. BABYLON.serialize()
  81564. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  81565. __decorate([
  81566. BABYLON.serialize()
  81567. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  81568. __decorate([
  81569. BABYLON.serialize()
  81570. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  81571. __decorate([
  81572. BABYLON.serialize()
  81573. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  81574. __decorate([
  81575. BABYLON.serialize()
  81576. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  81577. __decorate([
  81578. BABYLON.serialize()
  81579. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  81580. __decorate([
  81581. BABYLON.serialize()
  81582. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  81583. __decorate([
  81584. BABYLON.serialize()
  81585. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  81586. __decorate([
  81587. BABYLON.serialize()
  81588. ], DefaultRenderingPipeline.prototype, "samples", null);
  81589. __decorate([
  81590. BABYLON.serialize()
  81591. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  81592. __decorate([
  81593. BABYLON.serialize()
  81594. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  81595. __decorate([
  81596. BABYLON.serialize()
  81597. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  81598. __decorate([
  81599. BABYLON.serialize()
  81600. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  81601. return DefaultRenderingPipeline;
  81602. }(BABYLON.PostProcessRenderPipeline));
  81603. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  81604. })(BABYLON || (BABYLON = {}));
  81605. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  81606. var BABYLON;
  81607. (function (BABYLON) {
  81608. /**
  81609. * @hidden
  81610. */
  81611. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  81612. __extends(ImageProcessingConfigurationDefines, _super);
  81613. function ImageProcessingConfigurationDefines() {
  81614. var _this = _super.call(this) || this;
  81615. _this.IMAGEPROCESSING = false;
  81616. _this.VIGNETTE = false;
  81617. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  81618. _this.VIGNETTEBLENDMODEOPAQUE = false;
  81619. _this.TONEMAPPING = false;
  81620. _this.TONEMAPPING_ACES = false;
  81621. _this.CONTRAST = false;
  81622. _this.COLORCURVES = false;
  81623. _this.COLORGRADING = false;
  81624. _this.COLORGRADING3D = false;
  81625. _this.SAMPLER3DGREENDEPTH = false;
  81626. _this.SAMPLER3DBGRMAP = false;
  81627. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  81628. _this.EXPOSURE = false;
  81629. _this.rebuild();
  81630. return _this;
  81631. }
  81632. return ImageProcessingConfigurationDefines;
  81633. }(BABYLON.MaterialDefines));
  81634. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  81635. /**
  81636. * This groups together the common properties used for image processing either in direct forward pass
  81637. * or through post processing effect depending on the use of the image processing pipeline in your scene
  81638. * or not.
  81639. */
  81640. var ImageProcessingConfiguration = /** @class */ (function () {
  81641. function ImageProcessingConfiguration() {
  81642. /**
  81643. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  81644. */
  81645. this.colorCurves = new BABYLON.ColorCurves();
  81646. this._colorCurvesEnabled = false;
  81647. this._colorGradingEnabled = false;
  81648. this._colorGradingWithGreenDepth = true;
  81649. this._colorGradingBGR = true;
  81650. /** @hidden */
  81651. this._exposure = 1.0;
  81652. this._toneMappingEnabled = false;
  81653. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  81654. this._contrast = 1.0;
  81655. /**
  81656. * Vignette stretch size.
  81657. */
  81658. this.vignetteStretch = 0;
  81659. /**
  81660. * Vignette centre X Offset.
  81661. */
  81662. this.vignetteCentreX = 0;
  81663. /**
  81664. * Vignette centre Y Offset.
  81665. */
  81666. this.vignetteCentreY = 0;
  81667. /**
  81668. * Vignette weight or intensity of the vignette effect.
  81669. */
  81670. this.vignetteWeight = 1.5;
  81671. /**
  81672. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81673. * if vignetteEnabled is set to true.
  81674. */
  81675. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81676. /**
  81677. * Camera field of view used by the Vignette effect.
  81678. */
  81679. this.vignetteCameraFov = 0.5;
  81680. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  81681. this._vignetteEnabled = false;
  81682. this._applyByPostProcess = false;
  81683. this._isEnabled = true;
  81684. /**
  81685. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  81686. */
  81687. this.onUpdateParameters = new BABYLON.Observable();
  81688. }
  81689. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  81690. /**
  81691. * Gets wether the color curves effect is enabled.
  81692. */
  81693. get: function () {
  81694. return this._colorCurvesEnabled;
  81695. },
  81696. /**
  81697. * Sets wether the color curves effect is enabled.
  81698. */
  81699. set: function (value) {
  81700. if (this._colorCurvesEnabled === value) {
  81701. return;
  81702. }
  81703. this._colorCurvesEnabled = value;
  81704. this._updateParameters();
  81705. },
  81706. enumerable: true,
  81707. configurable: true
  81708. });
  81709. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  81710. /**
  81711. * Gets wether the color grading effect is enabled.
  81712. */
  81713. get: function () {
  81714. return this._colorGradingEnabled;
  81715. },
  81716. /**
  81717. * Sets wether the color grading effect is enabled.
  81718. */
  81719. set: function (value) {
  81720. if (this._colorGradingEnabled === value) {
  81721. return;
  81722. }
  81723. this._colorGradingEnabled = value;
  81724. this._updateParameters();
  81725. },
  81726. enumerable: true,
  81727. configurable: true
  81728. });
  81729. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  81730. /**
  81731. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  81732. */
  81733. get: function () {
  81734. return this._colorGradingWithGreenDepth;
  81735. },
  81736. /**
  81737. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  81738. */
  81739. set: function (value) {
  81740. if (this._colorGradingWithGreenDepth === value) {
  81741. return;
  81742. }
  81743. this._colorGradingWithGreenDepth = value;
  81744. this._updateParameters();
  81745. },
  81746. enumerable: true,
  81747. configurable: true
  81748. });
  81749. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  81750. /**
  81751. * Gets wether the color grading texture contains BGR values.
  81752. */
  81753. get: function () {
  81754. return this._colorGradingBGR;
  81755. },
  81756. /**
  81757. * Sets wether the color grading texture contains BGR values.
  81758. */
  81759. set: function (value) {
  81760. if (this._colorGradingBGR === value) {
  81761. return;
  81762. }
  81763. this._colorGradingBGR = value;
  81764. this._updateParameters();
  81765. },
  81766. enumerable: true,
  81767. configurable: true
  81768. });
  81769. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  81770. /**
  81771. * Gets the Exposure used in the effect.
  81772. */
  81773. get: function () {
  81774. return this._exposure;
  81775. },
  81776. /**
  81777. * Sets the Exposure used in the effect.
  81778. */
  81779. set: function (value) {
  81780. if (this._exposure === value) {
  81781. return;
  81782. }
  81783. this._exposure = value;
  81784. this._updateParameters();
  81785. },
  81786. enumerable: true,
  81787. configurable: true
  81788. });
  81789. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  81790. /**
  81791. * Gets wether the tone mapping effect is enabled.
  81792. */
  81793. get: function () {
  81794. return this._toneMappingEnabled;
  81795. },
  81796. /**
  81797. * Sets wether the tone mapping effect is enabled.
  81798. */
  81799. set: function (value) {
  81800. if (this._toneMappingEnabled === value) {
  81801. return;
  81802. }
  81803. this._toneMappingEnabled = value;
  81804. this._updateParameters();
  81805. },
  81806. enumerable: true,
  81807. configurable: true
  81808. });
  81809. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  81810. /**
  81811. * Gets the type of tone mapping effect.
  81812. */
  81813. get: function () {
  81814. return this._toneMappingType;
  81815. },
  81816. /**
  81817. * Sets the type of tone mapping effect used in BabylonJS.
  81818. */
  81819. set: function (value) {
  81820. if (this._toneMappingType === value) {
  81821. return;
  81822. }
  81823. this._toneMappingType = value;
  81824. this._updateParameters();
  81825. },
  81826. enumerable: true,
  81827. configurable: true
  81828. });
  81829. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  81830. /**
  81831. * Gets the contrast used in the effect.
  81832. */
  81833. get: function () {
  81834. return this._contrast;
  81835. },
  81836. /**
  81837. * Sets the contrast used in the effect.
  81838. */
  81839. set: function (value) {
  81840. if (this._contrast === value) {
  81841. return;
  81842. }
  81843. this._contrast = value;
  81844. this._updateParameters();
  81845. },
  81846. enumerable: true,
  81847. configurable: true
  81848. });
  81849. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  81850. /**
  81851. * Gets the vignette blend mode allowing different kind of effect.
  81852. */
  81853. get: function () {
  81854. return this._vignetteBlendMode;
  81855. },
  81856. /**
  81857. * Sets the vignette blend mode allowing different kind of effect.
  81858. */
  81859. set: function (value) {
  81860. if (this._vignetteBlendMode === value) {
  81861. return;
  81862. }
  81863. this._vignetteBlendMode = value;
  81864. this._updateParameters();
  81865. },
  81866. enumerable: true,
  81867. configurable: true
  81868. });
  81869. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  81870. /**
  81871. * Gets wether the vignette effect is enabled.
  81872. */
  81873. get: function () {
  81874. return this._vignetteEnabled;
  81875. },
  81876. /**
  81877. * Sets wether the vignette effect is enabled.
  81878. */
  81879. set: function (value) {
  81880. if (this._vignetteEnabled === value) {
  81881. return;
  81882. }
  81883. this._vignetteEnabled = value;
  81884. this._updateParameters();
  81885. },
  81886. enumerable: true,
  81887. configurable: true
  81888. });
  81889. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  81890. /**
  81891. * Gets wether the image processing is applied through a post process or not.
  81892. */
  81893. get: function () {
  81894. return this._applyByPostProcess;
  81895. },
  81896. /**
  81897. * Sets wether the image processing is applied through a post process or not.
  81898. */
  81899. set: function (value) {
  81900. if (this._applyByPostProcess === value) {
  81901. return;
  81902. }
  81903. this._applyByPostProcess = value;
  81904. this._updateParameters();
  81905. },
  81906. enumerable: true,
  81907. configurable: true
  81908. });
  81909. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  81910. /**
  81911. * Gets wether the image processing is enabled or not.
  81912. */
  81913. get: function () {
  81914. return this._isEnabled;
  81915. },
  81916. /**
  81917. * Sets wether the image processing is enabled or not.
  81918. */
  81919. set: function (value) {
  81920. if (this._isEnabled === value) {
  81921. return;
  81922. }
  81923. this._isEnabled = value;
  81924. this._updateParameters();
  81925. },
  81926. enumerable: true,
  81927. configurable: true
  81928. });
  81929. /**
  81930. * Method called each time the image processing information changes requires to recompile the effect.
  81931. */
  81932. ImageProcessingConfiguration.prototype._updateParameters = function () {
  81933. this.onUpdateParameters.notifyObservers(this);
  81934. };
  81935. ImageProcessingConfiguration.prototype.getClassName = function () {
  81936. return "ImageProcessingConfiguration";
  81937. };
  81938. /**
  81939. * Prepare the list of uniforms associated with the Image Processing effects.
  81940. * @param uniformsList The list of uniforms used in the effect
  81941. * @param defines the list of defines currently in use
  81942. */
  81943. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  81944. if (defines.EXPOSURE) {
  81945. uniforms.push("exposureLinear");
  81946. }
  81947. if (defines.CONTRAST) {
  81948. uniforms.push("contrast");
  81949. }
  81950. if (defines.COLORGRADING) {
  81951. uniforms.push("colorTransformSettings");
  81952. }
  81953. if (defines.VIGNETTE) {
  81954. uniforms.push("vInverseScreenSize");
  81955. uniforms.push("vignetteSettings1");
  81956. uniforms.push("vignetteSettings2");
  81957. }
  81958. if (defines.COLORCURVES) {
  81959. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  81960. }
  81961. };
  81962. /**
  81963. * Prepare the list of samplers associated with the Image Processing effects.
  81964. * @param uniformsList The list of uniforms used in the effect
  81965. * @param defines the list of defines currently in use
  81966. */
  81967. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  81968. if (defines.COLORGRADING) {
  81969. samplersList.push("txColorTransform");
  81970. }
  81971. };
  81972. /**
  81973. * Prepare the list of defines associated to the shader.
  81974. * @param defines the list of defines to complete
  81975. */
  81976. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  81977. if (forPostProcess === void 0) { forPostProcess = false; }
  81978. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  81979. defines.VIGNETTE = false;
  81980. defines.TONEMAPPING = false;
  81981. defines.TONEMAPPING_ACES = false;
  81982. defines.CONTRAST = false;
  81983. defines.EXPOSURE = false;
  81984. defines.COLORCURVES = false;
  81985. defines.COLORGRADING = false;
  81986. defines.COLORGRADING3D = false;
  81987. defines.IMAGEPROCESSING = false;
  81988. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  81989. return;
  81990. }
  81991. defines.VIGNETTE = this.vignetteEnabled;
  81992. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  81993. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  81994. defines.TONEMAPPING = this.toneMappingEnabled;
  81995. switch (this._toneMappingType) {
  81996. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  81997. defines.TONEMAPPING_ACES = true;
  81998. break;
  81999. }
  82000. defines.CONTRAST = (this.contrast !== 1.0);
  82001. defines.EXPOSURE = (this.exposure !== 1.0);
  82002. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  82003. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  82004. if (defines.COLORGRADING) {
  82005. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  82006. }
  82007. else {
  82008. defines.COLORGRADING3D = false;
  82009. }
  82010. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  82011. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  82012. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  82013. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  82014. };
  82015. /**
  82016. * Returns true if all the image processing information are ready.
  82017. */
  82018. ImageProcessingConfiguration.prototype.isReady = function () {
  82019. // Color Grading texure can not be none blocking.
  82020. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  82021. };
  82022. /**
  82023. * Binds the image processing to the shader.
  82024. * @param effect The effect to bind to
  82025. */
  82026. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  82027. if (aspectRatio === void 0) { aspectRatio = 1; }
  82028. // Color Curves
  82029. if (this._colorCurvesEnabled && this.colorCurves) {
  82030. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  82031. }
  82032. // Vignette
  82033. if (this._vignetteEnabled) {
  82034. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  82035. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  82036. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  82037. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  82038. var vignetteScaleX = vignetteScaleY * aspectRatio;
  82039. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  82040. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  82041. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  82042. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  82043. var vignettePower = -2.0 * this.vignetteWeight;
  82044. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  82045. }
  82046. // Exposure
  82047. effect.setFloat("exposureLinear", this.exposure);
  82048. // Contrast
  82049. effect.setFloat("contrast", this.contrast);
  82050. // Color transform settings
  82051. if (this.colorGradingTexture) {
  82052. effect.setTexture("txColorTransform", this.colorGradingTexture);
  82053. var textureSize = this.colorGradingTexture.getSize().height;
  82054. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  82055. 0.5 / textureSize, // textureOffset
  82056. textureSize, // textureSize
  82057. this.colorGradingTexture.level // weight
  82058. );
  82059. }
  82060. };
  82061. /**
  82062. * Clones the current image processing instance.
  82063. * @return The cloned image processing
  82064. */
  82065. ImageProcessingConfiguration.prototype.clone = function () {
  82066. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  82067. };
  82068. /**
  82069. * Serializes the current image processing instance to a json representation.
  82070. * @return a JSON representation
  82071. */
  82072. ImageProcessingConfiguration.prototype.serialize = function () {
  82073. return BABYLON.SerializationHelper.Serialize(this);
  82074. };
  82075. /**
  82076. * Parses the image processing from a json representation.
  82077. * @param source the JSON source to parse
  82078. * @return The parsed image processing
  82079. */
  82080. ImageProcessingConfiguration.Parse = function (source) {
  82081. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  82082. };
  82083. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  82084. /**
  82085. * Used to apply the vignette as a mix with the pixel color.
  82086. */
  82087. get: function () {
  82088. return this._VIGNETTEMODE_MULTIPLY;
  82089. },
  82090. enumerable: true,
  82091. configurable: true
  82092. });
  82093. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  82094. /**
  82095. * Used to apply the vignette as a replacement of the pixel color.
  82096. */
  82097. get: function () {
  82098. return this._VIGNETTEMODE_OPAQUE;
  82099. },
  82100. enumerable: true,
  82101. configurable: true
  82102. });
  82103. /**
  82104. * Default tone mapping applied in BabylonJS.
  82105. */
  82106. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  82107. /**
  82108. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  82109. * to other engines rendering to increase portability.
  82110. */
  82111. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  82112. // Static constants associated to the image processing.
  82113. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  82114. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  82115. __decorate([
  82116. BABYLON.serializeAsColorCurves()
  82117. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  82118. __decorate([
  82119. BABYLON.serialize()
  82120. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  82121. __decorate([
  82122. BABYLON.serializeAsTexture()
  82123. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  82124. __decorate([
  82125. BABYLON.serialize()
  82126. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  82127. __decorate([
  82128. BABYLON.serialize()
  82129. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  82130. __decorate([
  82131. BABYLON.serialize()
  82132. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  82133. __decorate([
  82134. BABYLON.serialize()
  82135. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  82136. __decorate([
  82137. BABYLON.serialize()
  82138. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  82139. __decorate([
  82140. BABYLON.serialize()
  82141. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  82142. __decorate([
  82143. BABYLON.serialize()
  82144. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  82145. __decorate([
  82146. BABYLON.serialize()
  82147. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  82148. __decorate([
  82149. BABYLON.serialize()
  82150. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  82151. __decorate([
  82152. BABYLON.serialize()
  82153. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  82154. __decorate([
  82155. BABYLON.serialize()
  82156. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  82157. __decorate([
  82158. BABYLON.serializeAsColor4()
  82159. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  82160. __decorate([
  82161. BABYLON.serialize()
  82162. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  82163. __decorate([
  82164. BABYLON.serialize()
  82165. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  82166. __decorate([
  82167. BABYLON.serialize()
  82168. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  82169. __decorate([
  82170. BABYLON.serialize()
  82171. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  82172. __decorate([
  82173. BABYLON.serialize()
  82174. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  82175. return ImageProcessingConfiguration;
  82176. }());
  82177. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  82178. })(BABYLON || (BABYLON = {}));
  82179. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  82180. var BABYLON;
  82181. (function (BABYLON) {
  82182. /**
  82183. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  82184. * It can help converting any input color in a desired output one. This can then be used to create effects
  82185. * from sepia, black and white to sixties or futuristic rendering...
  82186. *
  82187. * The only supported format is currently 3dl.
  82188. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  82189. */
  82190. var ColorGradingTexture = /** @class */ (function (_super) {
  82191. __extends(ColorGradingTexture, _super);
  82192. /**
  82193. * Instantiates a ColorGradingTexture from the following parameters.
  82194. *
  82195. * @param url The location of the color gradind data (currently only supporting 3dl)
  82196. * @param scene The scene the texture will be used in
  82197. */
  82198. function ColorGradingTexture(url, scene) {
  82199. var _this = _super.call(this, scene) || this;
  82200. if (!url) {
  82201. return _this;
  82202. }
  82203. _this._engine = scene.getEngine();
  82204. _this._textureMatrix = BABYLON.Matrix.Identity();
  82205. _this.name = url;
  82206. _this.url = url;
  82207. _this.hasAlpha = false;
  82208. _this.isCube = false;
  82209. _this.is3D = _this._engine.webGLVersion > 1;
  82210. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82211. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82212. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82213. _this.anisotropicFilteringLevel = 1;
  82214. _this._texture = _this._getFromCache(url, true);
  82215. if (!_this._texture) {
  82216. if (!scene.useDelayedTextureLoading) {
  82217. _this.loadTexture();
  82218. }
  82219. else {
  82220. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82221. }
  82222. }
  82223. return _this;
  82224. }
  82225. /**
  82226. * Returns the texture matrix used in most of the material.
  82227. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  82228. */
  82229. ColorGradingTexture.prototype.getTextureMatrix = function () {
  82230. return this._textureMatrix;
  82231. };
  82232. /**
  82233. * Occurs when the file being loaded is a .3dl LUT file.
  82234. */
  82235. ColorGradingTexture.prototype.load3dlTexture = function () {
  82236. var engine = this._engine;
  82237. var texture;
  82238. if (engine.webGLVersion === 1) {
  82239. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82240. }
  82241. else {
  82242. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82243. }
  82244. this._texture = texture;
  82245. var callback = function (text) {
  82246. if (typeof text !== "string") {
  82247. return;
  82248. }
  82249. var data = null;
  82250. var tempData = null;
  82251. var line;
  82252. var lines = text.split('\n');
  82253. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  82254. var maxColor = 0;
  82255. for (var i = 0; i < lines.length; i++) {
  82256. line = lines[i];
  82257. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  82258. continue;
  82259. if (line.indexOf('#') === 0)
  82260. continue;
  82261. var words = line.split(" ");
  82262. if (size === 0) {
  82263. // Number of space + one
  82264. size = words.length;
  82265. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  82266. tempData = new Float32Array(size * size * size * 4);
  82267. continue;
  82268. }
  82269. if (size != 0) {
  82270. var r = Math.max(parseInt(words[0]), 0);
  82271. var g = Math.max(parseInt(words[1]), 0);
  82272. var b = Math.max(parseInt(words[2]), 0);
  82273. maxColor = Math.max(r, maxColor);
  82274. maxColor = Math.max(g, maxColor);
  82275. maxColor = Math.max(b, maxColor);
  82276. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  82277. if (tempData) {
  82278. tempData[pixelStorageIndex + 0] = r;
  82279. tempData[pixelStorageIndex + 1] = g;
  82280. tempData[pixelStorageIndex + 2] = b;
  82281. }
  82282. pixelIndexSlice++;
  82283. if (pixelIndexSlice % size == 0) {
  82284. pixelIndexH++;
  82285. pixelIndexSlice = 0;
  82286. if (pixelIndexH % size == 0) {
  82287. pixelIndexW++;
  82288. pixelIndexH = 0;
  82289. }
  82290. }
  82291. }
  82292. }
  82293. if (tempData && data) {
  82294. for (var i = 0; i < tempData.length; i++) {
  82295. if (i > 0 && (i + 1) % 4 === 0) {
  82296. data[i] = 255;
  82297. }
  82298. else {
  82299. var value = tempData[i];
  82300. data[i] = (value / maxColor * 255);
  82301. }
  82302. }
  82303. }
  82304. if (texture.is3D) {
  82305. texture.updateSize(size, size, size);
  82306. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82307. }
  82308. else {
  82309. texture.updateSize(size * size, size);
  82310. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82311. }
  82312. };
  82313. var scene = this.getScene();
  82314. if (scene) {
  82315. scene._loadFile(this.url, callback);
  82316. }
  82317. else {
  82318. this._engine._loadFile(this.url, callback);
  82319. }
  82320. return this._texture;
  82321. };
  82322. /**
  82323. * Starts the loading process of the texture.
  82324. */
  82325. ColorGradingTexture.prototype.loadTexture = function () {
  82326. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  82327. this.load3dlTexture();
  82328. }
  82329. };
  82330. /**
  82331. * Clones the color gradind texture.
  82332. */
  82333. ColorGradingTexture.prototype.clone = function () {
  82334. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  82335. // Base texture
  82336. newTexture.level = this.level;
  82337. return newTexture;
  82338. };
  82339. /**
  82340. * Called during delayed load for textures.
  82341. */
  82342. ColorGradingTexture.prototype.delayLoad = function () {
  82343. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82344. return;
  82345. }
  82346. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82347. this._texture = this._getFromCache(this.url, true);
  82348. if (!this._texture) {
  82349. this.loadTexture();
  82350. }
  82351. };
  82352. /**
  82353. * Parses a color grading texture serialized by Babylon.
  82354. * @param parsedTexture The texture information being parsedTexture
  82355. * @param scene The scene to load the texture in
  82356. * @param rootUrl The root url of the data assets to load
  82357. * @return A color gradind texture
  82358. */
  82359. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82360. var texture = null;
  82361. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82362. texture = new ColorGradingTexture(parsedTexture.name, scene);
  82363. texture.name = parsedTexture.name;
  82364. texture.level = parsedTexture.level;
  82365. }
  82366. return texture;
  82367. };
  82368. /**
  82369. * Serializes the LUT texture to json format.
  82370. */
  82371. ColorGradingTexture.prototype.serialize = function () {
  82372. if (!this.name) {
  82373. return null;
  82374. }
  82375. var serializationObject = {};
  82376. serializationObject.name = this.name;
  82377. serializationObject.level = this.level;
  82378. serializationObject.customType = "BABYLON.ColorGradingTexture";
  82379. return serializationObject;
  82380. };
  82381. /**
  82382. * Empty line regex stored for GC.
  82383. */
  82384. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  82385. return ColorGradingTexture;
  82386. }(BABYLON.BaseTexture));
  82387. BABYLON.ColorGradingTexture = ColorGradingTexture;
  82388. })(BABYLON || (BABYLON = {}));
  82389. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  82390. var BABYLON;
  82391. (function (BABYLON) {
  82392. /**
  82393. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82394. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82395. * 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;
  82396. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82397. */
  82398. var ColorCurves = /** @class */ (function () {
  82399. function ColorCurves() {
  82400. this._dirty = true;
  82401. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  82402. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  82403. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82404. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  82405. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82406. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  82407. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  82408. this._globalHue = 30;
  82409. this._globalDensity = 0;
  82410. this._globalSaturation = 0;
  82411. this._globalExposure = 0;
  82412. this._highlightsHue = 30;
  82413. this._highlightsDensity = 0;
  82414. this._highlightsSaturation = 0;
  82415. this._highlightsExposure = 0;
  82416. this._midtonesHue = 30;
  82417. this._midtonesDensity = 0;
  82418. this._midtonesSaturation = 0;
  82419. this._midtonesExposure = 0;
  82420. this._shadowsHue = 30;
  82421. this._shadowsDensity = 0;
  82422. this._shadowsSaturation = 0;
  82423. this._shadowsExposure = 0;
  82424. }
  82425. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  82426. /**
  82427. * Gets the global Hue value.
  82428. * 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).
  82429. */
  82430. get: function () {
  82431. return this._globalHue;
  82432. },
  82433. /**
  82434. * Sets the global Hue value.
  82435. * 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).
  82436. */
  82437. set: function (value) {
  82438. this._globalHue = value;
  82439. this._dirty = true;
  82440. },
  82441. enumerable: true,
  82442. configurable: true
  82443. });
  82444. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  82445. /**
  82446. * Gets the global Density value.
  82447. * 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.
  82448. * Values less than zero provide a filter of opposite hue.
  82449. */
  82450. get: function () {
  82451. return this._globalDensity;
  82452. },
  82453. /**
  82454. * Sets the global Density value.
  82455. * 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.
  82456. * Values less than zero provide a filter of opposite hue.
  82457. */
  82458. set: function (value) {
  82459. this._globalDensity = value;
  82460. this._dirty = true;
  82461. },
  82462. enumerable: true,
  82463. configurable: true
  82464. });
  82465. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  82466. /**
  82467. * Gets the global Saturation value.
  82468. * 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.
  82469. */
  82470. get: function () {
  82471. return this._globalSaturation;
  82472. },
  82473. /**
  82474. * Sets the global Saturation value.
  82475. * 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.
  82476. */
  82477. set: function (value) {
  82478. this._globalSaturation = value;
  82479. this._dirty = true;
  82480. },
  82481. enumerable: true,
  82482. configurable: true
  82483. });
  82484. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  82485. /**
  82486. * Gets the global Exposure value.
  82487. * 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.
  82488. */
  82489. get: function () {
  82490. return this._globalExposure;
  82491. },
  82492. /**
  82493. * Sets the global Exposure value.
  82494. * 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.
  82495. */
  82496. set: function (value) {
  82497. this._globalExposure = value;
  82498. this._dirty = true;
  82499. },
  82500. enumerable: true,
  82501. configurable: true
  82502. });
  82503. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  82504. /**
  82505. * Gets the highlights Hue value.
  82506. * 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).
  82507. */
  82508. get: function () {
  82509. return this._highlightsHue;
  82510. },
  82511. /**
  82512. * Sets the highlights Hue value.
  82513. * 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).
  82514. */
  82515. set: function (value) {
  82516. this._highlightsHue = value;
  82517. this._dirty = true;
  82518. },
  82519. enumerable: true,
  82520. configurable: true
  82521. });
  82522. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  82523. /**
  82524. * Gets the highlights Density value.
  82525. * 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.
  82526. * Values less than zero provide a filter of opposite hue.
  82527. */
  82528. get: function () {
  82529. return this._highlightsDensity;
  82530. },
  82531. /**
  82532. * Sets the highlights Density value.
  82533. * 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.
  82534. * Values less than zero provide a filter of opposite hue.
  82535. */
  82536. set: function (value) {
  82537. this._highlightsDensity = value;
  82538. this._dirty = true;
  82539. },
  82540. enumerable: true,
  82541. configurable: true
  82542. });
  82543. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  82544. /**
  82545. * Gets the highlights Saturation value.
  82546. * 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.
  82547. */
  82548. get: function () {
  82549. return this._highlightsSaturation;
  82550. },
  82551. /**
  82552. * Sets the highlights Saturation value.
  82553. * 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.
  82554. */
  82555. set: function (value) {
  82556. this._highlightsSaturation = value;
  82557. this._dirty = true;
  82558. },
  82559. enumerable: true,
  82560. configurable: true
  82561. });
  82562. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  82563. /**
  82564. * Gets the highlights Exposure value.
  82565. * 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.
  82566. */
  82567. get: function () {
  82568. return this._highlightsExposure;
  82569. },
  82570. /**
  82571. * Sets the highlights Exposure value.
  82572. * 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.
  82573. */
  82574. set: function (value) {
  82575. this._highlightsExposure = value;
  82576. this._dirty = true;
  82577. },
  82578. enumerable: true,
  82579. configurable: true
  82580. });
  82581. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  82582. /**
  82583. * Gets the midtones Hue value.
  82584. * 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).
  82585. */
  82586. get: function () {
  82587. return this._midtonesHue;
  82588. },
  82589. /**
  82590. * Sets the midtones Hue value.
  82591. * 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).
  82592. */
  82593. set: function (value) {
  82594. this._midtonesHue = value;
  82595. this._dirty = true;
  82596. },
  82597. enumerable: true,
  82598. configurable: true
  82599. });
  82600. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  82601. /**
  82602. * Gets the midtones Density value.
  82603. * 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.
  82604. * Values less than zero provide a filter of opposite hue.
  82605. */
  82606. get: function () {
  82607. return this._midtonesDensity;
  82608. },
  82609. /**
  82610. * Sets the midtones Density value.
  82611. * 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.
  82612. * Values less than zero provide a filter of opposite hue.
  82613. */
  82614. set: function (value) {
  82615. this._midtonesDensity = value;
  82616. this._dirty = true;
  82617. },
  82618. enumerable: true,
  82619. configurable: true
  82620. });
  82621. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  82622. /**
  82623. * Gets the midtones Saturation value.
  82624. * 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.
  82625. */
  82626. get: function () {
  82627. return this._midtonesSaturation;
  82628. },
  82629. /**
  82630. * Sets the midtones Saturation value.
  82631. * 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.
  82632. */
  82633. set: function (value) {
  82634. this._midtonesSaturation = value;
  82635. this._dirty = true;
  82636. },
  82637. enumerable: true,
  82638. configurable: true
  82639. });
  82640. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  82641. /**
  82642. * Gets the midtones Exposure value.
  82643. * 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.
  82644. */
  82645. get: function () {
  82646. return this._midtonesExposure;
  82647. },
  82648. /**
  82649. * Sets the midtones Exposure value.
  82650. * 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.
  82651. */
  82652. set: function (value) {
  82653. this._midtonesExposure = value;
  82654. this._dirty = true;
  82655. },
  82656. enumerable: true,
  82657. configurable: true
  82658. });
  82659. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  82660. /**
  82661. * Gets the shadows Hue value.
  82662. * 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).
  82663. */
  82664. get: function () {
  82665. return this._shadowsHue;
  82666. },
  82667. /**
  82668. * Sets the shadows Hue value.
  82669. * 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).
  82670. */
  82671. set: function (value) {
  82672. this._shadowsHue = value;
  82673. this._dirty = true;
  82674. },
  82675. enumerable: true,
  82676. configurable: true
  82677. });
  82678. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  82679. /**
  82680. * Gets the shadows Density value.
  82681. * 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.
  82682. * Values less than zero provide a filter of opposite hue.
  82683. */
  82684. get: function () {
  82685. return this._shadowsDensity;
  82686. },
  82687. /**
  82688. * Sets the shadows Density value.
  82689. * 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.
  82690. * Values less than zero provide a filter of opposite hue.
  82691. */
  82692. set: function (value) {
  82693. this._shadowsDensity = value;
  82694. this._dirty = true;
  82695. },
  82696. enumerable: true,
  82697. configurable: true
  82698. });
  82699. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  82700. /**
  82701. * Gets the shadows Saturation value.
  82702. * 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.
  82703. */
  82704. get: function () {
  82705. return this._shadowsSaturation;
  82706. },
  82707. /**
  82708. * Sets the shadows Saturation value.
  82709. * 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.
  82710. */
  82711. set: function (value) {
  82712. this._shadowsSaturation = value;
  82713. this._dirty = true;
  82714. },
  82715. enumerable: true,
  82716. configurable: true
  82717. });
  82718. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  82719. /**
  82720. * Gets the shadows Exposure value.
  82721. * 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.
  82722. */
  82723. get: function () {
  82724. return this._shadowsExposure;
  82725. },
  82726. /**
  82727. * Sets the shadows Exposure value.
  82728. * 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.
  82729. */
  82730. set: function (value) {
  82731. this._shadowsExposure = value;
  82732. this._dirty = true;
  82733. },
  82734. enumerable: true,
  82735. configurable: true
  82736. });
  82737. ColorCurves.prototype.getClassName = function () {
  82738. return "ColorCurves";
  82739. };
  82740. /**
  82741. * Binds the color curves to the shader.
  82742. * @param colorCurves The color curve to bind
  82743. * @param effect The effect to bind to
  82744. */
  82745. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  82746. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  82747. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  82748. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  82749. if (colorCurves._dirty) {
  82750. colorCurves._dirty = false;
  82751. // Fill in global info.
  82752. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  82753. // Compute highlights info.
  82754. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  82755. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  82756. // Compute midtones info.
  82757. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  82758. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  82759. // Compute shadows info.
  82760. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  82761. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  82762. // Compute deltas (neutral is midtones).
  82763. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  82764. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  82765. }
  82766. if (effect) {
  82767. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  82768. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  82769. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  82770. }
  82771. };
  82772. /**
  82773. * Prepare the list of uniforms associated with the ColorCurves effects.
  82774. * @param uniformsList The list of uniforms used in the effect
  82775. */
  82776. ColorCurves.PrepareUniforms = function (uniformsList) {
  82777. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  82778. };
  82779. /**
  82780. * Returns color grading data based on a hue, density, saturation and exposure value.
  82781. * @param filterHue The hue of the color filter.
  82782. * @param filterDensity The density of the color filter.
  82783. * @param saturation The saturation.
  82784. * @param exposure The exposure.
  82785. * @param result The result data container.
  82786. */
  82787. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  82788. if (hue == null) {
  82789. return;
  82790. }
  82791. hue = ColorCurves.clamp(hue, 0, 360);
  82792. density = ColorCurves.clamp(density, -100, 100);
  82793. saturation = ColorCurves.clamp(saturation, -100, 100);
  82794. exposure = ColorCurves.clamp(exposure, -100, 100);
  82795. // Remap the slider/config filter density with non-linear mapping and also scale by half
  82796. // so that the maximum filter density is only 50% control. This provides fine control
  82797. // for small values and reasonable range.
  82798. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  82799. density *= 0.5;
  82800. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  82801. if (density < 0) {
  82802. density *= -1;
  82803. hue = (hue + 180) % 360;
  82804. }
  82805. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  82806. result.scaleToRef(2, result);
  82807. result.a = 1 + 0.01 * saturation;
  82808. };
  82809. /**
  82810. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  82811. * @param value The input slider value in range [-100,100].
  82812. * @returns Adjusted value.
  82813. */
  82814. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  82815. value /= 100;
  82816. var x = Math.abs(value);
  82817. x = Math.pow(x, 2);
  82818. if (value < 0) {
  82819. x *= -1;
  82820. }
  82821. x *= 100;
  82822. return x;
  82823. };
  82824. /**
  82825. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  82826. * @param hue The hue (H) input.
  82827. * @param saturation The saturation (S) input.
  82828. * @param brightness The brightness (B) input.
  82829. * @result An RGBA color represented as Vector4.
  82830. */
  82831. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  82832. var h = ColorCurves.clamp(hue, 0, 360);
  82833. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  82834. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  82835. if (s === 0) {
  82836. result.r = v;
  82837. result.g = v;
  82838. result.b = v;
  82839. }
  82840. else {
  82841. // sector 0 to 5
  82842. h /= 60;
  82843. var i = Math.floor(h);
  82844. // fractional part of h
  82845. var f = h - i;
  82846. var p = v * (1 - s);
  82847. var q = v * (1 - s * f);
  82848. var t = v * (1 - s * (1 - f));
  82849. switch (i) {
  82850. case 0:
  82851. result.r = v;
  82852. result.g = t;
  82853. result.b = p;
  82854. break;
  82855. case 1:
  82856. result.r = q;
  82857. result.g = v;
  82858. result.b = p;
  82859. break;
  82860. case 2:
  82861. result.r = p;
  82862. result.g = v;
  82863. result.b = t;
  82864. break;
  82865. case 3:
  82866. result.r = p;
  82867. result.g = q;
  82868. result.b = v;
  82869. break;
  82870. case 4:
  82871. result.r = t;
  82872. result.g = p;
  82873. result.b = v;
  82874. break;
  82875. default: // case 5:
  82876. result.r = v;
  82877. result.g = p;
  82878. result.b = q;
  82879. break;
  82880. }
  82881. }
  82882. result.a = 1;
  82883. };
  82884. /**
  82885. * Returns a value clamped between min and max
  82886. * @param value The value to clamp
  82887. * @param min The minimum of value
  82888. * @param max The maximum of value
  82889. * @returns The clamped value.
  82890. */
  82891. ColorCurves.clamp = function (value, min, max) {
  82892. return Math.min(Math.max(value, min), max);
  82893. };
  82894. /**
  82895. * Clones the current color curve instance.
  82896. * @return The cloned curves
  82897. */
  82898. ColorCurves.prototype.clone = function () {
  82899. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  82900. };
  82901. /**
  82902. * Serializes the current color curve instance to a json representation.
  82903. * @return a JSON representation
  82904. */
  82905. ColorCurves.prototype.serialize = function () {
  82906. return BABYLON.SerializationHelper.Serialize(this);
  82907. };
  82908. /**
  82909. * Parses the color curve from a json representation.
  82910. * @param source the JSON source to parse
  82911. * @return The parsed curves
  82912. */
  82913. ColorCurves.Parse = function (source) {
  82914. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  82915. };
  82916. __decorate([
  82917. BABYLON.serialize()
  82918. ], ColorCurves.prototype, "_globalHue", void 0);
  82919. __decorate([
  82920. BABYLON.serialize()
  82921. ], ColorCurves.prototype, "_globalDensity", void 0);
  82922. __decorate([
  82923. BABYLON.serialize()
  82924. ], ColorCurves.prototype, "_globalSaturation", void 0);
  82925. __decorate([
  82926. BABYLON.serialize()
  82927. ], ColorCurves.prototype, "_globalExposure", void 0);
  82928. __decorate([
  82929. BABYLON.serialize()
  82930. ], ColorCurves.prototype, "_highlightsHue", void 0);
  82931. __decorate([
  82932. BABYLON.serialize()
  82933. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  82934. __decorate([
  82935. BABYLON.serialize()
  82936. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  82937. __decorate([
  82938. BABYLON.serialize()
  82939. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  82940. __decorate([
  82941. BABYLON.serialize()
  82942. ], ColorCurves.prototype, "_midtonesHue", void 0);
  82943. __decorate([
  82944. BABYLON.serialize()
  82945. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  82946. __decorate([
  82947. BABYLON.serialize()
  82948. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  82949. __decorate([
  82950. BABYLON.serialize()
  82951. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  82952. return ColorCurves;
  82953. }());
  82954. BABYLON.ColorCurves = ColorCurves;
  82955. })(BABYLON || (BABYLON = {}));
  82956. //# sourceMappingURL=babylon.colorCurves.js.map
  82957. var BABYLON;
  82958. (function (BABYLON) {
  82959. var RefractionPostProcess = /** @class */ (function (_super) {
  82960. __extends(RefractionPostProcess, _super);
  82961. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  82962. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  82963. _this.color = color;
  82964. _this.depth = depth;
  82965. _this.colorLevel = colorLevel;
  82966. _this._ownRefractionTexture = true;
  82967. _this.onActivateObservable.add(function (cam) {
  82968. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  82969. });
  82970. _this.onApplyObservable.add(function (effect) {
  82971. effect.setColor3("baseColor", _this.color);
  82972. effect.setFloat("depth", _this.depth);
  82973. effect.setFloat("colorLevel", _this.colorLevel);
  82974. effect.setTexture("refractionSampler", _this._refTexture);
  82975. });
  82976. return _this;
  82977. }
  82978. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  82979. /**
  82980. * Gets or sets the refraction texture
  82981. * Please note that you are responsible for disposing the texture if you set it manually
  82982. */
  82983. get: function () {
  82984. return this._refTexture;
  82985. },
  82986. set: function (value) {
  82987. if (this._refTexture && this._ownRefractionTexture) {
  82988. this._refTexture.dispose();
  82989. }
  82990. this._refTexture = value;
  82991. this._ownRefractionTexture = false;
  82992. },
  82993. enumerable: true,
  82994. configurable: true
  82995. });
  82996. // Methods
  82997. RefractionPostProcess.prototype.dispose = function (camera) {
  82998. if (this._refTexture && this._ownRefractionTexture) {
  82999. this._refTexture.dispose();
  83000. this._refTexture = null;
  83001. }
  83002. _super.prototype.dispose.call(this, camera);
  83003. };
  83004. return RefractionPostProcess;
  83005. }(BABYLON.PostProcess));
  83006. BABYLON.RefractionPostProcess = RefractionPostProcess;
  83007. })(BABYLON || (BABYLON = {}));
  83008. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  83009. var BABYLON;
  83010. (function (BABYLON) {
  83011. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  83012. __extends(BlackAndWhitePostProcess, _super);
  83013. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  83014. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  83015. _this.degree = 1;
  83016. _this.onApplyObservable.add(function (effect) {
  83017. effect.setFloat("degree", _this.degree);
  83018. });
  83019. return _this;
  83020. }
  83021. return BlackAndWhitePostProcess;
  83022. }(BABYLON.PostProcess));
  83023. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  83024. })(BABYLON || (BABYLON = {}));
  83025. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  83026. var BABYLON;
  83027. (function (BABYLON) {
  83028. /**
  83029. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  83030. * input texture to perform effects such as edge detection or sharpening
  83031. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83032. */
  83033. var ConvolutionPostProcess = /** @class */ (function (_super) {
  83034. __extends(ConvolutionPostProcess, _super);
  83035. /**
  83036. * Creates a new instance ConvolutionPostProcess
  83037. * @param name The name of the effect.
  83038. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  83039. * @param options The required width/height ratio to downsize to before computing the render pass.
  83040. * @param camera The camera to apply the render pass to.
  83041. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83042. * @param engine The engine which the post process will be applied. (default: current engine)
  83043. * @param reusable If the post process can be reused on the same frame. (default: false)
  83044. * @param textureType Type of textures used when performing the post process. (default: 0)
  83045. */
  83046. function ConvolutionPostProcess(name,
  83047. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  83048. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  83049. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83050. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83051. _this.kernel = kernel;
  83052. _this.onApply = function (effect) {
  83053. effect.setFloat2("screenSize", _this.width, _this.height);
  83054. effect.setArray("kernel", _this.kernel);
  83055. };
  83056. return _this;
  83057. }
  83058. // Statics
  83059. /**
  83060. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83061. */
  83062. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  83063. /**
  83064. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83065. */
  83066. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  83067. /**
  83068. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83069. */
  83070. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  83071. /**
  83072. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83073. */
  83074. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  83075. /**
  83076. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83077. */
  83078. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  83079. /**
  83080. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83081. */
  83082. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  83083. return ConvolutionPostProcess;
  83084. }(BABYLON.PostProcess));
  83085. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  83086. })(BABYLON || (BABYLON = {}));
  83087. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  83088. var BABYLON;
  83089. (function (BABYLON) {
  83090. var FilterPostProcess = /** @class */ (function (_super) {
  83091. __extends(FilterPostProcess, _super);
  83092. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  83093. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  83094. _this.kernelMatrix = kernelMatrix;
  83095. _this.onApply = function (effect) {
  83096. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  83097. };
  83098. return _this;
  83099. }
  83100. return FilterPostProcess;
  83101. }(BABYLON.PostProcess));
  83102. BABYLON.FilterPostProcess = FilterPostProcess;
  83103. })(BABYLON || (BABYLON = {}));
  83104. //# sourceMappingURL=babylon.filterPostProcess.js.map
  83105. var BABYLON;
  83106. (function (BABYLON) {
  83107. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  83108. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  83109. __extends(VolumetricLightScatteringPostProcess, _super);
  83110. /**
  83111. * @constructor
  83112. * @param {string} name - The post-process name
  83113. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  83114. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  83115. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  83116. * @param {number} samples - The post-process quality, default 100
  83117. * @param {number} samplingMode - The post-process filtering mode
  83118. * @param {BABYLON.Engine} engine - The babylon engine
  83119. * @param {boolean} reusable - If the post-process is reusable
  83120. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  83121. */
  83122. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  83123. if (samples === void 0) { samples = 100; }
  83124. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83125. 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;
  83126. _this._screenCoordinates = BABYLON.Vector2.Zero();
  83127. /**
  83128. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  83129. */
  83130. _this.customMeshPosition = BABYLON.Vector3.Zero();
  83131. /**
  83132. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  83133. */
  83134. _this.useCustomMeshPosition = false;
  83135. /**
  83136. * If the post-process should inverse the light scattering direction
  83137. */
  83138. _this.invert = true;
  83139. /**
  83140. * Array containing the excluded meshes not rendered in the internal pass
  83141. */
  83142. _this.excludedMeshes = new Array();
  83143. /**
  83144. * Controls the overall intensity of the post-process
  83145. */
  83146. _this.exposure = 0.3;
  83147. /**
  83148. * Dissipates each sample's contribution in range [0, 1]
  83149. */
  83150. _this.decay = 0.96815;
  83151. /**
  83152. * Controls the overall intensity of each sample
  83153. */
  83154. _this.weight = 0.58767;
  83155. /**
  83156. * Controls the density of each sample
  83157. */
  83158. _this.density = 0.926;
  83159. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  83160. engine = scene.getEngine();
  83161. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  83162. // Configure mesh
  83163. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  83164. // Configure
  83165. _this._createPass(scene, ratio.passRatio || ratio);
  83166. _this.onActivate = function (camera) {
  83167. if (!_this.isSupported) {
  83168. _this.dispose(camera);
  83169. }
  83170. _this.onActivate = null;
  83171. };
  83172. _this.onApplyObservable.add(function (effect) {
  83173. _this._updateMeshScreenCoordinates(scene);
  83174. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  83175. effect.setFloat("exposure", _this.exposure);
  83176. effect.setFloat("decay", _this.decay);
  83177. effect.setFloat("weight", _this.weight);
  83178. effect.setFloat("density", _this.density);
  83179. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  83180. });
  83181. return _this;
  83182. }
  83183. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  83184. get: function () {
  83185. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83186. return false;
  83187. },
  83188. set: function (useDiffuseColor) {
  83189. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83190. },
  83191. enumerable: true,
  83192. configurable: true
  83193. });
  83194. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  83195. return "VolumetricLightScatteringPostProcess";
  83196. };
  83197. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  83198. var mesh = subMesh.getMesh();
  83199. // Render this.mesh as default
  83200. if (mesh === this.mesh && mesh.material) {
  83201. return mesh.material.isReady(mesh);
  83202. }
  83203. var defines = [];
  83204. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83205. var material = subMesh.getMaterial();
  83206. // Alpha test
  83207. if (material) {
  83208. if (material.needAlphaTesting()) {
  83209. defines.push("#define ALPHATEST");
  83210. }
  83211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83212. attribs.push(BABYLON.VertexBuffer.UVKind);
  83213. defines.push("#define UV1");
  83214. }
  83215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83216. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83217. defines.push("#define UV2");
  83218. }
  83219. }
  83220. // Bones
  83221. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83222. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83223. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83224. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83225. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83226. }
  83227. else {
  83228. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83229. }
  83230. // Instances
  83231. if (useInstances) {
  83232. defines.push("#define INSTANCES");
  83233. attribs.push("world0");
  83234. attribs.push("world1");
  83235. attribs.push("world2");
  83236. attribs.push("world3");
  83237. }
  83238. // Get correct effect
  83239. var join = defines.join("\n");
  83240. if (this._cachedDefines !== join) {
  83241. this._cachedDefines = join;
  83242. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  83243. }
  83244. return this._volumetricLightScatteringPass.isReady();
  83245. };
  83246. /**
  83247. * Sets the new light position for light scattering effect
  83248. * @param {BABYLON.Vector3} The new custom light position
  83249. */
  83250. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  83251. this.customMeshPosition = position;
  83252. };
  83253. /**
  83254. * Returns the light position for light scattering effect
  83255. * @return {BABYLON.Vector3} The custom light position
  83256. */
  83257. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  83258. return this.customMeshPosition;
  83259. };
  83260. /**
  83261. * Disposes the internal assets and detaches the post-process from the camera
  83262. */
  83263. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  83264. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  83265. if (rttIndex !== -1) {
  83266. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  83267. }
  83268. this._volumetricLightScatteringRTT.dispose();
  83269. _super.prototype.dispose.call(this, camera);
  83270. };
  83271. /**
  83272. * Returns the render target texture used by the post-process
  83273. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  83274. */
  83275. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  83276. return this._volumetricLightScatteringRTT;
  83277. };
  83278. // Private methods
  83279. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  83280. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  83281. return true;
  83282. }
  83283. return false;
  83284. };
  83285. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  83286. var _this = this;
  83287. var engine = scene.getEngine();
  83288. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83289. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83290. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83291. this._volumetricLightScatteringRTT.renderList = null;
  83292. this._volumetricLightScatteringRTT.renderParticles = false;
  83293. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  83294. var camera = this.getCamera();
  83295. if (camera) {
  83296. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83297. }
  83298. else {
  83299. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83300. }
  83301. // Custom render function for submeshes
  83302. var renderSubMesh = function (subMesh) {
  83303. var mesh = subMesh.getRenderingMesh();
  83304. if (_this._meshExcluded(mesh)) {
  83305. return;
  83306. }
  83307. var material = subMesh.getMaterial();
  83308. if (!material) {
  83309. return;
  83310. }
  83311. var scene = mesh.getScene();
  83312. var engine = scene.getEngine();
  83313. // Culling
  83314. engine.setState(material.backFaceCulling);
  83315. // Managing instances
  83316. var batch = mesh._getInstancesRenderList(subMesh._id);
  83317. if (batch.mustReturn) {
  83318. return;
  83319. }
  83320. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83321. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  83322. var effect = _this._volumetricLightScatteringPass;
  83323. if (mesh === _this.mesh) {
  83324. if (subMesh.effect) {
  83325. effect = subMesh.effect;
  83326. }
  83327. else {
  83328. effect = material.getEffect();
  83329. }
  83330. }
  83331. engine.enableEffect(effect);
  83332. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  83333. if (mesh === _this.mesh) {
  83334. material.bind(mesh.getWorldMatrix(), mesh);
  83335. }
  83336. else {
  83337. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  83338. // Alpha test
  83339. if (material && material.needAlphaTesting()) {
  83340. var alphaTexture = material.getAlphaTestTexture();
  83341. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  83342. if (alphaTexture) {
  83343. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83344. }
  83345. }
  83346. // Bones
  83347. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83348. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83349. }
  83350. }
  83351. // Draw
  83352. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  83353. }
  83354. };
  83355. // Render target texture callbacks
  83356. var savedSceneClearColor;
  83357. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  83358. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  83359. savedSceneClearColor = scene.clearColor;
  83360. scene.clearColor = sceneClearColor;
  83361. });
  83362. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  83363. scene.clearColor = savedSceneClearColor;
  83364. });
  83365. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83366. var engine = scene.getEngine();
  83367. var index;
  83368. if (depthOnlySubMeshes.length) {
  83369. engine.setColorWrite(false);
  83370. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83371. renderSubMesh(depthOnlySubMeshes.data[index]);
  83372. }
  83373. engine.setColorWrite(true);
  83374. }
  83375. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83376. renderSubMesh(opaqueSubMeshes.data[index]);
  83377. }
  83378. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83379. renderSubMesh(alphaTestSubMeshes.data[index]);
  83380. }
  83381. if (transparentSubMeshes.length) {
  83382. // Sort sub meshes
  83383. for (index = 0; index < transparentSubMeshes.length; index++) {
  83384. var submesh = transparentSubMeshes.data[index];
  83385. var boundingInfo = submesh.getBoundingInfo();
  83386. if (boundingInfo && scene.activeCamera) {
  83387. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  83388. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  83389. }
  83390. }
  83391. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  83392. sortedArray.sort(function (a, b) {
  83393. // Alpha index first
  83394. if (a._alphaIndex > b._alphaIndex) {
  83395. return 1;
  83396. }
  83397. if (a._alphaIndex < b._alphaIndex) {
  83398. return -1;
  83399. }
  83400. // Then distance to camera
  83401. if (a._distanceToCamera < b._distanceToCamera) {
  83402. return 1;
  83403. }
  83404. if (a._distanceToCamera > b._distanceToCamera) {
  83405. return -1;
  83406. }
  83407. return 0;
  83408. });
  83409. // Render sub meshes
  83410. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  83411. for (index = 0; index < sortedArray.length; index++) {
  83412. renderSubMesh(sortedArray[index]);
  83413. }
  83414. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83415. }
  83416. };
  83417. };
  83418. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  83419. var transform = scene.getTransformMatrix();
  83420. var meshPosition;
  83421. if (this.useCustomMeshPosition) {
  83422. meshPosition = this.customMeshPosition;
  83423. }
  83424. else if (this.attachedNode) {
  83425. meshPosition = this.attachedNode.position;
  83426. }
  83427. else {
  83428. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  83429. }
  83430. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  83431. this._screenCoordinates.x = pos.x / this._viewPort.width;
  83432. this._screenCoordinates.y = pos.y / this._viewPort.height;
  83433. if (this.invert)
  83434. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  83435. };
  83436. // Static methods
  83437. /**
  83438. * Creates a default mesh for the Volumeric Light Scattering post-process
  83439. * @param {string} The mesh name
  83440. * @param {BABYLON.Scene} The scene where to create the mesh
  83441. * @return {BABYLON.Mesh} the default mesh
  83442. */
  83443. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  83444. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  83445. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  83446. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  83447. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  83448. mesh.material = material;
  83449. return mesh;
  83450. };
  83451. __decorate([
  83452. BABYLON.serializeAsVector3()
  83453. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  83454. __decorate([
  83455. BABYLON.serialize()
  83456. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  83457. __decorate([
  83458. BABYLON.serialize()
  83459. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  83460. __decorate([
  83461. BABYLON.serializeAsMeshReference()
  83462. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  83463. __decorate([
  83464. BABYLON.serialize()
  83465. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  83466. __decorate([
  83467. BABYLON.serialize()
  83468. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  83469. __decorate([
  83470. BABYLON.serialize()
  83471. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  83472. __decorate([
  83473. BABYLON.serialize()
  83474. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  83475. __decorate([
  83476. BABYLON.serialize()
  83477. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  83478. return VolumetricLightScatteringPostProcess;
  83479. }(BABYLON.PostProcess));
  83480. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  83481. })(BABYLON || (BABYLON = {}));
  83482. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  83483. //
  83484. // This post-process allows the modification of rendered colors by using
  83485. // a 'look-up table' (LUT). This effect is also called Color Grading.
  83486. //
  83487. // The object needs to be provided an url to a texture containing the color
  83488. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  83489. // Use an image editing software to tweak the LUT to match your needs.
  83490. //
  83491. // For an example of a color LUT, see here:
  83492. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  83493. // For explanations on color grading, see here:
  83494. // http://udn.epicgames.com/Three/ColorGrading.html
  83495. //
  83496. var BABYLON;
  83497. (function (BABYLON) {
  83498. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  83499. __extends(ColorCorrectionPostProcess, _super);
  83500. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  83501. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  83502. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83503. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  83504. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83505. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83506. _this.onApply = function (effect) {
  83507. effect.setTexture("colorTable", _this._colorTableTexture);
  83508. };
  83509. return _this;
  83510. }
  83511. return ColorCorrectionPostProcess;
  83512. }(BABYLON.PostProcess));
  83513. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  83514. })(BABYLON || (BABYLON = {}));
  83515. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  83516. var BABYLON;
  83517. (function (BABYLON) {
  83518. /** Defines operator used for tonemapping */
  83519. var TonemappingOperator;
  83520. (function (TonemappingOperator) {
  83521. /** Hable */
  83522. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  83523. /** Reinhard */
  83524. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  83525. /** HejiDawson */
  83526. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  83527. /** Photographic */
  83528. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  83529. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  83530. ;
  83531. /**
  83532. * Defines a post process to apply tone mapping
  83533. */
  83534. var TonemapPostProcess = /** @class */ (function (_super) {
  83535. __extends(TonemapPostProcess, _super);
  83536. /**
  83537. * Creates a new TonemapPostProcess
  83538. * @param name defines the name of the postprocess
  83539. * @param _operator defines the operator to use
  83540. * @param exposureAdjustment defines the required exposure adjustement
  83541. * @param camera defines the camera to use (can be null)
  83542. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  83543. * @param engine defines the hosting engine (can be ignore if camera is set)
  83544. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  83545. */
  83546. function TonemapPostProcess(name, _operator,
  83547. /** Defines the required exposure adjustement */
  83548. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  83549. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83550. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83551. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  83552. _this._operator = _operator;
  83553. _this.exposureAdjustment = exposureAdjustment;
  83554. var defines = "#define ";
  83555. if (_this._operator === TonemappingOperator.Hable)
  83556. defines += "HABLE_TONEMAPPING";
  83557. else if (_this._operator === TonemappingOperator.Reinhard)
  83558. defines += "REINHARD_TONEMAPPING";
  83559. else if (_this._operator === TonemappingOperator.HejiDawson)
  83560. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  83561. else if (_this._operator === TonemappingOperator.Photographic)
  83562. defines += "PHOTOGRAPHIC_TONEMAPPING";
  83563. //sadly a second call to create the effect.
  83564. _this.updateEffect(defines);
  83565. _this.onApply = function (effect) {
  83566. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  83567. };
  83568. return _this;
  83569. }
  83570. return TonemapPostProcess;
  83571. }(BABYLON.PostProcess));
  83572. BABYLON.TonemapPostProcess = TonemapPostProcess;
  83573. })(BABYLON || (BABYLON = {}));
  83574. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  83575. var BABYLON;
  83576. (function (BABYLON) {
  83577. var DisplayPassPostProcess = /** @class */ (function (_super) {
  83578. __extends(DisplayPassPostProcess, _super);
  83579. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  83580. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  83581. }
  83582. return DisplayPassPostProcess;
  83583. }(BABYLON.PostProcess));
  83584. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  83585. })(BABYLON || (BABYLON = {}));
  83586. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  83587. var BABYLON;
  83588. (function (BABYLON) {
  83589. var HighlightsPostProcess = /** @class */ (function (_super) {
  83590. __extends(HighlightsPostProcess, _super);
  83591. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83592. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83593. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83594. }
  83595. return HighlightsPostProcess;
  83596. }(BABYLON.PostProcess));
  83597. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  83598. })(BABYLON || (BABYLON = {}));
  83599. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  83600. var BABYLON;
  83601. (function (BABYLON) {
  83602. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  83603. __extends(ImageProcessingPostProcess, _super);
  83604. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  83605. if (camera === void 0) { camera = null; }
  83606. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83607. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  83608. _this._fromLinearSpace = true;
  83609. /**
  83610. * Defines cache preventing GC.
  83611. */
  83612. _this._defines = {
  83613. IMAGEPROCESSING: false,
  83614. VIGNETTE: false,
  83615. VIGNETTEBLENDMODEMULTIPLY: false,
  83616. VIGNETTEBLENDMODEOPAQUE: false,
  83617. TONEMAPPING: false,
  83618. TONEMAPPING_ACES: false,
  83619. CONTRAST: false,
  83620. COLORCURVES: false,
  83621. COLORGRADING: false,
  83622. COLORGRADING3D: false,
  83623. FROMLINEARSPACE: false,
  83624. SAMPLER3DGREENDEPTH: false,
  83625. SAMPLER3DBGRMAP: false,
  83626. IMAGEPROCESSINGPOSTPROCESS: false,
  83627. EXPOSURE: false,
  83628. };
  83629. // Setup the configuration as forced by the constructor. This would then not force the
  83630. // scene materials output in linear space and let untouched the default forward pass.
  83631. if (imageProcessingConfiguration) {
  83632. imageProcessingConfiguration.applyByPostProcess = true;
  83633. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  83634. // This will cause the shader to be compiled
  83635. _this.fromLinearSpace = false;
  83636. }
  83637. // Setup the default processing configuration to the scene.
  83638. else {
  83639. _this._attachImageProcessingConfiguration(null, true);
  83640. _this.imageProcessingConfiguration.applyByPostProcess = true;
  83641. }
  83642. _this.onApply = function (effect) {
  83643. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  83644. };
  83645. return _this;
  83646. }
  83647. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  83648. /**
  83649. * Gets the image processing configuration used either in this material.
  83650. */
  83651. get: function () {
  83652. return this._imageProcessingConfiguration;
  83653. },
  83654. /**
  83655. * Sets the Default image processing configuration used either in the this material.
  83656. *
  83657. * If sets to null, the scene one is in use.
  83658. */
  83659. set: function (value) {
  83660. this._attachImageProcessingConfiguration(value);
  83661. },
  83662. enumerable: true,
  83663. configurable: true
  83664. });
  83665. /**
  83666. * Attaches a new image processing configuration to the PBR Material.
  83667. * @param configuration
  83668. */
  83669. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  83670. var _this = this;
  83671. if (doNotBuild === void 0) { doNotBuild = false; }
  83672. if (configuration === this._imageProcessingConfiguration) {
  83673. return;
  83674. }
  83675. // Detaches observer.
  83676. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83677. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83678. }
  83679. // Pick the scene configuration if needed.
  83680. if (!configuration) {
  83681. var scene = null;
  83682. var engine = this.getEngine();
  83683. var camera = this.getCamera();
  83684. if (camera) {
  83685. scene = camera.getScene();
  83686. }
  83687. else if (engine && engine.scenes) {
  83688. var scenes = engine.scenes;
  83689. scene = scenes[scenes.length - 1];
  83690. }
  83691. else {
  83692. scene = BABYLON.Engine.LastCreatedScene;
  83693. }
  83694. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  83695. }
  83696. else {
  83697. this._imageProcessingConfiguration = configuration;
  83698. }
  83699. // Attaches observer.
  83700. if (this._imageProcessingConfiguration) {
  83701. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83702. _this._updateParameters();
  83703. });
  83704. }
  83705. // Ensure the effect will be rebuilt.
  83706. if (!doNotBuild) {
  83707. this._updateParameters();
  83708. }
  83709. };
  83710. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  83711. /**
  83712. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83713. */
  83714. get: function () {
  83715. return this.imageProcessingConfiguration.colorCurves;
  83716. },
  83717. /**
  83718. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83719. */
  83720. set: function (value) {
  83721. this.imageProcessingConfiguration.colorCurves = value;
  83722. },
  83723. enumerable: true,
  83724. configurable: true
  83725. });
  83726. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  83727. /**
  83728. * Gets wether the color curves effect is enabled.
  83729. */
  83730. get: function () {
  83731. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83732. },
  83733. /**
  83734. * Sets wether the color curves effect is enabled.
  83735. */
  83736. set: function (value) {
  83737. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83738. },
  83739. enumerable: true,
  83740. configurable: true
  83741. });
  83742. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  83743. /**
  83744. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83745. */
  83746. get: function () {
  83747. return this.imageProcessingConfiguration.colorGradingTexture;
  83748. },
  83749. /**
  83750. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83751. */
  83752. set: function (value) {
  83753. this.imageProcessingConfiguration.colorGradingTexture = value;
  83754. },
  83755. enumerable: true,
  83756. configurable: true
  83757. });
  83758. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  83759. /**
  83760. * Gets wether the color grading effect is enabled.
  83761. */
  83762. get: function () {
  83763. return this.imageProcessingConfiguration.colorGradingEnabled;
  83764. },
  83765. /**
  83766. * Gets wether the color grading effect is enabled.
  83767. */
  83768. set: function (value) {
  83769. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83770. },
  83771. enumerable: true,
  83772. configurable: true
  83773. });
  83774. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  83775. /**
  83776. * Gets exposure used in the effect.
  83777. */
  83778. get: function () {
  83779. return this.imageProcessingConfiguration.exposure;
  83780. },
  83781. /**
  83782. * Sets exposure used in the effect.
  83783. */
  83784. set: function (value) {
  83785. this.imageProcessingConfiguration.exposure = value;
  83786. },
  83787. enumerable: true,
  83788. configurable: true
  83789. });
  83790. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  83791. /**
  83792. * Gets wether tonemapping is enabled or not.
  83793. */
  83794. get: function () {
  83795. return this._imageProcessingConfiguration.toneMappingEnabled;
  83796. },
  83797. /**
  83798. * Sets wether tonemapping is enabled or not
  83799. */
  83800. set: function (value) {
  83801. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83802. },
  83803. enumerable: true,
  83804. configurable: true
  83805. });
  83806. ;
  83807. ;
  83808. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  83809. /**
  83810. * Gets contrast used in the effect.
  83811. */
  83812. get: function () {
  83813. return this.imageProcessingConfiguration.contrast;
  83814. },
  83815. /**
  83816. * Sets contrast used in the effect.
  83817. */
  83818. set: function (value) {
  83819. this.imageProcessingConfiguration.contrast = value;
  83820. },
  83821. enumerable: true,
  83822. configurable: true
  83823. });
  83824. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  83825. /**
  83826. * Gets Vignette stretch size.
  83827. */
  83828. get: function () {
  83829. return this.imageProcessingConfiguration.vignetteStretch;
  83830. },
  83831. /**
  83832. * Sets Vignette stretch size.
  83833. */
  83834. set: function (value) {
  83835. this.imageProcessingConfiguration.vignetteStretch = value;
  83836. },
  83837. enumerable: true,
  83838. configurable: true
  83839. });
  83840. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  83841. /**
  83842. * Gets Vignette centre X Offset.
  83843. */
  83844. get: function () {
  83845. return this.imageProcessingConfiguration.vignetteCentreX;
  83846. },
  83847. /**
  83848. * Sets Vignette centre X Offset.
  83849. */
  83850. set: function (value) {
  83851. this.imageProcessingConfiguration.vignetteCentreX = value;
  83852. },
  83853. enumerable: true,
  83854. configurable: true
  83855. });
  83856. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  83857. /**
  83858. * Gets Vignette centre Y Offset.
  83859. */
  83860. get: function () {
  83861. return this.imageProcessingConfiguration.vignetteCentreY;
  83862. },
  83863. /**
  83864. * Sets Vignette centre Y Offset.
  83865. */
  83866. set: function (value) {
  83867. this.imageProcessingConfiguration.vignetteCentreY = value;
  83868. },
  83869. enumerable: true,
  83870. configurable: true
  83871. });
  83872. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  83873. /**
  83874. * Gets Vignette weight or intensity of the vignette effect.
  83875. */
  83876. get: function () {
  83877. return this.imageProcessingConfiguration.vignetteWeight;
  83878. },
  83879. /**
  83880. * Sets Vignette weight or intensity of the vignette effect.
  83881. */
  83882. set: function (value) {
  83883. this.imageProcessingConfiguration.vignetteWeight = value;
  83884. },
  83885. enumerable: true,
  83886. configurable: true
  83887. });
  83888. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  83889. /**
  83890. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83891. * if vignetteEnabled is set to true.
  83892. */
  83893. get: function () {
  83894. return this.imageProcessingConfiguration.vignetteColor;
  83895. },
  83896. /**
  83897. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83898. * if vignetteEnabled is set to true.
  83899. */
  83900. set: function (value) {
  83901. this.imageProcessingConfiguration.vignetteColor = value;
  83902. },
  83903. enumerable: true,
  83904. configurable: true
  83905. });
  83906. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  83907. /**
  83908. * Gets Camera field of view used by the Vignette effect.
  83909. */
  83910. get: function () {
  83911. return this.imageProcessingConfiguration.vignetteCameraFov;
  83912. },
  83913. /**
  83914. * Sets Camera field of view used by the Vignette effect.
  83915. */
  83916. set: function (value) {
  83917. this.imageProcessingConfiguration.vignetteCameraFov = value;
  83918. },
  83919. enumerable: true,
  83920. configurable: true
  83921. });
  83922. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  83923. /**
  83924. * Gets the vignette blend mode allowing different kind of effect.
  83925. */
  83926. get: function () {
  83927. return this.imageProcessingConfiguration.vignetteBlendMode;
  83928. },
  83929. /**
  83930. * Sets the vignette blend mode allowing different kind of effect.
  83931. */
  83932. set: function (value) {
  83933. this.imageProcessingConfiguration.vignetteBlendMode = value;
  83934. },
  83935. enumerable: true,
  83936. configurable: true
  83937. });
  83938. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  83939. /**
  83940. * Gets wether the vignette effect is enabled.
  83941. */
  83942. get: function () {
  83943. return this.imageProcessingConfiguration.vignetteEnabled;
  83944. },
  83945. /**
  83946. * Sets wether the vignette effect is enabled.
  83947. */
  83948. set: function (value) {
  83949. this.imageProcessingConfiguration.vignetteEnabled = value;
  83950. },
  83951. enumerable: true,
  83952. configurable: true
  83953. });
  83954. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  83955. /**
  83956. * Gets wether the input of the processing is in Gamma or Linear Space.
  83957. */
  83958. get: function () {
  83959. return this._fromLinearSpace;
  83960. },
  83961. /**
  83962. * Sets wether the input of the processing is in Gamma or Linear Space.
  83963. */
  83964. set: function (value) {
  83965. if (this._fromLinearSpace === value) {
  83966. return;
  83967. }
  83968. this._fromLinearSpace = value;
  83969. this._updateParameters();
  83970. },
  83971. enumerable: true,
  83972. configurable: true
  83973. });
  83974. ImageProcessingPostProcess.prototype.getClassName = function () {
  83975. return "ImageProcessingPostProcess";
  83976. };
  83977. ImageProcessingPostProcess.prototype._updateParameters = function () {
  83978. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  83979. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  83980. var defines = "";
  83981. for (var define in this._defines) {
  83982. if (this._defines[define]) {
  83983. defines += "#define " + define + ";\r\n";
  83984. }
  83985. }
  83986. var samplers = ["textureSampler"];
  83987. var uniforms = ["scale"];
  83988. if (BABYLON.ImageProcessingConfiguration) {
  83989. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  83990. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  83991. }
  83992. this.updateEffect(defines, uniforms, samplers);
  83993. };
  83994. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  83995. _super.prototype.dispose.call(this, camera);
  83996. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83997. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83998. }
  83999. if (this._imageProcessingConfiguration) {
  84000. this.imageProcessingConfiguration.applyByPostProcess = false;
  84001. }
  84002. };
  84003. __decorate([
  84004. BABYLON.serialize()
  84005. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  84006. return ImageProcessingPostProcess;
  84007. }(BABYLON.PostProcess));
  84008. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  84009. })(BABYLON || (BABYLON = {}));
  84010. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  84011. var BABYLON;
  84012. (function (BABYLON) {
  84013. /**
  84014. * Class used to store bone information
  84015. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84016. */
  84017. var Bone = /** @class */ (function (_super) {
  84018. __extends(Bone, _super);
  84019. /**
  84020. * Create a new bone
  84021. * @param name defines the bone name
  84022. * @param skeleton defines the parent skeleton
  84023. * @param parentBone defines the parent (can be null if the bone is the root)
  84024. * @param localMatrix defines the local matrix
  84025. * @param restPose defines the rest pose matrix
  84026. * @param baseMatrix defines the base matrix
  84027. * @param index defines index of the bone in the hiearchy
  84028. */
  84029. function Bone(
  84030. /**
  84031. * defines the bone name
  84032. */
  84033. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  84034. if (parentBone === void 0) { parentBone = null; }
  84035. if (localMatrix === void 0) { localMatrix = null; }
  84036. if (restPose === void 0) { restPose = null; }
  84037. if (baseMatrix === void 0) { baseMatrix = null; }
  84038. if (index === void 0) { index = null; }
  84039. var _this = _super.call(this, name, skeleton.getScene()) || this;
  84040. _this.name = name;
  84041. /**
  84042. * Gets the list of child bones
  84043. */
  84044. _this.children = new Array();
  84045. /** Gets the animations associated with this bone */
  84046. _this.animations = new Array();
  84047. /**
  84048. * @hidden Internal only
  84049. * Set this value to map this bone to a different index in the transform matrices
  84050. * Set this value to -1 to exclude the bone from the transform matrices
  84051. */
  84052. _this._index = null;
  84053. _this._absoluteTransform = new BABYLON.Matrix();
  84054. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  84055. _this._scalingDeterminant = 1;
  84056. _this._worldTransform = new BABYLON.Matrix();
  84057. _this._needToDecompose = true;
  84058. _this._needToCompose = false;
  84059. _this._skeleton = skeleton;
  84060. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  84061. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  84062. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  84063. _this._index = index;
  84064. skeleton.bones.push(_this);
  84065. _this.setParent(parentBone, false);
  84066. if (baseMatrix || localMatrix) {
  84067. _this._updateDifferenceMatrix();
  84068. }
  84069. return _this;
  84070. }
  84071. Object.defineProperty(Bone.prototype, "_matrix", {
  84072. /** @hidden */
  84073. get: function () {
  84074. this._compose();
  84075. return this._localMatrix;
  84076. },
  84077. /** @hidden */
  84078. set: function (value) {
  84079. this._localMatrix.copyFrom(value);
  84080. this._needToDecompose = true;
  84081. },
  84082. enumerable: true,
  84083. configurable: true
  84084. });
  84085. // Members
  84086. /**
  84087. * Gets the parent skeleton
  84088. * @returns a skeleton
  84089. */
  84090. Bone.prototype.getSkeleton = function () {
  84091. return this._skeleton;
  84092. };
  84093. /**
  84094. * Gets parent bone
  84095. * @returns a bone or null if the bone is the root of the bone hierarchy
  84096. */
  84097. Bone.prototype.getParent = function () {
  84098. return this._parent;
  84099. };
  84100. /**
  84101. * Sets the parent bone
  84102. * @param parent defines the parent (can be null if the bone is the root)
  84103. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84104. */
  84105. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  84106. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84107. if (this._parent === parent) {
  84108. return;
  84109. }
  84110. if (this._parent) {
  84111. var index = this._parent.children.indexOf(this);
  84112. if (index !== -1) {
  84113. this._parent.children.splice(index, 1);
  84114. }
  84115. }
  84116. this._parent = parent;
  84117. if (this._parent) {
  84118. this._parent.children.push(this);
  84119. }
  84120. if (updateDifferenceMatrix) {
  84121. this._updateDifferenceMatrix();
  84122. }
  84123. this.markAsDirty();
  84124. };
  84125. /**
  84126. * Gets the local matrix
  84127. * @returns a matrix
  84128. */
  84129. Bone.prototype.getLocalMatrix = function () {
  84130. this._compose();
  84131. return this._localMatrix;
  84132. };
  84133. /**
  84134. * Gets the base matrix (initial matrix which remains unchanged)
  84135. * @returns a matrix
  84136. */
  84137. Bone.prototype.getBaseMatrix = function () {
  84138. return this._baseMatrix;
  84139. };
  84140. /**
  84141. * Gets the rest pose matrix
  84142. * @returns a matrix
  84143. */
  84144. Bone.prototype.getRestPose = function () {
  84145. return this._restPose;
  84146. };
  84147. /**
  84148. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  84149. */
  84150. Bone.prototype.getWorldMatrix = function () {
  84151. return this._worldTransform;
  84152. };
  84153. /**
  84154. * Sets the local matrix to rest pose matrix
  84155. */
  84156. Bone.prototype.returnToRest = function () {
  84157. this.updateMatrix(this._restPose.clone());
  84158. };
  84159. /**
  84160. * Gets the inverse of the absolute transform matrix.
  84161. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  84162. * @returns a matrix
  84163. */
  84164. Bone.prototype.getInvertedAbsoluteTransform = function () {
  84165. return this._invertedAbsoluteTransform;
  84166. };
  84167. /**
  84168. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  84169. * @returns a matrix
  84170. */
  84171. Bone.prototype.getAbsoluteTransform = function () {
  84172. return this._absoluteTransform;
  84173. };
  84174. Object.defineProperty(Bone.prototype, "position", {
  84175. // Properties (matches AbstractMesh properties)
  84176. /** Gets or sets current position (in local space) */
  84177. get: function () {
  84178. this._decompose();
  84179. return this._localPosition;
  84180. },
  84181. set: function (newPosition) {
  84182. this._decompose();
  84183. this._localPosition.copyFrom(newPosition);
  84184. this._markAsDirtyAndCompose();
  84185. },
  84186. enumerable: true,
  84187. configurable: true
  84188. });
  84189. Object.defineProperty(Bone.prototype, "rotation", {
  84190. /** Gets or sets current rotation (in local space) */
  84191. get: function () {
  84192. return this.getRotation();
  84193. },
  84194. set: function (newRotation) {
  84195. this.setRotation(newRotation);
  84196. },
  84197. enumerable: true,
  84198. configurable: true
  84199. });
  84200. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  84201. /** Gets or sets current rotation quaternion (in local space) */
  84202. get: function () {
  84203. this._decompose();
  84204. return this._localRotation;
  84205. },
  84206. set: function (newRotation) {
  84207. this.setRotationQuaternion(newRotation);
  84208. },
  84209. enumerable: true,
  84210. configurable: true
  84211. });
  84212. Object.defineProperty(Bone.prototype, "scaling", {
  84213. /** Gets or sets current scaling (in local space) */
  84214. get: function () {
  84215. return this.getScale();
  84216. },
  84217. set: function (newScaling) {
  84218. this.setScale(newScaling);
  84219. },
  84220. enumerable: true,
  84221. configurable: true
  84222. });
  84223. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  84224. /**
  84225. * Gets the animation properties override
  84226. */
  84227. get: function () {
  84228. return this._skeleton.animationPropertiesOverride;
  84229. },
  84230. enumerable: true,
  84231. configurable: true
  84232. });
  84233. // Methods
  84234. Bone.prototype._decompose = function () {
  84235. if (!this._needToDecompose) {
  84236. return;
  84237. }
  84238. this._needToDecompose = false;
  84239. if (!this._localScaling) {
  84240. this._localScaling = BABYLON.Vector3.Zero();
  84241. this._localRotation = BABYLON.Quaternion.Zero();
  84242. this._localPosition = BABYLON.Vector3.Zero();
  84243. }
  84244. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  84245. };
  84246. Bone.prototype._compose = function () {
  84247. if (!this._needToCompose) {
  84248. return;
  84249. }
  84250. this._needToCompose = false;
  84251. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  84252. };
  84253. /**
  84254. * Update the base and local matrices
  84255. * @param matrix defines the new base or local matrix
  84256. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84257. * @param updateLocalMatrix defines if the local matrix should be updated
  84258. */
  84259. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  84260. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84261. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  84262. this._baseMatrix.copyFrom(matrix);
  84263. if (updateDifferenceMatrix) {
  84264. this._updateDifferenceMatrix();
  84265. }
  84266. if (updateLocalMatrix) {
  84267. this._localMatrix.copyFrom(matrix);
  84268. this._markAsDirtyAndDecompose();
  84269. }
  84270. else {
  84271. this.markAsDirty();
  84272. }
  84273. };
  84274. /** @hidden */
  84275. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  84276. if (updateChildren === void 0) { updateChildren = true; }
  84277. if (!rootMatrix) {
  84278. rootMatrix = this._baseMatrix;
  84279. }
  84280. if (this._parent) {
  84281. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84282. }
  84283. else {
  84284. this._absoluteTransform.copyFrom(rootMatrix);
  84285. }
  84286. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  84287. if (updateChildren) {
  84288. for (var index = 0; index < this.children.length; index++) {
  84289. this.children[index]._updateDifferenceMatrix();
  84290. }
  84291. }
  84292. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  84293. };
  84294. /**
  84295. * Flag the bone as dirty (Forcing it to update everything)
  84296. */
  84297. Bone.prototype.markAsDirty = function () {
  84298. this._currentRenderId++;
  84299. this._childRenderId++;
  84300. this._skeleton._markAsDirty();
  84301. };
  84302. Bone.prototype._markAsDirtyAndCompose = function () {
  84303. this.markAsDirty();
  84304. this._needToCompose = true;
  84305. };
  84306. Bone.prototype._markAsDirtyAndDecompose = function () {
  84307. this.markAsDirty();
  84308. this._needToDecompose = true;
  84309. };
  84310. /**
  84311. * Copy an animation range from another bone
  84312. * @param source defines the source bone
  84313. * @param rangeName defines the range name to copy
  84314. * @param frameOffset defines the frame offset
  84315. * @param rescaleAsRequired defines if rescaling must be applied if required
  84316. * @param skelDimensionsRatio defines the scaling ratio
  84317. * @returns true if operation was successful
  84318. */
  84319. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  84320. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84321. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  84322. // all animation may be coming from a library skeleton, so may need to create animation
  84323. if (this.animations.length === 0) {
  84324. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  84325. this.animations[0].setKeys([]);
  84326. }
  84327. // get animation info / verify there is such a range from the source bone
  84328. var sourceRange = source.animations[0].getRange(rangeName);
  84329. if (!sourceRange) {
  84330. return false;
  84331. }
  84332. var from = sourceRange.from;
  84333. var to = sourceRange.to;
  84334. var sourceKeys = source.animations[0].getKeys();
  84335. // rescaling prep
  84336. var sourceBoneLength = source.length;
  84337. var sourceParent = source.getParent();
  84338. var parent = this.getParent();
  84339. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  84340. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  84341. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  84342. var destKeys = this.animations[0].getKeys();
  84343. // loop vars declaration
  84344. var orig;
  84345. var origTranslation;
  84346. var mat;
  84347. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  84348. orig = sourceKeys[key];
  84349. if (orig.frame >= from && orig.frame <= to) {
  84350. if (rescaleAsRequired) {
  84351. mat = orig.value.clone();
  84352. // scale based on parent ratio, when bone has parent
  84353. if (parentScalingReqd) {
  84354. origTranslation = mat.getTranslation();
  84355. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  84356. // scale based on skeleton dimension ratio when root bone, and value is passed
  84357. }
  84358. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  84359. origTranslation = mat.getTranslation();
  84360. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  84361. // use original when root bone, and no data for skelDimensionsRatio
  84362. }
  84363. else {
  84364. mat = orig.value;
  84365. }
  84366. }
  84367. else {
  84368. mat = orig.value;
  84369. }
  84370. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  84371. }
  84372. }
  84373. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  84374. return true;
  84375. };
  84376. /**
  84377. * Translate the bone in local or world space
  84378. * @param vec The amount to translate the bone
  84379. * @param space The space that the translation is in
  84380. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84381. */
  84382. Bone.prototype.translate = function (vec, space, mesh) {
  84383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84384. var lm = this.getLocalMatrix();
  84385. if (space == BABYLON.Space.LOCAL) {
  84386. lm.m[12] += vec.x;
  84387. lm.m[13] += vec.y;
  84388. lm.m[14] += vec.z;
  84389. }
  84390. else {
  84391. var wm = null;
  84392. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84393. if (mesh) {
  84394. wm = mesh.getWorldMatrix();
  84395. }
  84396. this._skeleton.computeAbsoluteTransforms();
  84397. var tmat = Bone._tmpMats[0];
  84398. var tvec = Bone._tmpVecs[0];
  84399. if (this._parent) {
  84400. if (mesh && wm) {
  84401. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84402. tmat.multiplyToRef(wm, tmat);
  84403. }
  84404. else {
  84405. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84406. }
  84407. }
  84408. tmat.m[12] = 0;
  84409. tmat.m[13] = 0;
  84410. tmat.m[14] = 0;
  84411. tmat.invert();
  84412. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  84413. lm.m[12] += tvec.x;
  84414. lm.m[13] += tvec.y;
  84415. lm.m[14] += tvec.z;
  84416. }
  84417. this._markAsDirtyAndDecompose();
  84418. };
  84419. /**
  84420. * Set the postion of the bone in local or world space
  84421. * @param position The position to set the bone
  84422. * @param space The space that the position is in
  84423. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84424. */
  84425. Bone.prototype.setPosition = function (position, space, mesh) {
  84426. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84427. var lm = this.getLocalMatrix();
  84428. if (space == BABYLON.Space.LOCAL) {
  84429. lm.m[12] = position.x;
  84430. lm.m[13] = position.y;
  84431. lm.m[14] = position.z;
  84432. }
  84433. else {
  84434. var wm = null;
  84435. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84436. if (mesh) {
  84437. wm = mesh.getWorldMatrix();
  84438. }
  84439. this._skeleton.computeAbsoluteTransforms();
  84440. var tmat = Bone._tmpMats[0];
  84441. var vec = Bone._tmpVecs[0];
  84442. if (this._parent) {
  84443. if (mesh && wm) {
  84444. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84445. tmat.multiplyToRef(wm, tmat);
  84446. }
  84447. else {
  84448. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84449. }
  84450. }
  84451. tmat.invert();
  84452. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  84453. lm.m[12] = vec.x;
  84454. lm.m[13] = vec.y;
  84455. lm.m[14] = vec.z;
  84456. }
  84457. this._markAsDirtyAndDecompose();
  84458. };
  84459. /**
  84460. * Set the absolute position of the bone (world space)
  84461. * @param position The position to set the bone
  84462. * @param mesh The mesh that this bone is attached to
  84463. */
  84464. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  84465. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  84466. };
  84467. /**
  84468. * Scale the bone on the x, y and z axes (in local space)
  84469. * @param x The amount to scale the bone on the x axis
  84470. * @param y The amount to scale the bone on the y axis
  84471. * @param z The amount to scale the bone on the z axis
  84472. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  84473. */
  84474. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  84475. if (scaleChildren === void 0) { scaleChildren = false; }
  84476. var locMat = this.getLocalMatrix();
  84477. // Apply new scaling on top of current local matrix
  84478. var scaleMat = Bone._tmpMats[0];
  84479. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  84480. scaleMat.multiplyToRef(locMat, locMat);
  84481. // Invert scaling matrix and apply the inverse to all children
  84482. scaleMat.invert();
  84483. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  84484. var child = _a[_i];
  84485. var cm = child.getLocalMatrix();
  84486. cm.multiplyToRef(scaleMat, cm);
  84487. cm.m[12] *= x;
  84488. cm.m[13] *= y;
  84489. cm.m[14] *= z;
  84490. child._markAsDirtyAndDecompose();
  84491. }
  84492. this._markAsDirtyAndDecompose();
  84493. if (scaleChildren) {
  84494. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  84495. var child = _c[_b];
  84496. child.scale(x, y, z, scaleChildren);
  84497. }
  84498. }
  84499. };
  84500. /**
  84501. * Set the bone scaling in local space
  84502. * @param scale defines the scaling vector
  84503. */
  84504. Bone.prototype.setScale = function (scale) {
  84505. this._decompose();
  84506. this._localScaling.copyFrom(scale);
  84507. this._markAsDirtyAndCompose();
  84508. };
  84509. /**
  84510. * Gets the current scaling in local space
  84511. * @returns the current scaling vector
  84512. */
  84513. Bone.prototype.getScale = function () {
  84514. this._decompose();
  84515. return this._localScaling;
  84516. };
  84517. /**
  84518. * Gets the current scaling in local space and stores it in a target vector
  84519. * @param result defines the target vector
  84520. */
  84521. Bone.prototype.getScaleToRef = function (result) {
  84522. this._decompose();
  84523. result.copyFrom(this._localScaling);
  84524. };
  84525. /**
  84526. * Set the yaw, pitch, and roll of the bone in local or world space
  84527. * @param yaw The rotation of the bone on the y axis
  84528. * @param pitch The rotation of the bone on the x axis
  84529. * @param roll The rotation of the bone on the z axis
  84530. * @param space The space that the axes of rotation are in
  84531. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84532. */
  84533. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  84534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84535. if (space === BABYLON.Space.LOCAL) {
  84536. var quat = Bone._tmpQuat;
  84537. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  84538. this.setRotationQuaternion(quat, space, mesh);
  84539. return;
  84540. }
  84541. var rotMatInv = Bone._tmpMats[0];
  84542. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84543. return;
  84544. }
  84545. var rotMat = Bone._tmpMats[1];
  84546. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  84547. rotMatInv.multiplyToRef(rotMat, rotMat);
  84548. this._rotateWithMatrix(rotMat, space, mesh);
  84549. };
  84550. /**
  84551. * Add a rotation to the bone on an axis in local or world space
  84552. * @param axis The axis to rotate the bone on
  84553. * @param amount The amount to rotate the bone
  84554. * @param space The space that the axis is in
  84555. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84556. */
  84557. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  84558. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84559. var rmat = Bone._tmpMats[0];
  84560. rmat.m[12] = 0;
  84561. rmat.m[13] = 0;
  84562. rmat.m[14] = 0;
  84563. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  84564. this._rotateWithMatrix(rmat, space, mesh);
  84565. };
  84566. /**
  84567. * Set the rotation of the bone to a particular axis angle in local or world space
  84568. * @param axis The axis to rotate the bone on
  84569. * @param angle The angle that the bone should be rotated to
  84570. * @param space The space that the axis is in
  84571. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84572. */
  84573. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  84574. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84575. if (space === BABYLON.Space.LOCAL) {
  84576. var quat = Bone._tmpQuat;
  84577. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  84578. this.setRotationQuaternion(quat, space, mesh);
  84579. return;
  84580. }
  84581. var rotMatInv = Bone._tmpMats[0];
  84582. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84583. return;
  84584. }
  84585. var rotMat = Bone._tmpMats[1];
  84586. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  84587. rotMatInv.multiplyToRef(rotMat, rotMat);
  84588. this._rotateWithMatrix(rotMat, space, mesh);
  84589. };
  84590. /**
  84591. * Set the euler rotation of the bone in local of world space
  84592. * @param rotation The euler rotation that the bone should be set to
  84593. * @param space The space that the rotation is in
  84594. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84595. */
  84596. Bone.prototype.setRotation = function (rotation, space, mesh) {
  84597. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84598. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  84599. };
  84600. /**
  84601. * Set the quaternion rotation of the bone in local of world space
  84602. * @param quat The quaternion rotation that the bone should be set to
  84603. * @param space The space that the rotation is in
  84604. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84605. */
  84606. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  84607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84608. if (space === BABYLON.Space.LOCAL) {
  84609. this._decompose();
  84610. this._localRotation.copyFrom(quat);
  84611. this._markAsDirtyAndCompose();
  84612. return;
  84613. }
  84614. var rotMatInv = Bone._tmpMats[0];
  84615. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84616. return;
  84617. }
  84618. var rotMat = Bone._tmpMats[1];
  84619. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  84620. rotMatInv.multiplyToRef(rotMat, rotMat);
  84621. this._rotateWithMatrix(rotMat, space, mesh);
  84622. };
  84623. /**
  84624. * Set the rotation matrix of the bone in local of world space
  84625. * @param rotMat The rotation matrix that the bone should be set to
  84626. * @param space The space that the rotation is in
  84627. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84628. */
  84629. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  84630. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84631. if (space === BABYLON.Space.LOCAL) {
  84632. var quat = Bone._tmpQuat;
  84633. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  84634. this.setRotationQuaternion(quat, space, mesh);
  84635. return;
  84636. }
  84637. var rotMatInv = Bone._tmpMats[0];
  84638. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84639. return;
  84640. }
  84641. var rotMat2 = Bone._tmpMats[1];
  84642. rotMat2.copyFrom(rotMat);
  84643. rotMatInv.multiplyToRef(rotMat, rotMat2);
  84644. this._rotateWithMatrix(rotMat2, space, mesh);
  84645. };
  84646. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  84647. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84648. var lmat = this.getLocalMatrix();
  84649. var lx = lmat.m[12];
  84650. var ly = lmat.m[13];
  84651. var lz = lmat.m[14];
  84652. var parent = this.getParent();
  84653. var parentScale = Bone._tmpMats[3];
  84654. var parentScaleInv = Bone._tmpMats[4];
  84655. if (parent && space == BABYLON.Space.WORLD) {
  84656. if (mesh) {
  84657. parentScale.copyFrom(mesh.getWorldMatrix());
  84658. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  84659. }
  84660. else {
  84661. parentScale.copyFrom(parent.getAbsoluteTransform());
  84662. }
  84663. parentScaleInv.copyFrom(parentScale);
  84664. parentScaleInv.invert();
  84665. lmat.multiplyToRef(parentScale, lmat);
  84666. lmat.multiplyToRef(rmat, lmat);
  84667. lmat.multiplyToRef(parentScaleInv, lmat);
  84668. }
  84669. else {
  84670. if (space == BABYLON.Space.WORLD && mesh) {
  84671. parentScale.copyFrom(mesh.getWorldMatrix());
  84672. parentScaleInv.copyFrom(parentScale);
  84673. parentScaleInv.invert();
  84674. lmat.multiplyToRef(parentScale, lmat);
  84675. lmat.multiplyToRef(rmat, lmat);
  84676. lmat.multiplyToRef(parentScaleInv, lmat);
  84677. }
  84678. else {
  84679. lmat.multiplyToRef(rmat, lmat);
  84680. }
  84681. }
  84682. lmat.m[12] = lx;
  84683. lmat.m[13] = ly;
  84684. lmat.m[14] = lz;
  84685. this.computeAbsoluteTransforms();
  84686. this._markAsDirtyAndDecompose();
  84687. };
  84688. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  84689. var scaleMatrix = Bone._tmpMats[2];
  84690. rotMatInv.copyFrom(this.getAbsoluteTransform());
  84691. if (mesh) {
  84692. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  84693. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  84694. }
  84695. rotMatInv.invert();
  84696. if (isNaN(rotMatInv.m[0])) {
  84697. // Matrix failed to invert.
  84698. // This can happen if scale is zero for example.
  84699. return false;
  84700. }
  84701. scaleMatrix.m[0] *= this._scalingDeterminant;
  84702. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  84703. return true;
  84704. };
  84705. /**
  84706. * Get the position of the bone in local or world space
  84707. * @param space The space that the returned position is in
  84708. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84709. * @returns The position of the bone
  84710. */
  84711. Bone.prototype.getPosition = function (space, mesh) {
  84712. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84713. if (mesh === void 0) { mesh = null; }
  84714. var pos = BABYLON.Vector3.Zero();
  84715. this.getPositionToRef(space, mesh, pos);
  84716. return pos;
  84717. };
  84718. /**
  84719. * Copy the position of the bone to a vector3 in local or world space
  84720. * @param space The space that the returned position is in
  84721. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84722. * @param result The vector3 to copy the position to
  84723. */
  84724. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  84725. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84726. if (space == BABYLON.Space.LOCAL) {
  84727. var lm = this.getLocalMatrix();
  84728. result.x = lm.m[12];
  84729. result.y = lm.m[13];
  84730. result.z = lm.m[14];
  84731. }
  84732. else {
  84733. var wm = null;
  84734. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84735. if (mesh) {
  84736. wm = mesh.getWorldMatrix();
  84737. }
  84738. this._skeleton.computeAbsoluteTransforms();
  84739. var tmat = Bone._tmpMats[0];
  84740. if (mesh && wm) {
  84741. tmat.copyFrom(this.getAbsoluteTransform());
  84742. tmat.multiplyToRef(wm, tmat);
  84743. }
  84744. else {
  84745. tmat = this.getAbsoluteTransform();
  84746. }
  84747. result.x = tmat.m[12];
  84748. result.y = tmat.m[13];
  84749. result.z = tmat.m[14];
  84750. }
  84751. };
  84752. /**
  84753. * Get the absolute position of the bone (world space)
  84754. * @param mesh The mesh that this bone is attached to
  84755. * @returns The absolute position of the bone
  84756. */
  84757. Bone.prototype.getAbsolutePosition = function (mesh) {
  84758. if (mesh === void 0) { mesh = null; }
  84759. var pos = BABYLON.Vector3.Zero();
  84760. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  84761. return pos;
  84762. };
  84763. /**
  84764. * Copy the absolute position of the bone (world space) to the result param
  84765. * @param mesh The mesh that this bone is attached to
  84766. * @param result The vector3 to copy the absolute position to
  84767. */
  84768. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  84769. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  84770. };
  84771. /**
  84772. * Compute the absolute transforms of this bone and its children
  84773. */
  84774. Bone.prototype.computeAbsoluteTransforms = function () {
  84775. this._compose();
  84776. if (this._parent) {
  84777. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84778. }
  84779. else {
  84780. this._absoluteTransform.copyFrom(this._localMatrix);
  84781. var poseMatrix = this._skeleton.getPoseMatrix();
  84782. if (poseMatrix) {
  84783. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  84784. }
  84785. }
  84786. var children = this.children;
  84787. var len = children.length;
  84788. for (var i = 0; i < len; i++) {
  84789. children[i].computeAbsoluteTransforms();
  84790. }
  84791. };
  84792. /**
  84793. * Get the world direction from an axis that is in the local space of the bone
  84794. * @param localAxis The local direction that is used to compute the world direction
  84795. * @param mesh The mesh that this bone is attached to
  84796. * @returns The world direction
  84797. */
  84798. Bone.prototype.getDirection = function (localAxis, mesh) {
  84799. if (mesh === void 0) { mesh = null; }
  84800. var result = BABYLON.Vector3.Zero();
  84801. this.getDirectionToRef(localAxis, mesh, result);
  84802. return result;
  84803. };
  84804. /**
  84805. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  84806. * @param localAxis The local direction that is used to compute the world direction
  84807. * @param mesh The mesh that this bone is attached to
  84808. * @param result The vector3 that the world direction will be copied to
  84809. */
  84810. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  84811. if (mesh === void 0) { mesh = null; }
  84812. var wm = null;
  84813. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84814. if (mesh) {
  84815. wm = mesh.getWorldMatrix();
  84816. }
  84817. this._skeleton.computeAbsoluteTransforms();
  84818. var mat = Bone._tmpMats[0];
  84819. mat.copyFrom(this.getAbsoluteTransform());
  84820. if (mesh && wm) {
  84821. mat.multiplyToRef(wm, mat);
  84822. }
  84823. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  84824. result.normalize();
  84825. };
  84826. /**
  84827. * Get the euler rotation of the bone in local or world space
  84828. * @param space The space that the rotation should be in
  84829. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84830. * @returns The euler rotation
  84831. */
  84832. Bone.prototype.getRotation = function (space, mesh) {
  84833. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84834. if (mesh === void 0) { mesh = null; }
  84835. var result = BABYLON.Vector3.Zero();
  84836. this.getRotationToRef(space, mesh, result);
  84837. return result;
  84838. };
  84839. /**
  84840. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  84841. * @param space The space that the rotation should be in
  84842. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84843. * @param result The vector3 that the rotation should be copied to
  84844. */
  84845. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  84846. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84847. if (mesh === void 0) { mesh = null; }
  84848. var quat = Bone._tmpQuat;
  84849. this.getRotationQuaternionToRef(space, mesh, quat);
  84850. quat.toEulerAnglesToRef(result);
  84851. };
  84852. /**
  84853. * Get the quaternion rotation of the bone in either local or world space
  84854. * @param space The space that the rotation should be in
  84855. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84856. * @returns The quaternion rotation
  84857. */
  84858. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  84859. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84860. if (mesh === void 0) { mesh = null; }
  84861. var result = BABYLON.Quaternion.Identity();
  84862. this.getRotationQuaternionToRef(space, mesh, result);
  84863. return result;
  84864. };
  84865. /**
  84866. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  84867. * @param space The space that the rotation should be in
  84868. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84869. * @param result The quaternion that the rotation should be copied to
  84870. */
  84871. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  84872. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84873. if (mesh === void 0) { mesh = null; }
  84874. if (space == BABYLON.Space.LOCAL) {
  84875. this._decompose();
  84876. result.copyFrom(this._localRotation);
  84877. }
  84878. else {
  84879. var mat = Bone._tmpMats[0];
  84880. var amat = this.getAbsoluteTransform();
  84881. if (mesh) {
  84882. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84883. }
  84884. else {
  84885. mat.copyFrom(amat);
  84886. }
  84887. mat.m[0] *= this._scalingDeterminant;
  84888. mat.m[1] *= this._scalingDeterminant;
  84889. mat.m[2] *= this._scalingDeterminant;
  84890. mat.decompose(undefined, result, undefined);
  84891. }
  84892. };
  84893. /**
  84894. * Get the rotation matrix of the bone in local or world space
  84895. * @param space The space that the rotation should be in
  84896. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84897. * @returns The rotation matrix
  84898. */
  84899. Bone.prototype.getRotationMatrix = function (space, mesh) {
  84900. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84901. var result = BABYLON.Matrix.Identity();
  84902. this.getRotationMatrixToRef(space, mesh, result);
  84903. return result;
  84904. };
  84905. /**
  84906. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  84907. * @param space The space that the rotation should be in
  84908. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84909. * @param result The quaternion that the rotation should be copied to
  84910. */
  84911. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  84912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84913. if (space == BABYLON.Space.LOCAL) {
  84914. this.getLocalMatrix().getRotationMatrixToRef(result);
  84915. }
  84916. else {
  84917. var mat = Bone._tmpMats[0];
  84918. var amat = this.getAbsoluteTransform();
  84919. if (mesh) {
  84920. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84921. }
  84922. else {
  84923. mat.copyFrom(amat);
  84924. }
  84925. mat.m[0] *= this._scalingDeterminant;
  84926. mat.m[1] *= this._scalingDeterminant;
  84927. mat.m[2] *= this._scalingDeterminant;
  84928. mat.getRotationMatrixToRef(result);
  84929. }
  84930. };
  84931. /**
  84932. * Get the world position of a point that is in the local space of the bone
  84933. * @param position The local position
  84934. * @param mesh The mesh that this bone is attached to
  84935. * @returns The world position
  84936. */
  84937. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  84938. if (mesh === void 0) { mesh = null; }
  84939. var result = BABYLON.Vector3.Zero();
  84940. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  84941. return result;
  84942. };
  84943. /**
  84944. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  84945. * @param position The local position
  84946. * @param mesh The mesh that this bone is attached to
  84947. * @param result The vector3 that the world position should be copied to
  84948. */
  84949. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  84950. if (mesh === void 0) { mesh = null; }
  84951. var wm = null;
  84952. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84953. if (mesh) {
  84954. wm = mesh.getWorldMatrix();
  84955. }
  84956. this._skeleton.computeAbsoluteTransforms();
  84957. var tmat = Bone._tmpMats[0];
  84958. if (mesh && wm) {
  84959. tmat.copyFrom(this.getAbsoluteTransform());
  84960. tmat.multiplyToRef(wm, tmat);
  84961. }
  84962. else {
  84963. tmat = this.getAbsoluteTransform();
  84964. }
  84965. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  84966. };
  84967. /**
  84968. * Get the local position of a point that is in world space
  84969. * @param position The world position
  84970. * @param mesh The mesh that this bone is attached to
  84971. * @returns The local position
  84972. */
  84973. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  84974. if (mesh === void 0) { mesh = null; }
  84975. var result = BABYLON.Vector3.Zero();
  84976. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  84977. return result;
  84978. };
  84979. /**
  84980. * Get the local position of a point that is in world space and copy it to the result param
  84981. * @param position The world position
  84982. * @param mesh The mesh that this bone is attached to
  84983. * @param result The vector3 that the local position should be copied to
  84984. */
  84985. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  84986. if (mesh === void 0) { mesh = null; }
  84987. var wm = null;
  84988. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84989. if (mesh) {
  84990. wm = mesh.getWorldMatrix();
  84991. }
  84992. this._skeleton.computeAbsoluteTransforms();
  84993. var tmat = Bone._tmpMats[0];
  84994. tmat.copyFrom(this.getAbsoluteTransform());
  84995. if (mesh && wm) {
  84996. tmat.multiplyToRef(wm, tmat);
  84997. }
  84998. tmat.invert();
  84999. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85000. };
  85001. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85002. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  85003. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85004. return Bone;
  85005. }(BABYLON.Node));
  85006. BABYLON.Bone = Bone;
  85007. })(BABYLON || (BABYLON = {}));
  85008. //# sourceMappingURL=babylon.bone.js.map
  85009. var BABYLON;
  85010. (function (BABYLON) {
  85011. /**
  85012. * Class used to apply inverse kinematics to bones
  85013. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  85014. */
  85015. var BoneIKController = /** @class */ (function () {
  85016. /**
  85017. * Creates a new BoneIKController
  85018. * @param mesh defines the mesh to control
  85019. * @param bone defines the bone to control
  85020. * @param options defines options to set up the controller
  85021. */
  85022. function BoneIKController(mesh, bone, options) {
  85023. /**
  85024. * Gets or sets the target position
  85025. */
  85026. this.targetPosition = BABYLON.Vector3.Zero();
  85027. /**
  85028. * Gets or sets the pole target position
  85029. */
  85030. this.poleTargetPosition = BABYLON.Vector3.Zero();
  85031. /**
  85032. * Gets or sets the pole target local offset
  85033. */
  85034. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  85035. /**
  85036. * Gets or sets the pole angle
  85037. */
  85038. this.poleAngle = 0;
  85039. /**
  85040. * 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)
  85041. */
  85042. this.slerpAmount = 1;
  85043. this._bone1Quat = BABYLON.Quaternion.Identity();
  85044. this._bone1Mat = BABYLON.Matrix.Identity();
  85045. this._bone2Ang = Math.PI;
  85046. this._maxAngle = Math.PI;
  85047. this._rightHandedSystem = false;
  85048. this._bendAxis = BABYLON.Vector3.Right();
  85049. this._slerping = false;
  85050. this._adjustRoll = 0;
  85051. this._bone2 = bone;
  85052. this._bone1 = bone.getParent();
  85053. if (!this._bone1) {
  85054. return;
  85055. }
  85056. this.mesh = mesh;
  85057. var bonePos = bone.getPosition();
  85058. if (bone.getAbsoluteTransform().determinant() > 0) {
  85059. this._rightHandedSystem = true;
  85060. this._bendAxis.x = 0;
  85061. this._bendAxis.y = 0;
  85062. this._bendAxis.z = -1;
  85063. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  85064. this._adjustRoll = Math.PI * .5;
  85065. this._bendAxis.z = 1;
  85066. }
  85067. }
  85068. if (this._bone1.length) {
  85069. var boneScale1 = this._bone1.getScale();
  85070. var boneScale2 = this._bone2.getScale();
  85071. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  85072. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  85073. }
  85074. else if (this._bone1.children[0]) {
  85075. mesh.computeWorldMatrix(true);
  85076. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  85077. var pos2 = this._bone2.getAbsolutePosition(mesh);
  85078. var pos3 = this._bone1.getAbsolutePosition(mesh);
  85079. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  85080. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  85081. }
  85082. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  85083. this.maxAngle = Math.PI;
  85084. if (options) {
  85085. if (options.targetMesh) {
  85086. this.targetMesh = options.targetMesh;
  85087. this.targetMesh.computeWorldMatrix(true);
  85088. }
  85089. if (options.poleTargetMesh) {
  85090. this.poleTargetMesh = options.poleTargetMesh;
  85091. this.poleTargetMesh.computeWorldMatrix(true);
  85092. }
  85093. else if (options.poleTargetBone) {
  85094. this.poleTargetBone = options.poleTargetBone;
  85095. }
  85096. else if (this._bone1.getParent()) {
  85097. this.poleTargetBone = this._bone1.getParent();
  85098. }
  85099. if (options.poleTargetLocalOffset) {
  85100. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  85101. }
  85102. if (options.poleAngle) {
  85103. this.poleAngle = options.poleAngle;
  85104. }
  85105. if (options.bendAxis) {
  85106. this._bendAxis.copyFrom(options.bendAxis);
  85107. }
  85108. if (options.maxAngle) {
  85109. this.maxAngle = options.maxAngle;
  85110. }
  85111. if (options.slerpAmount) {
  85112. this.slerpAmount = options.slerpAmount;
  85113. }
  85114. }
  85115. }
  85116. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  85117. /**
  85118. * Gets or sets maximum allowed angle
  85119. */
  85120. get: function () {
  85121. return this._maxAngle;
  85122. },
  85123. set: function (value) {
  85124. this._setMaxAngle(value);
  85125. },
  85126. enumerable: true,
  85127. configurable: true
  85128. });
  85129. BoneIKController.prototype._setMaxAngle = function (ang) {
  85130. if (ang < 0) {
  85131. ang = 0;
  85132. }
  85133. if (ang > Math.PI || ang == undefined) {
  85134. ang = Math.PI;
  85135. }
  85136. this._maxAngle = ang;
  85137. var a = this._bone1Length;
  85138. var b = this._bone2Length;
  85139. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  85140. };
  85141. /**
  85142. * Force the controller to update the bones
  85143. */
  85144. BoneIKController.prototype.update = function () {
  85145. var bone1 = this._bone1;
  85146. if (!bone1) {
  85147. return;
  85148. }
  85149. var target = this.targetPosition;
  85150. var poleTarget = this.poleTargetPosition;
  85151. var mat1 = BoneIKController._tmpMats[0];
  85152. var mat2 = BoneIKController._tmpMats[1];
  85153. if (this.targetMesh) {
  85154. target.copyFrom(this.targetMesh.getAbsolutePosition());
  85155. }
  85156. if (this.poleTargetBone) {
  85157. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  85158. }
  85159. else if (this.poleTargetMesh) {
  85160. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  85161. }
  85162. var bonePos = BoneIKController._tmpVecs[0];
  85163. var zaxis = BoneIKController._tmpVecs[1];
  85164. var xaxis = BoneIKController._tmpVecs[2];
  85165. var yaxis = BoneIKController._tmpVecs[3];
  85166. var upAxis = BoneIKController._tmpVecs[4];
  85167. var _tmpQuat = BoneIKController._tmpQuat;
  85168. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  85169. poleTarget.subtractToRef(bonePos, upAxis);
  85170. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  85171. upAxis.y = 1;
  85172. }
  85173. else {
  85174. upAxis.normalize();
  85175. }
  85176. target.subtractToRef(bonePos, yaxis);
  85177. yaxis.normalize();
  85178. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  85179. zaxis.normalize();
  85180. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  85181. xaxis.normalize();
  85182. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  85183. var a = this._bone1Length;
  85184. var b = this._bone2Length;
  85185. var c = BABYLON.Vector3.Distance(bonePos, target);
  85186. if (this._maxReach > 0) {
  85187. c = Math.min(this._maxReach, c);
  85188. }
  85189. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  85190. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  85191. if (acosa > 1) {
  85192. acosa = 1;
  85193. }
  85194. if (acosb > 1) {
  85195. acosb = 1;
  85196. }
  85197. if (acosa < -1) {
  85198. acosa = -1;
  85199. }
  85200. if (acosb < -1) {
  85201. acosb = -1;
  85202. }
  85203. var angA = Math.acos(acosa);
  85204. var angB = Math.acos(acosb);
  85205. var angC = -angA - angB;
  85206. if (this._rightHandedSystem) {
  85207. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  85208. mat2.multiplyToRef(mat1, mat1);
  85209. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  85210. mat2.multiplyToRef(mat1, mat1);
  85211. }
  85212. else {
  85213. var _tmpVec = BoneIKController._tmpVecs[5];
  85214. _tmpVec.copyFrom(this._bendAxis);
  85215. _tmpVec.x *= -1;
  85216. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  85217. mat2.multiplyToRef(mat1, mat1);
  85218. }
  85219. if (this.poleAngle) {
  85220. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  85221. mat1.multiplyToRef(mat2, mat1);
  85222. }
  85223. if (this._bone1) {
  85224. if (this.slerpAmount < 1) {
  85225. if (!this._slerping) {
  85226. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  85227. }
  85228. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  85229. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  85230. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  85231. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  85232. this._slerping = true;
  85233. }
  85234. else {
  85235. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  85236. this._bone1Mat.copyFrom(mat1);
  85237. this._slerping = false;
  85238. }
  85239. }
  85240. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  85241. this._bone2Ang = angC;
  85242. };
  85243. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85244. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  85245. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85246. return BoneIKController;
  85247. }());
  85248. BABYLON.BoneIKController = BoneIKController;
  85249. })(BABYLON || (BABYLON = {}));
  85250. //# sourceMappingURL=babylon.boneIKController.js.map
  85251. var BABYLON;
  85252. (function (BABYLON) {
  85253. /**
  85254. * Class used to make a bone look toward a point in space
  85255. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  85256. */
  85257. var BoneLookController = /** @class */ (function () {
  85258. /**
  85259. * Create a BoneLookController
  85260. * @param mesh the mesh that the bone belongs to
  85261. * @param bone the bone that will be looking to the target
  85262. * @param target the target Vector3 to look at
  85263. * @param settings optional settings:
  85264. * * maxYaw: the maximum angle the bone will yaw to
  85265. * * minYaw: the minimum angle the bone will yaw to
  85266. * * maxPitch: the maximum angle the bone will pitch to
  85267. * * minPitch: the minimum angle the bone will yaw to
  85268. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  85269. * * upAxis: the up axis of the coordinate system
  85270. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  85271. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  85272. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  85273. * * adjustYaw: used to make an adjustment to the yaw of the bone
  85274. * * adjustPitch: used to make an adjustment to the pitch of the bone
  85275. * * adjustRoll: used to make an adjustment to the roll of the bone
  85276. **/
  85277. function BoneLookController(mesh, bone, target, options) {
  85278. /**
  85279. * The up axis of the coordinate system that is used when the bone is rotated
  85280. */
  85281. this.upAxis = BABYLON.Vector3.Up();
  85282. /**
  85283. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  85284. */
  85285. this.upAxisSpace = BABYLON.Space.LOCAL;
  85286. /**
  85287. * Used to make an adjustment to the yaw of the bone
  85288. */
  85289. this.adjustYaw = 0;
  85290. /**
  85291. * Used to make an adjustment to the pitch of the bone
  85292. */
  85293. this.adjustPitch = 0;
  85294. /**
  85295. * Used to make an adjustment to the roll of the bone
  85296. */
  85297. this.adjustRoll = 0;
  85298. /**
  85299. * 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)
  85300. */
  85301. this.slerpAmount = 1;
  85302. this._boneQuat = BABYLON.Quaternion.Identity();
  85303. this._slerping = false;
  85304. this._firstFrameSkipped = false;
  85305. this._fowardAxis = BABYLON.Vector3.Forward();
  85306. this.mesh = mesh;
  85307. this.bone = bone;
  85308. this.target = target;
  85309. if (options) {
  85310. if (options.adjustYaw) {
  85311. this.adjustYaw = options.adjustYaw;
  85312. }
  85313. if (options.adjustPitch) {
  85314. this.adjustPitch = options.adjustPitch;
  85315. }
  85316. if (options.adjustRoll) {
  85317. this.adjustRoll = options.adjustRoll;
  85318. }
  85319. if (options.maxYaw != null) {
  85320. this.maxYaw = options.maxYaw;
  85321. }
  85322. else {
  85323. this.maxYaw = Math.PI;
  85324. }
  85325. if (options.minYaw != null) {
  85326. this.minYaw = options.minYaw;
  85327. }
  85328. else {
  85329. this.minYaw = -Math.PI;
  85330. }
  85331. if (options.maxPitch != null) {
  85332. this.maxPitch = options.maxPitch;
  85333. }
  85334. else {
  85335. this.maxPitch = Math.PI;
  85336. }
  85337. if (options.minPitch != null) {
  85338. this.minPitch = options.minPitch;
  85339. }
  85340. else {
  85341. this.minPitch = -Math.PI;
  85342. }
  85343. if (options.slerpAmount != null) {
  85344. this.slerpAmount = options.slerpAmount;
  85345. }
  85346. if (options.upAxis != null) {
  85347. this.upAxis = options.upAxis;
  85348. }
  85349. if (options.upAxisSpace != null) {
  85350. this.upAxisSpace = options.upAxisSpace;
  85351. }
  85352. if (options.yawAxis != null || options.pitchAxis != null) {
  85353. var newYawAxis = BABYLON.Axis.Y;
  85354. var newPitchAxis = BABYLON.Axis.X;
  85355. if (options.yawAxis != null) {
  85356. newYawAxis = options.yawAxis.clone();
  85357. newYawAxis.normalize();
  85358. }
  85359. if (options.pitchAxis != null) {
  85360. newPitchAxis = options.pitchAxis.clone();
  85361. newPitchAxis.normalize();
  85362. }
  85363. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  85364. this._transformYawPitch = BABYLON.Matrix.Identity();
  85365. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  85366. this._transformYawPitchInv = this._transformYawPitch.clone();
  85367. this._transformYawPitch.invert();
  85368. }
  85369. }
  85370. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  85371. this.upAxisSpace = BABYLON.Space.LOCAL;
  85372. }
  85373. }
  85374. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  85375. /**
  85376. * Gets or sets the minimum yaw angle that the bone can look to
  85377. */
  85378. get: function () {
  85379. return this._minYaw;
  85380. },
  85381. set: function (value) {
  85382. this._minYaw = value;
  85383. this._minYawSin = Math.sin(value);
  85384. this._minYawCos = Math.cos(value);
  85385. if (this._maxYaw != null) {
  85386. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85387. this._yawRange = this._maxYaw - this._minYaw;
  85388. }
  85389. },
  85390. enumerable: true,
  85391. configurable: true
  85392. });
  85393. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  85394. /**
  85395. * Gets or sets the maximum yaw angle that the bone can look to
  85396. */
  85397. get: function () {
  85398. return this._maxYaw;
  85399. },
  85400. set: function (value) {
  85401. this._maxYaw = value;
  85402. this._maxYawSin = Math.sin(value);
  85403. this._maxYawCos = Math.cos(value);
  85404. if (this._minYaw != null) {
  85405. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85406. this._yawRange = this._maxYaw - this._minYaw;
  85407. }
  85408. },
  85409. enumerable: true,
  85410. configurable: true
  85411. });
  85412. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  85413. /**
  85414. * Gets or sets the minimum pitch angle that the bone can look to
  85415. */
  85416. get: function () {
  85417. return this._minPitch;
  85418. },
  85419. set: function (value) {
  85420. this._minPitch = value;
  85421. this._minPitchTan = Math.tan(value);
  85422. },
  85423. enumerable: true,
  85424. configurable: true
  85425. });
  85426. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  85427. /**
  85428. * Gets or sets the maximum pitch angle that the bone can look to
  85429. */
  85430. get: function () {
  85431. return this._maxPitch;
  85432. },
  85433. set: function (value) {
  85434. this._maxPitch = value;
  85435. this._maxPitchTan = Math.tan(value);
  85436. },
  85437. enumerable: true,
  85438. configurable: true
  85439. });
  85440. /**
  85441. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  85442. */
  85443. BoneLookController.prototype.update = function () {
  85444. //skip the first frame when slerping so that the mesh rotation is correct
  85445. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  85446. this._firstFrameSkipped = true;
  85447. return;
  85448. }
  85449. var bone = this.bone;
  85450. var bonePos = BoneLookController._tmpVecs[0];
  85451. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  85452. var target = this.target;
  85453. var _tmpMat1 = BoneLookController._tmpMats[0];
  85454. var _tmpMat2 = BoneLookController._tmpMats[1];
  85455. var mesh = this.mesh;
  85456. var parentBone = bone.getParent();
  85457. var upAxis = BoneLookController._tmpVecs[1];
  85458. upAxis.copyFrom(this.upAxis);
  85459. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  85460. if (this._transformYawPitch) {
  85461. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  85462. }
  85463. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  85464. }
  85465. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  85466. mesh.getDirectionToRef(upAxis, upAxis);
  85467. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  85468. upAxis.normalize();
  85469. }
  85470. }
  85471. var checkYaw = false;
  85472. var checkPitch = false;
  85473. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  85474. checkYaw = true;
  85475. }
  85476. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  85477. checkPitch = true;
  85478. }
  85479. if (checkYaw || checkPitch) {
  85480. var spaceMat = BoneLookController._tmpMats[2];
  85481. var spaceMatInv = BoneLookController._tmpMats[3];
  85482. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  85483. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  85484. }
  85485. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  85486. spaceMat.copyFrom(mesh.getWorldMatrix());
  85487. }
  85488. else {
  85489. var forwardAxis = BoneLookController._tmpVecs[2];
  85490. forwardAxis.copyFrom(this._fowardAxis);
  85491. if (this._transformYawPitch) {
  85492. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  85493. }
  85494. if (parentBone) {
  85495. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  85496. }
  85497. else {
  85498. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  85499. }
  85500. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  85501. rightAxis.normalize();
  85502. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  85503. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  85504. }
  85505. spaceMat.invertToRef(spaceMatInv);
  85506. var xzlen = null;
  85507. if (checkPitch) {
  85508. var localTarget = BoneLookController._tmpVecs[3];
  85509. target.subtractToRef(bonePos, localTarget);
  85510. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85511. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85512. var pitch = Math.atan2(localTarget.y, xzlen);
  85513. var newPitch = pitch;
  85514. if (pitch > this._maxPitch) {
  85515. localTarget.y = this._maxPitchTan * xzlen;
  85516. newPitch = this._maxPitch;
  85517. }
  85518. else if (pitch < this._minPitch) {
  85519. localTarget.y = this._minPitchTan * xzlen;
  85520. newPitch = this._minPitch;
  85521. }
  85522. if (pitch != newPitch) {
  85523. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85524. localTarget.addInPlace(bonePos);
  85525. target = localTarget;
  85526. }
  85527. }
  85528. if (checkYaw) {
  85529. var localTarget = BoneLookController._tmpVecs[4];
  85530. target.subtractToRef(bonePos, localTarget);
  85531. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85532. var yaw = Math.atan2(localTarget.x, localTarget.z);
  85533. var newYaw = yaw;
  85534. if (yaw > this._maxYaw || yaw < this._minYaw) {
  85535. if (xzlen == null) {
  85536. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85537. }
  85538. if (this._yawRange > Math.PI) {
  85539. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  85540. localTarget.z = this._maxYawCos * xzlen;
  85541. localTarget.x = this._maxYawSin * xzlen;
  85542. newYaw = this._maxYaw;
  85543. }
  85544. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  85545. localTarget.z = this._minYawCos * xzlen;
  85546. localTarget.x = this._minYawSin * xzlen;
  85547. newYaw = this._minYaw;
  85548. }
  85549. }
  85550. else {
  85551. if (yaw > this._maxYaw) {
  85552. localTarget.z = this._maxYawCos * xzlen;
  85553. localTarget.x = this._maxYawSin * xzlen;
  85554. newYaw = this._maxYaw;
  85555. }
  85556. else if (yaw < this._minYaw) {
  85557. localTarget.z = this._minYawCos * xzlen;
  85558. localTarget.x = this._minYawSin * xzlen;
  85559. newYaw = this._minYaw;
  85560. }
  85561. }
  85562. }
  85563. if (this._slerping && this._yawRange > Math.PI) {
  85564. //are we going to be crossing into the min/max region?
  85565. var boneFwd = BoneLookController._tmpVecs[8];
  85566. boneFwd.copyFrom(BABYLON.Axis.Z);
  85567. if (this._transformYawPitch) {
  85568. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  85569. }
  85570. var boneRotMat = BoneLookController._tmpMats[4];
  85571. this._boneQuat.toRotationMatrix(boneRotMat);
  85572. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  85573. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  85574. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  85575. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  85576. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  85577. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  85578. if (angBtwTar > angBtwMidYaw) {
  85579. if (xzlen == null) {
  85580. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85581. }
  85582. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  85583. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  85584. if (angBtwMin < angBtwMax) {
  85585. newYaw = boneYaw + Math.PI * .75;
  85586. localTarget.z = Math.cos(newYaw) * xzlen;
  85587. localTarget.x = Math.sin(newYaw) * xzlen;
  85588. }
  85589. else {
  85590. newYaw = boneYaw - Math.PI * .75;
  85591. localTarget.z = Math.cos(newYaw) * xzlen;
  85592. localTarget.x = Math.sin(newYaw) * xzlen;
  85593. }
  85594. }
  85595. }
  85596. if (yaw != newYaw) {
  85597. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85598. localTarget.addInPlace(bonePos);
  85599. target = localTarget;
  85600. }
  85601. }
  85602. }
  85603. var zaxis = BoneLookController._tmpVecs[5];
  85604. var xaxis = BoneLookController._tmpVecs[6];
  85605. var yaxis = BoneLookController._tmpVecs[7];
  85606. var _tmpQuat = BoneLookController._tmpQuat;
  85607. target.subtractToRef(bonePos, zaxis);
  85608. zaxis.normalize();
  85609. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  85610. xaxis.normalize();
  85611. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  85612. yaxis.normalize();
  85613. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  85614. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  85615. return;
  85616. }
  85617. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  85618. return;
  85619. }
  85620. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  85621. return;
  85622. }
  85623. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  85624. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  85625. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  85626. }
  85627. if (this.slerpAmount < 1) {
  85628. if (!this._slerping) {
  85629. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  85630. }
  85631. if (this._transformYawPitch) {
  85632. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85633. }
  85634. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  85635. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  85636. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  85637. this._slerping = true;
  85638. }
  85639. else {
  85640. if (this._transformYawPitch) {
  85641. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85642. }
  85643. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  85644. this._slerping = false;
  85645. }
  85646. };
  85647. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  85648. var angDiff = ang2 - ang1;
  85649. angDiff %= Math.PI * 2;
  85650. if (angDiff > Math.PI) {
  85651. angDiff -= Math.PI * 2;
  85652. }
  85653. else if (angDiff < -Math.PI) {
  85654. angDiff += Math.PI * 2;
  85655. }
  85656. return angDiff;
  85657. };
  85658. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  85659. ang1 %= (2 * Math.PI);
  85660. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85661. ang2 %= (2 * Math.PI);
  85662. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85663. var ab = 0;
  85664. if (ang1 < ang2) {
  85665. ab = ang2 - ang1;
  85666. }
  85667. else {
  85668. ab = ang1 - ang2;
  85669. }
  85670. if (ab > Math.PI) {
  85671. ab = Math.PI * 2 - ab;
  85672. }
  85673. return ab;
  85674. };
  85675. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  85676. ang %= (2 * Math.PI);
  85677. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  85678. ang1 %= (2 * Math.PI);
  85679. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85680. ang2 %= (2 * Math.PI);
  85681. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85682. if (ang1 < ang2) {
  85683. if (ang > ang1 && ang < ang2) {
  85684. return true;
  85685. }
  85686. }
  85687. else {
  85688. if (ang > ang2 && ang < ang1) {
  85689. return true;
  85690. }
  85691. }
  85692. return false;
  85693. };
  85694. 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()];
  85695. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  85696. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85697. return BoneLookController;
  85698. }());
  85699. BABYLON.BoneLookController = BoneLookController;
  85700. })(BABYLON || (BABYLON = {}));
  85701. //# sourceMappingURL=babylon.boneLookController.js.map
  85702. var BABYLON;
  85703. (function (BABYLON) {
  85704. /**
  85705. * Class used to handle skinning animations
  85706. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  85707. */
  85708. var Skeleton = /** @class */ (function () {
  85709. /**
  85710. * Creates a new skeleton
  85711. * @param name defines the skeleton name
  85712. * @param id defines the skeleton Id
  85713. * @param scene defines the hosting scene
  85714. */
  85715. function Skeleton(
  85716. /** defines the skeleton name */
  85717. name,
  85718. /** defines the skeleton Id */
  85719. id, scene) {
  85720. this.name = name;
  85721. this.id = id;
  85722. /**
  85723. * Gets the list of child bones
  85724. */
  85725. this.bones = new Array();
  85726. /**
  85727. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  85728. */
  85729. this.needInitialSkinMatrix = false;
  85730. this._isDirty = true;
  85731. this._meshesWithPoseMatrix = new Array();
  85732. this._identity = BABYLON.Matrix.Identity();
  85733. this._ranges = {};
  85734. this._lastAbsoluteTransformsUpdateId = -1;
  85735. /**
  85736. * Specifies if the skeleton should be serialized
  85737. */
  85738. this.doNotSerialize = false;
  85739. this._animationPropertiesOverride = null;
  85740. // Events
  85741. /**
  85742. * An observable triggered before computing the skeleton's matrices
  85743. */
  85744. this.onBeforeComputeObservable = new BABYLON.Observable();
  85745. this.bones = [];
  85746. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85747. scene.skeletons.push(this);
  85748. //make sure it will recalculate the matrix next time prepare is called.
  85749. this._isDirty = true;
  85750. }
  85751. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  85752. /**
  85753. * Gets or sets the animation properties override
  85754. */
  85755. get: function () {
  85756. if (!this._animationPropertiesOverride) {
  85757. return this._scene.animationPropertiesOverride;
  85758. }
  85759. return this._animationPropertiesOverride;
  85760. },
  85761. set: function (value) {
  85762. this._animationPropertiesOverride = value;
  85763. },
  85764. enumerable: true,
  85765. configurable: true
  85766. });
  85767. // Members
  85768. /**
  85769. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  85770. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  85771. * @returns a Float32Array containing matrices data
  85772. */
  85773. Skeleton.prototype.getTransformMatrices = function (mesh) {
  85774. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  85775. return mesh._bonesTransformMatrices;
  85776. }
  85777. if (!this._transformMatrices) {
  85778. this.prepare();
  85779. }
  85780. return this._transformMatrices;
  85781. };
  85782. /**
  85783. * Gets the current hosting scene
  85784. * @returns a scene object
  85785. */
  85786. Skeleton.prototype.getScene = function () {
  85787. return this._scene;
  85788. };
  85789. // Methods
  85790. /**
  85791. * Gets a string representing the current skeleton data
  85792. * @param fullDetails defines a boolean indicating if we want a verbose version
  85793. * @returns a string representing the current skeleton data
  85794. */
  85795. Skeleton.prototype.toString = function (fullDetails) {
  85796. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  85797. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  85798. if (fullDetails) {
  85799. ret += ", Ranges: {";
  85800. var first = true;
  85801. for (var name_1 in this._ranges) {
  85802. if (first) {
  85803. ret += ", ";
  85804. first = false;
  85805. }
  85806. ret += name_1;
  85807. }
  85808. ret += "}";
  85809. }
  85810. return ret;
  85811. };
  85812. /**
  85813. * Get bone's index searching by name
  85814. * @param name defines bone's name to search for
  85815. * @return the indice of the bone. Returns -1 if not found
  85816. */
  85817. Skeleton.prototype.getBoneIndexByName = function (name) {
  85818. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  85819. if (this.bones[boneIndex].name === name) {
  85820. return boneIndex;
  85821. }
  85822. }
  85823. return -1;
  85824. };
  85825. /**
  85826. * Creater a new animation range
  85827. * @param name defines the name of the range
  85828. * @param from defines the start key
  85829. * @param to defines the end key
  85830. */
  85831. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  85832. // check name not already in use
  85833. if (!this._ranges[name]) {
  85834. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  85835. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85836. if (this.bones[i].animations[0]) {
  85837. this.bones[i].animations[0].createRange(name, from, to);
  85838. }
  85839. }
  85840. }
  85841. };
  85842. /**
  85843. * Delete a specific animation range
  85844. * @param name defines the name of the range
  85845. * @param deleteFrames defines if frames must be removed as well
  85846. */
  85847. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  85848. if (deleteFrames === void 0) { deleteFrames = true; }
  85849. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85850. if (this.bones[i].animations[0]) {
  85851. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  85852. }
  85853. }
  85854. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  85855. };
  85856. /**
  85857. * Gets a specific animation range
  85858. * @param name defines the name of the range to look for
  85859. * @returns the requested animation range or null if not found
  85860. */
  85861. Skeleton.prototype.getAnimationRange = function (name) {
  85862. return this._ranges[name];
  85863. };
  85864. /**
  85865. * Gets the list of all animation ranges defined on this skeleton
  85866. * @returns an array
  85867. */
  85868. Skeleton.prototype.getAnimationRanges = function () {
  85869. var animationRanges = [];
  85870. var name;
  85871. var i = 0;
  85872. for (name in this._ranges) {
  85873. animationRanges[i] = this._ranges[name];
  85874. i++;
  85875. }
  85876. return animationRanges;
  85877. };
  85878. /**
  85879. * Copy animation range from a source skeleton.
  85880. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  85881. * @param source defines the source skeleton
  85882. * @param name defines the name of the range to copy
  85883. * @param rescaleAsRequired defines if rescaling must be applied if required
  85884. * @returns true if operation was successful
  85885. */
  85886. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  85887. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  85888. if (this._ranges[name] || !source.getAnimationRange(name)) {
  85889. return false;
  85890. }
  85891. var ret = true;
  85892. var frameOffset = this._getHighestAnimationFrame() + 1;
  85893. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  85894. var boneDict = {};
  85895. var sourceBones = source.bones;
  85896. var nBones;
  85897. var i;
  85898. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  85899. boneDict[sourceBones[i].name] = sourceBones[i];
  85900. }
  85901. if (this.bones.length !== sourceBones.length) {
  85902. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  85903. ret = false;
  85904. }
  85905. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  85906. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  85907. var boneName = this.bones[i].name;
  85908. var sourceBone = boneDict[boneName];
  85909. if (sourceBone) {
  85910. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  85911. }
  85912. else {
  85913. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  85914. ret = false;
  85915. }
  85916. }
  85917. // do not call createAnimationRange(), since it also is done to bones, which was already done
  85918. var range = source.getAnimationRange(name);
  85919. if (range) {
  85920. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  85921. }
  85922. return ret;
  85923. };
  85924. /**
  85925. * Forces the skeleton to go to rest pose
  85926. */
  85927. Skeleton.prototype.returnToRest = function () {
  85928. for (var index = 0; index < this.bones.length; index++) {
  85929. this.bones[index].returnToRest();
  85930. }
  85931. };
  85932. Skeleton.prototype._getHighestAnimationFrame = function () {
  85933. var ret = 0;
  85934. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85935. if (this.bones[i].animations[0]) {
  85936. var highest = this.bones[i].animations[0].getHighestFrame();
  85937. if (ret < highest) {
  85938. ret = highest;
  85939. }
  85940. }
  85941. }
  85942. return ret;
  85943. };
  85944. /**
  85945. * Begin a specific animation range
  85946. * @param name defines the name of the range to start
  85947. * @param loop defines if looping must be turned on (false by default)
  85948. * @param speedRatio defines the speed ratio to apply (1 by default)
  85949. * @param onAnimationEnd defines a callback which will be called when animation will end
  85950. * @returns a new animatable
  85951. */
  85952. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  85953. var range = this.getAnimationRange(name);
  85954. if (!range) {
  85955. return null;
  85956. }
  85957. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  85958. };
  85959. /** @hidden */
  85960. Skeleton.prototype._markAsDirty = function () {
  85961. this._isDirty = true;
  85962. };
  85963. /** @hidden */
  85964. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  85965. this._meshesWithPoseMatrix.push(mesh);
  85966. };
  85967. /** @hidden */
  85968. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  85969. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  85970. if (index > -1) {
  85971. this._meshesWithPoseMatrix.splice(index, 1);
  85972. }
  85973. };
  85974. /** @hidden */
  85975. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  85976. this.onBeforeComputeObservable.notifyObservers(this);
  85977. for (var index = 0; index < this.bones.length; index++) {
  85978. var bone = this.bones[index];
  85979. var parentBone = bone.getParent();
  85980. if (parentBone) {
  85981. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  85982. }
  85983. else {
  85984. if (initialSkinMatrix) {
  85985. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  85986. }
  85987. else {
  85988. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  85989. }
  85990. }
  85991. if (bone._index !== -1) {
  85992. var mappedIndex = bone._index === null ? index : bone._index;
  85993. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  85994. }
  85995. }
  85996. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  85997. };
  85998. /**
  85999. * Build all resources required to render a skeleton
  86000. */
  86001. Skeleton.prototype.prepare = function () {
  86002. if (!this._isDirty) {
  86003. return;
  86004. }
  86005. if (this.needInitialSkinMatrix) {
  86006. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  86007. var mesh = this._meshesWithPoseMatrix[index];
  86008. var poseMatrix = mesh.getPoseMatrix();
  86009. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  86010. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86011. }
  86012. if (this._synchronizedWithMesh !== mesh) {
  86013. this._synchronizedWithMesh = mesh;
  86014. // Prepare bones
  86015. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  86016. var bone = this.bones[boneIndex];
  86017. if (!bone.getParent()) {
  86018. var matrix = bone.getBaseMatrix();
  86019. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  86020. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  86021. }
  86022. }
  86023. }
  86024. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  86025. }
  86026. }
  86027. else {
  86028. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  86029. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86030. }
  86031. this._computeTransformMatrices(this._transformMatrices, null);
  86032. }
  86033. this._isDirty = false;
  86034. this._scene._activeBones.addCount(this.bones.length, false);
  86035. };
  86036. /**
  86037. * Gets the list of animatables currently running for this skeleton
  86038. * @returns an array of animatables
  86039. */
  86040. Skeleton.prototype.getAnimatables = function () {
  86041. if (!this._animatables || this._animatables.length !== this.bones.length) {
  86042. this._animatables = [];
  86043. for (var index = 0; index < this.bones.length; index++) {
  86044. this._animatables.push(this.bones[index]);
  86045. }
  86046. }
  86047. return this._animatables;
  86048. };
  86049. /**
  86050. * Clone the current skeleton
  86051. * @param name defines the name of the new skeleton
  86052. * @param id defines the id of the enw skeleton
  86053. * @returns the new skeleton
  86054. */
  86055. Skeleton.prototype.clone = function (name, id) {
  86056. var result = new Skeleton(name, id || name, this._scene);
  86057. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86058. for (var index = 0; index < this.bones.length; index++) {
  86059. var source = this.bones[index];
  86060. var parentBone = null;
  86061. var parent_1 = source.getParent();
  86062. if (parent_1) {
  86063. var parentIndex = this.bones.indexOf(parent_1);
  86064. parentBone = result.bones[parentIndex];
  86065. }
  86066. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  86067. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  86068. }
  86069. if (this._ranges) {
  86070. result._ranges = {};
  86071. for (var rangeName in this._ranges) {
  86072. var range = this._ranges[rangeName];
  86073. if (range) {
  86074. result._ranges[rangeName] = range.clone();
  86075. }
  86076. }
  86077. }
  86078. this._isDirty = true;
  86079. return result;
  86080. };
  86081. /**
  86082. * Enable animation blending for this skeleton
  86083. * @param blendingSpeed defines the blending speed to apply
  86084. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  86085. */
  86086. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  86087. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  86088. this.bones.forEach(function (bone) {
  86089. bone.animations.forEach(function (animation) {
  86090. animation.enableBlending = true;
  86091. animation.blendingSpeed = blendingSpeed;
  86092. });
  86093. });
  86094. };
  86095. /**
  86096. * Releases all resources associated with the current skeleton
  86097. */
  86098. Skeleton.prototype.dispose = function () {
  86099. this._meshesWithPoseMatrix = [];
  86100. // Animations
  86101. this.getScene().stopAnimation(this);
  86102. // Remove from scene
  86103. this.getScene().removeSkeleton(this);
  86104. };
  86105. /**
  86106. * Serialize the skeleton in a JSON object
  86107. * @returns a JSON object
  86108. */
  86109. Skeleton.prototype.serialize = function () {
  86110. var serializationObject = {};
  86111. serializationObject.name = this.name;
  86112. serializationObject.id = this.id;
  86113. if (this.dimensionsAtRest) {
  86114. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  86115. }
  86116. serializationObject.bones = [];
  86117. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86118. for (var index = 0; index < this.bones.length; index++) {
  86119. var bone = this.bones[index];
  86120. var parent_2 = bone.getParent();
  86121. var serializedBone = {
  86122. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  86123. name: bone.name,
  86124. matrix: bone.getBaseMatrix().toArray(),
  86125. rest: bone.getRestPose().toArray()
  86126. };
  86127. serializationObject.bones.push(serializedBone);
  86128. if (bone.length) {
  86129. serializedBone.length = bone.length;
  86130. }
  86131. if (bone.metadata) {
  86132. serializedBone.metadata = bone.metadata;
  86133. }
  86134. if (bone.animations && bone.animations.length > 0) {
  86135. serializedBone.animation = bone.animations[0].serialize();
  86136. }
  86137. serializationObject.ranges = [];
  86138. for (var name in this._ranges) {
  86139. var source = this._ranges[name];
  86140. if (!source) {
  86141. continue;
  86142. }
  86143. var range = {};
  86144. range.name = name;
  86145. range.from = source.from;
  86146. range.to = source.to;
  86147. serializationObject.ranges.push(range);
  86148. }
  86149. }
  86150. return serializationObject;
  86151. };
  86152. /**
  86153. * Creates a new skeleton from serialized data
  86154. * @param parsedSkeleton defines the serialized data
  86155. * @param scene defines the hosting scene
  86156. * @returns a new skeleton
  86157. */
  86158. Skeleton.Parse = function (parsedSkeleton, scene) {
  86159. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  86160. if (parsedSkeleton.dimensionsAtRest) {
  86161. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  86162. }
  86163. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  86164. var index;
  86165. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  86166. var parsedBone = parsedSkeleton.bones[index];
  86167. var parentBone = null;
  86168. if (parsedBone.parentBoneIndex > -1) {
  86169. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  86170. }
  86171. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  86172. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  86173. if (parsedBone.length) {
  86174. bone.length = parsedBone.length;
  86175. }
  86176. if (parsedBone.metadata) {
  86177. bone.metadata = parsedBone.metadata;
  86178. }
  86179. if (parsedBone.animation) {
  86180. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  86181. }
  86182. }
  86183. // placed after bones, so createAnimationRange can cascade down
  86184. if (parsedSkeleton.ranges) {
  86185. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  86186. var data = parsedSkeleton.ranges[index];
  86187. skeleton.createAnimationRange(data.name, data.from, data.to);
  86188. }
  86189. }
  86190. return skeleton;
  86191. };
  86192. /**
  86193. * Compute all node absolute transforms
  86194. * @param forceUpdate defines if computation must be done even if cache is up to date
  86195. */
  86196. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  86197. if (forceUpdate === void 0) { forceUpdate = false; }
  86198. var renderId = this._scene.getRenderId();
  86199. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  86200. this.bones[0].computeAbsoluteTransforms();
  86201. this._lastAbsoluteTransformsUpdateId = renderId;
  86202. }
  86203. };
  86204. /**
  86205. * Gets the root pose matrix
  86206. * @returns a matrix
  86207. */
  86208. Skeleton.prototype.getPoseMatrix = function () {
  86209. var poseMatrix = null;
  86210. if (this._meshesWithPoseMatrix.length > 0) {
  86211. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  86212. }
  86213. return poseMatrix;
  86214. };
  86215. /**
  86216. * Sorts bones per internal index
  86217. */
  86218. Skeleton.prototype.sortBones = function () {
  86219. var bones = new Array();
  86220. var visited = new Array(this.bones.length);
  86221. for (var index = 0; index < this.bones.length; index++) {
  86222. this._sortBones(index, bones, visited);
  86223. }
  86224. this.bones = bones;
  86225. };
  86226. Skeleton.prototype._sortBones = function (index, bones, visited) {
  86227. if (visited[index]) {
  86228. return;
  86229. }
  86230. visited[index] = true;
  86231. var bone = this.bones[index];
  86232. if (bone._index === undefined) {
  86233. bone._index = index;
  86234. }
  86235. var parentBone = bone.getParent();
  86236. if (parentBone) {
  86237. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  86238. }
  86239. bones.push(bone);
  86240. };
  86241. return Skeleton;
  86242. }());
  86243. BABYLON.Skeleton = Skeleton;
  86244. })(BABYLON || (BABYLON = {}));
  86245. //# sourceMappingURL=babylon.skeleton.js.map
  86246. var BABYLON;
  86247. (function (BABYLON) {
  86248. ;
  86249. /**
  86250. * This groups tools to convert HDR texture to native colors array.
  86251. */
  86252. var HDRTools = /** @class */ (function () {
  86253. function HDRTools() {
  86254. }
  86255. HDRTools.Ldexp = function (mantissa, exponent) {
  86256. if (exponent > 1023) {
  86257. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  86258. }
  86259. if (exponent < -1074) {
  86260. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  86261. }
  86262. return mantissa * Math.pow(2, exponent);
  86263. };
  86264. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  86265. if (exponent > 0) { /*nonzero pixel*/
  86266. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  86267. float32array[index + 0] = red * exponent;
  86268. float32array[index + 1] = green * exponent;
  86269. float32array[index + 2] = blue * exponent;
  86270. }
  86271. else {
  86272. float32array[index + 0] = 0;
  86273. float32array[index + 1] = 0;
  86274. float32array[index + 2] = 0;
  86275. }
  86276. };
  86277. HDRTools.readStringLine = function (uint8array, startIndex) {
  86278. var line = "";
  86279. var character = "";
  86280. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  86281. character = String.fromCharCode(uint8array[i]);
  86282. if (character == "\n") {
  86283. break;
  86284. }
  86285. line += character;
  86286. }
  86287. return line;
  86288. };
  86289. /**
  86290. * Reads header information from an RGBE texture stored in a native array.
  86291. * More information on this format are available here:
  86292. * https://en.wikipedia.org/wiki/RGBE_image_format
  86293. *
  86294. * @param uint8array The binary file stored in native array.
  86295. * @return The header information.
  86296. */
  86297. HDRTools.RGBE_ReadHeader = function (uint8array) {
  86298. var height = 0;
  86299. var width = 0;
  86300. var line = this.readStringLine(uint8array, 0);
  86301. if (line[0] != '#' || line[1] != '?') {
  86302. throw "Bad HDR Format.";
  86303. }
  86304. var endOfHeader = false;
  86305. var findFormat = false;
  86306. var lineIndex = 0;
  86307. do {
  86308. lineIndex += (line.length + 1);
  86309. line = this.readStringLine(uint8array, lineIndex);
  86310. if (line == "FORMAT=32-bit_rle_rgbe") {
  86311. findFormat = true;
  86312. }
  86313. else if (line.length == 0) {
  86314. endOfHeader = true;
  86315. }
  86316. } while (!endOfHeader);
  86317. if (!findFormat) {
  86318. throw "HDR Bad header format, unsupported FORMAT";
  86319. }
  86320. lineIndex += (line.length + 1);
  86321. line = this.readStringLine(uint8array, lineIndex);
  86322. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  86323. var match = sizeRegexp.exec(line);
  86324. // TODO. Support +Y and -X if needed.
  86325. if (!match || match.length < 3) {
  86326. throw "HDR Bad header format, no size";
  86327. }
  86328. width = parseInt(match[2]);
  86329. height = parseInt(match[1]);
  86330. if (width < 8 || width > 0x7fff) {
  86331. throw "HDR Bad header format, unsupported size";
  86332. }
  86333. lineIndex += (line.length + 1);
  86334. return {
  86335. height: height,
  86336. width: width,
  86337. dataPosition: lineIndex
  86338. };
  86339. };
  86340. /**
  86341. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  86342. * This RGBE texture needs to store the information as a panorama.
  86343. *
  86344. * More information on this format are available here:
  86345. * https://en.wikipedia.org/wiki/RGBE_image_format
  86346. *
  86347. * @param buffer The binary file stored in an array buffer.
  86348. * @param size The expected size of the extracted cubemap.
  86349. * @return The Cube Map information.
  86350. */
  86351. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  86352. var uint8array = new Uint8Array(buffer);
  86353. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  86354. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86355. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  86356. return cubeMapData;
  86357. };
  86358. /**
  86359. * Returns the pixels data extracted from an RGBE texture.
  86360. * This pixels will be stored left to right up to down in the R G B order in one array.
  86361. *
  86362. * More information on this format are available here:
  86363. * https://en.wikipedia.org/wiki/RGBE_image_format
  86364. *
  86365. * @param uint8array The binary file stored in an array buffer.
  86366. * @param hdrInfo The header information of the file.
  86367. * @return The pixels data in RGB right to left up to down order.
  86368. */
  86369. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  86370. // Keep for multi format supports.
  86371. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86372. };
  86373. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  86374. var num_scanlines = hdrInfo.height;
  86375. var scanline_width = hdrInfo.width;
  86376. var a, b, c, d, count;
  86377. var dataIndex = hdrInfo.dataPosition;
  86378. var index = 0, endIndex = 0, i = 0;
  86379. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  86380. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  86381. // 3 channels of 4 bytes per pixel in float.
  86382. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  86383. var resultArray = new Float32Array(resultBuffer);
  86384. // read in each successive scanline
  86385. while (num_scanlines > 0) {
  86386. a = uint8array[dataIndex++];
  86387. b = uint8array[dataIndex++];
  86388. c = uint8array[dataIndex++];
  86389. d = uint8array[dataIndex++];
  86390. if (a != 2 || b != 2 || (c & 0x80)) {
  86391. // this file is not run length encoded
  86392. throw "HDR Bad header format, not RLE";
  86393. }
  86394. if (((c << 8) | d) != scanline_width) {
  86395. throw "HDR Bad header format, wrong scan line width";
  86396. }
  86397. index = 0;
  86398. // read each of the four channels for the scanline into the buffer
  86399. for (i = 0; i < 4; i++) {
  86400. endIndex = (i + 1) * scanline_width;
  86401. while (index < endIndex) {
  86402. a = uint8array[dataIndex++];
  86403. b = uint8array[dataIndex++];
  86404. if (a > 128) {
  86405. // a run of the same value
  86406. count = a - 128;
  86407. if ((count == 0) || (count > endIndex - index)) {
  86408. throw "HDR Bad Format, bad scanline data (run)";
  86409. }
  86410. while (count-- > 0) {
  86411. scanLineArray[index++] = b;
  86412. }
  86413. }
  86414. else {
  86415. // a non-run
  86416. count = a;
  86417. if ((count == 0) || (count > endIndex - index)) {
  86418. throw "HDR Bad Format, bad scanline data (non-run)";
  86419. }
  86420. scanLineArray[index++] = b;
  86421. if (--count > 0) {
  86422. for (var j = 0; j < count; j++) {
  86423. scanLineArray[index++] = uint8array[dataIndex++];
  86424. }
  86425. }
  86426. }
  86427. }
  86428. }
  86429. // now convert data from buffer into floats
  86430. for (i = 0; i < scanline_width; i++) {
  86431. a = scanLineArray[i];
  86432. b = scanLineArray[i + scanline_width];
  86433. c = scanLineArray[i + 2 * scanline_width];
  86434. d = scanLineArray[i + 3 * scanline_width];
  86435. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  86436. }
  86437. num_scanlines--;
  86438. }
  86439. return resultArray;
  86440. };
  86441. return HDRTools;
  86442. }());
  86443. BABYLON.HDRTools = HDRTools;
  86444. })(BABYLON || (BABYLON = {}));
  86445. //# sourceMappingURL=babylon.hdr.js.map
  86446. var BABYLON;
  86447. (function (BABYLON) {
  86448. /**
  86449. * This represents a texture coming from an HDR input.
  86450. *
  86451. * The only supported format is currently panorama picture stored in RGBE format.
  86452. * Example of such files can be found on HDRLib: http://hdrlib.com/
  86453. */
  86454. var HDRCubeTexture = /** @class */ (function (_super) {
  86455. __extends(HDRCubeTexture, _super);
  86456. /**
  86457. * Instantiates an HDRTexture from the following parameters.
  86458. *
  86459. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  86460. * @param scene The scene the texture will be used in
  86461. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  86462. * @param noMipmap Forces to not generate the mipmap if true
  86463. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  86464. * @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)
  86465. * @param reserved Reserved flag for internal use.
  86466. */
  86467. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  86468. if (noMipmap === void 0) { noMipmap = false; }
  86469. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86470. if (gammaSpace === void 0) { gammaSpace = false; }
  86471. if (reserved === void 0) { reserved = false; }
  86472. if (onLoad === void 0) { onLoad = null; }
  86473. if (onError === void 0) { onError = null; }
  86474. var _this = _super.call(this, scene) || this;
  86475. _this._generateHarmonics = true;
  86476. _this._onLoad = null;
  86477. _this._onError = null;
  86478. /**
  86479. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  86480. */
  86481. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  86482. _this._isBlocking = true;
  86483. _this._rotationY = 0;
  86484. /**
  86485. * Gets or sets the center of the bounding box associated with the cube texture
  86486. * It must define where the camera used to render the texture was set
  86487. */
  86488. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  86489. if (!url) {
  86490. return _this;
  86491. }
  86492. _this.name = url;
  86493. _this.url = url;
  86494. _this.hasAlpha = false;
  86495. _this.isCube = true;
  86496. _this._textureMatrix = BABYLON.Matrix.Identity();
  86497. _this._onLoad = onLoad;
  86498. _this._onError = onError;
  86499. _this.gammaSpace = gammaSpace;
  86500. _this._noMipmap = noMipmap;
  86501. _this._size = size;
  86502. _this._texture = _this._getFromCache(url, _this._noMipmap);
  86503. if (!_this._texture) {
  86504. if (!scene.useDelayedTextureLoading) {
  86505. _this.loadTexture();
  86506. }
  86507. else {
  86508. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86509. }
  86510. }
  86511. return _this;
  86512. }
  86513. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  86514. /**
  86515. * Gets wether or not the texture is blocking during loading.
  86516. */
  86517. get: function () {
  86518. return this._isBlocking;
  86519. },
  86520. /**
  86521. * Sets wether or not the texture is blocking during loading.
  86522. */
  86523. set: function (value) {
  86524. this._isBlocking = value;
  86525. },
  86526. enumerable: true,
  86527. configurable: true
  86528. });
  86529. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  86530. /**
  86531. * Gets texture matrix rotation angle around Y axis radians.
  86532. */
  86533. get: function () {
  86534. return this._rotationY;
  86535. },
  86536. /**
  86537. * Sets texture matrix rotation angle around Y axis in radians.
  86538. */
  86539. set: function (value) {
  86540. this._rotationY = value;
  86541. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  86542. },
  86543. enumerable: true,
  86544. configurable: true
  86545. });
  86546. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  86547. get: function () {
  86548. return this._boundingBoxSize;
  86549. },
  86550. /**
  86551. * Gets or sets the size of the bounding box associated with the cube texture
  86552. * When defined, the cubemap will switch to local mode
  86553. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  86554. * @example https://www.babylonjs-playground.com/#RNASML
  86555. */
  86556. set: function (value) {
  86557. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  86558. return;
  86559. }
  86560. this._boundingBoxSize = value;
  86561. var scene = this.getScene();
  86562. if (scene) {
  86563. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  86564. }
  86565. },
  86566. enumerable: true,
  86567. configurable: true
  86568. });
  86569. /**
  86570. * Occurs when the file is raw .hdr file.
  86571. */
  86572. HDRCubeTexture.prototype.loadTexture = function () {
  86573. var _this = this;
  86574. var callback = function (buffer) {
  86575. _this.lodGenerationOffset = 0.0;
  86576. _this.lodGenerationScale = 0.8;
  86577. var scene = _this.getScene();
  86578. if (!scene) {
  86579. return null;
  86580. }
  86581. // Extract the raw linear data.
  86582. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  86583. // Generate harmonics if needed.
  86584. if (_this._generateHarmonics) {
  86585. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  86586. _this.sphericalPolynomial = sphericalPolynomial;
  86587. }
  86588. var results = [];
  86589. var byteArray = null;
  86590. // Push each faces.
  86591. for (var j = 0; j < 6; j++) {
  86592. // Create uintarray fallback.
  86593. if (!scene.getEngine().getCaps().textureFloat) {
  86594. // 3 channels of 1 bytes per pixel in bytes.
  86595. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  86596. byteArray = new Uint8Array(byteBuffer);
  86597. }
  86598. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  86599. // If special cases.
  86600. if (_this.gammaSpace || byteArray) {
  86601. for (var i = 0; i < _this._size * _this._size; i++) {
  86602. // Put in gamma space if requested.
  86603. if (_this.gammaSpace) {
  86604. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  86605. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  86606. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  86607. }
  86608. // Convert to int texture for fallback.
  86609. if (byteArray) {
  86610. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  86611. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  86612. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  86613. // May use luminance instead if the result is not accurate.
  86614. var max = Math.max(Math.max(r, g), b);
  86615. if (max > 255) {
  86616. var scale = 255 / max;
  86617. r *= scale;
  86618. g *= scale;
  86619. b *= scale;
  86620. }
  86621. byteArray[(i * 3) + 0] = r;
  86622. byteArray[(i * 3) + 1] = g;
  86623. byteArray[(i * 3) + 2] = b;
  86624. }
  86625. }
  86626. }
  86627. if (byteArray) {
  86628. results.push(byteArray);
  86629. }
  86630. else {
  86631. results.push(dataFace);
  86632. }
  86633. }
  86634. return results;
  86635. };
  86636. var scene = this.getScene();
  86637. if (scene) {
  86638. 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);
  86639. }
  86640. };
  86641. HDRCubeTexture.prototype.clone = function () {
  86642. var scene = this.getScene();
  86643. if (!scene) {
  86644. return this;
  86645. }
  86646. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  86647. // Base texture
  86648. newTexture.level = this.level;
  86649. newTexture.wrapU = this.wrapU;
  86650. newTexture.wrapV = this.wrapV;
  86651. newTexture.coordinatesIndex = this.coordinatesIndex;
  86652. newTexture.coordinatesMode = this.coordinatesMode;
  86653. return newTexture;
  86654. };
  86655. // Methods
  86656. HDRCubeTexture.prototype.delayLoad = function () {
  86657. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86658. return;
  86659. }
  86660. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86661. this._texture = this._getFromCache(this.url, this._noMipmap);
  86662. if (!this._texture) {
  86663. this.loadTexture();
  86664. }
  86665. };
  86666. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  86667. return this._textureMatrix;
  86668. };
  86669. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  86670. this._textureMatrix = value;
  86671. };
  86672. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  86673. var texture = null;
  86674. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  86675. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  86676. texture.name = parsedTexture.name;
  86677. texture.hasAlpha = parsedTexture.hasAlpha;
  86678. texture.level = parsedTexture.level;
  86679. texture.coordinatesMode = parsedTexture.coordinatesMode;
  86680. texture.isBlocking = parsedTexture.isBlocking;
  86681. }
  86682. if (texture) {
  86683. if (parsedTexture.boundingBoxPosition) {
  86684. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  86685. }
  86686. if (parsedTexture.boundingBoxSize) {
  86687. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  86688. }
  86689. if (parsedTexture.rotationY) {
  86690. texture.rotationY = parsedTexture.rotationY;
  86691. }
  86692. }
  86693. return texture;
  86694. };
  86695. HDRCubeTexture.prototype.serialize = function () {
  86696. if (!this.name) {
  86697. return null;
  86698. }
  86699. var serializationObject = {};
  86700. serializationObject.name = this.name;
  86701. serializationObject.hasAlpha = this.hasAlpha;
  86702. serializationObject.isCube = true;
  86703. serializationObject.level = this.level;
  86704. serializationObject.size = this._size;
  86705. serializationObject.coordinatesMode = this.coordinatesMode;
  86706. serializationObject.useInGammaSpace = this.gammaSpace;
  86707. serializationObject.generateHarmonics = this._generateHarmonics;
  86708. serializationObject.customType = "BABYLON.HDRCubeTexture";
  86709. serializationObject.noMipmap = this._noMipmap;
  86710. serializationObject.isBlocking = this._isBlocking;
  86711. serializationObject.rotationY = this._rotationY;
  86712. return serializationObject;
  86713. };
  86714. HDRCubeTexture._facesMapping = [
  86715. "right",
  86716. "left",
  86717. "up",
  86718. "down",
  86719. "front",
  86720. "back"
  86721. ];
  86722. return HDRCubeTexture;
  86723. }(BABYLON.BaseTexture));
  86724. BABYLON.HDRCubeTexture = HDRCubeTexture;
  86725. })(BABYLON || (BABYLON = {}));
  86726. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  86727. var BABYLON;
  86728. (function (BABYLON) {
  86729. /**
  86730. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  86731. */
  86732. var PanoramaToCubeMapTools = /** @class */ (function () {
  86733. function PanoramaToCubeMapTools() {
  86734. }
  86735. /**
  86736. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  86737. *
  86738. * @param float32Array The source data.
  86739. * @param inputWidth The width of the input panorama.
  86740. * @param inputhHeight The height of the input panorama.
  86741. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  86742. * @return The cubemap data
  86743. */
  86744. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  86745. if (!float32Array) {
  86746. throw "ConvertPanoramaToCubemap: input cannot be null";
  86747. }
  86748. if (float32Array.length != inputWidth * inputHeight * 3) {
  86749. throw "ConvertPanoramaToCubemap: input size is wrong";
  86750. }
  86751. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  86752. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  86753. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  86754. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  86755. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  86756. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  86757. return {
  86758. front: textureFront,
  86759. back: textureBack,
  86760. left: textureLeft,
  86761. right: textureRight,
  86762. up: textureUp,
  86763. down: textureDown,
  86764. size: size,
  86765. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86766. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  86767. gammaSpace: false,
  86768. };
  86769. };
  86770. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  86771. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  86772. var textureArray = new Float32Array(buffer);
  86773. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  86774. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  86775. var dy = 1 / texSize;
  86776. var fy = 0;
  86777. for (var y = 0; y < texSize; y++) {
  86778. var xv1 = faceData[0];
  86779. var xv2 = faceData[2];
  86780. for (var x = 0; x < texSize; x++) {
  86781. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  86782. v.normalize();
  86783. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  86784. // 3 channels per pixels
  86785. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  86786. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  86787. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  86788. xv1 = xv1.add(rotDX1);
  86789. xv2 = xv2.add(rotDX2);
  86790. }
  86791. fy += dy;
  86792. }
  86793. return textureArray;
  86794. };
  86795. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  86796. var theta = Math.atan2(vDir.z, vDir.x);
  86797. var phi = Math.acos(vDir.y);
  86798. while (theta < -Math.PI)
  86799. theta += 2 * Math.PI;
  86800. while (theta > Math.PI)
  86801. theta -= 2 * Math.PI;
  86802. var dx = theta / Math.PI;
  86803. var dy = phi / Math.PI;
  86804. // recenter.
  86805. dx = dx * 0.5 + 0.5;
  86806. var px = Math.round(dx * inputWidth);
  86807. if (px < 0)
  86808. px = 0;
  86809. else if (px >= inputWidth)
  86810. px = inputWidth - 1;
  86811. var py = Math.round(dy * inputHeight);
  86812. if (py < 0)
  86813. py = 0;
  86814. else if (py >= inputHeight)
  86815. py = inputHeight - 1;
  86816. var inputY = (inputHeight - py - 1);
  86817. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  86818. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  86819. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  86820. return {
  86821. r: r,
  86822. g: g,
  86823. b: b
  86824. };
  86825. };
  86826. PanoramaToCubeMapTools.FACE_FRONT = [
  86827. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86828. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86829. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86830. new BABYLON.Vector3(1.0, 1.0, -1.0)
  86831. ];
  86832. PanoramaToCubeMapTools.FACE_BACK = [
  86833. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86834. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86835. new BABYLON.Vector3(1.0, 1.0, 1.0),
  86836. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  86837. ];
  86838. PanoramaToCubeMapTools.FACE_RIGHT = [
  86839. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86840. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86841. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86842. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86843. ];
  86844. PanoramaToCubeMapTools.FACE_LEFT = [
  86845. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86846. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86847. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86848. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  86849. ];
  86850. PanoramaToCubeMapTools.FACE_DOWN = [
  86851. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86852. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86853. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86854. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86855. ];
  86856. PanoramaToCubeMapTools.FACE_UP = [
  86857. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86858. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86859. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86860. new BABYLON.Vector3(1.0, -1.0, -1.0)
  86861. ];
  86862. return PanoramaToCubeMapTools;
  86863. }());
  86864. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  86865. })(BABYLON || (BABYLON = {}));
  86866. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  86867. var BABYLON;
  86868. (function (BABYLON) {
  86869. var IndexedVector2 = /** @class */ (function (_super) {
  86870. __extends(IndexedVector2, _super);
  86871. function IndexedVector2(original, index) {
  86872. var _this = _super.call(this, original.x, original.y) || this;
  86873. _this.index = index;
  86874. return _this;
  86875. }
  86876. return IndexedVector2;
  86877. }(BABYLON.Vector2));
  86878. var PolygonPoints = /** @class */ (function () {
  86879. function PolygonPoints() {
  86880. this.elements = new Array();
  86881. }
  86882. PolygonPoints.prototype.add = function (originalPoints) {
  86883. var _this = this;
  86884. var result = new Array();
  86885. originalPoints.forEach(function (point) {
  86886. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  86887. var newPoint = new IndexedVector2(point, _this.elements.length);
  86888. result.push(newPoint);
  86889. _this.elements.push(newPoint);
  86890. }
  86891. });
  86892. return result;
  86893. };
  86894. PolygonPoints.prototype.computeBounds = function () {
  86895. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86896. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86897. this.elements.forEach(function (point) {
  86898. // x
  86899. if (point.x < lmin.x) {
  86900. lmin.x = point.x;
  86901. }
  86902. else if (point.x > lmax.x) {
  86903. lmax.x = point.x;
  86904. }
  86905. // y
  86906. if (point.y < lmin.y) {
  86907. lmin.y = point.y;
  86908. }
  86909. else if (point.y > lmax.y) {
  86910. lmax.y = point.y;
  86911. }
  86912. });
  86913. return {
  86914. min: lmin,
  86915. max: lmax,
  86916. width: lmax.x - lmin.x,
  86917. height: lmax.y - lmin.y
  86918. };
  86919. };
  86920. return PolygonPoints;
  86921. }());
  86922. var Polygon = /** @class */ (function () {
  86923. function Polygon() {
  86924. }
  86925. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  86926. return [
  86927. new BABYLON.Vector2(xmin, ymin),
  86928. new BABYLON.Vector2(xmax, ymin),
  86929. new BABYLON.Vector2(xmax, ymax),
  86930. new BABYLON.Vector2(xmin, ymax)
  86931. ];
  86932. };
  86933. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  86934. if (cx === void 0) { cx = 0; }
  86935. if (cy === void 0) { cy = 0; }
  86936. if (numberOfSides === void 0) { numberOfSides = 32; }
  86937. var result = new Array();
  86938. var angle = 0;
  86939. var increment = (Math.PI * 2) / numberOfSides;
  86940. for (var i = 0; i < numberOfSides; i++) {
  86941. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  86942. angle -= increment;
  86943. }
  86944. return result;
  86945. };
  86946. Polygon.Parse = function (input) {
  86947. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  86948. var i, result = [];
  86949. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  86950. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  86951. }
  86952. return result;
  86953. };
  86954. Polygon.StartingAt = function (x, y) {
  86955. return BABYLON.Path2.StartingAt(x, y);
  86956. };
  86957. return Polygon;
  86958. }());
  86959. BABYLON.Polygon = Polygon;
  86960. var PolygonMeshBuilder = /** @class */ (function () {
  86961. function PolygonMeshBuilder(name, contours, scene) {
  86962. this._points = new PolygonPoints();
  86963. this._outlinepoints = new PolygonPoints();
  86964. this._holes = new Array();
  86965. this._epoints = new Array();
  86966. this._eholes = new Array();
  86967. this._name = name;
  86968. this._scene = scene;
  86969. var points;
  86970. if (contours instanceof BABYLON.Path2) {
  86971. points = contours.getPoints();
  86972. }
  86973. else {
  86974. points = contours;
  86975. }
  86976. this._addToepoint(points);
  86977. this._points.add(points);
  86978. this._outlinepoints.add(points);
  86979. if (typeof earcut === 'undefined') {
  86980. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  86981. }
  86982. }
  86983. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  86984. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  86985. var p = points_1[_i];
  86986. this._epoints.push(p.x, p.y);
  86987. }
  86988. };
  86989. PolygonMeshBuilder.prototype.addHole = function (hole) {
  86990. this._points.add(hole);
  86991. var holepoints = new PolygonPoints();
  86992. holepoints.add(hole);
  86993. this._holes.push(holepoints);
  86994. this._eholes.push(this._epoints.length / 2);
  86995. this._addToepoint(hole);
  86996. return this;
  86997. };
  86998. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  86999. var _this = this;
  87000. if (updatable === void 0) { updatable = false; }
  87001. if (depth === void 0) { depth = 0; }
  87002. var result = new BABYLON.Mesh(this._name, this._scene);
  87003. var normals = new Array();
  87004. var positions = new Array();
  87005. var uvs = new Array();
  87006. var bounds = this._points.computeBounds();
  87007. this._points.elements.forEach(function (p) {
  87008. normals.push(0, 1.0, 0);
  87009. positions.push(p.x, 0, p.y);
  87010. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  87011. });
  87012. var indices = new Array();
  87013. var res = earcut(this._epoints, this._eholes, 2);
  87014. for (var i = 0; i < res.length; i++) {
  87015. indices.push(res[i]);
  87016. }
  87017. if (depth > 0) {
  87018. var positionscount = (positions.length / 3); //get the current pointcount
  87019. this._points.elements.forEach(function (p) {
  87020. normals.push(0, -1.0, 0);
  87021. positions.push(p.x, -depth, p.y);
  87022. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  87023. });
  87024. var totalCount = indices.length;
  87025. for (var i = 0; i < totalCount; i += 3) {
  87026. var i0 = indices[i + 0];
  87027. var i1 = indices[i + 1];
  87028. var i2 = indices[i + 2];
  87029. indices.push(i2 + positionscount);
  87030. indices.push(i1 + positionscount);
  87031. indices.push(i0 + positionscount);
  87032. }
  87033. //Add the sides
  87034. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  87035. this._holes.forEach(function (hole) {
  87036. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  87037. });
  87038. }
  87039. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  87040. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  87041. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  87042. result.setIndices(indices);
  87043. return result;
  87044. };
  87045. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  87046. var StartIndex = positions.length / 3;
  87047. var ulength = 0;
  87048. for (var i = 0; i < points.elements.length; i++) {
  87049. var p = points.elements[i];
  87050. var p1;
  87051. if ((i + 1) > points.elements.length - 1) {
  87052. p1 = points.elements[0];
  87053. }
  87054. else {
  87055. p1 = points.elements[i + 1];
  87056. }
  87057. positions.push(p.x, 0, p.y);
  87058. positions.push(p.x, -depth, p.y);
  87059. positions.push(p1.x, 0, p1.y);
  87060. positions.push(p1.x, -depth, p1.y);
  87061. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  87062. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  87063. var v3 = v2.subtract(v1);
  87064. var v4 = new BABYLON.Vector3(0, 1, 0);
  87065. var vn = BABYLON.Vector3.Cross(v3, v4);
  87066. vn = vn.normalize();
  87067. uvs.push(ulength / bounds.width, 0);
  87068. uvs.push(ulength / bounds.width, 1);
  87069. ulength += v3.length();
  87070. uvs.push((ulength / bounds.width), 0);
  87071. uvs.push((ulength / bounds.width), 1);
  87072. if (!flip) {
  87073. normals.push(-vn.x, -vn.y, -vn.z);
  87074. normals.push(-vn.x, -vn.y, -vn.z);
  87075. normals.push(-vn.x, -vn.y, -vn.z);
  87076. normals.push(-vn.x, -vn.y, -vn.z);
  87077. indices.push(StartIndex);
  87078. indices.push(StartIndex + 1);
  87079. indices.push(StartIndex + 2);
  87080. indices.push(StartIndex + 1);
  87081. indices.push(StartIndex + 3);
  87082. indices.push(StartIndex + 2);
  87083. }
  87084. else {
  87085. normals.push(vn.x, vn.y, vn.z);
  87086. normals.push(vn.x, vn.y, vn.z);
  87087. normals.push(vn.x, vn.y, vn.z);
  87088. normals.push(vn.x, vn.y, vn.z);
  87089. indices.push(StartIndex);
  87090. indices.push(StartIndex + 2);
  87091. indices.push(StartIndex + 1);
  87092. indices.push(StartIndex + 1);
  87093. indices.push(StartIndex + 2);
  87094. indices.push(StartIndex + 3);
  87095. }
  87096. StartIndex += 4;
  87097. }
  87098. ;
  87099. };
  87100. return PolygonMeshBuilder;
  87101. }());
  87102. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  87103. })(BABYLON || (BABYLON = {}));
  87104. //# sourceMappingURL=babylon.polygonMesh.js.map
  87105. var BABYLON;
  87106. (function (BABYLON) {
  87107. // Unique ID when we import meshes from Babylon to CSG
  87108. var currentCSGMeshId = 0;
  87109. // # class Vertex
  87110. // Represents a vertex of a polygon. Use your own vertex class instead of this
  87111. // one to provide additional features like texture coordinates and vertex
  87112. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  87113. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  87114. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  87115. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  87116. // is not used anywhere else.
  87117. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  87118. var Vertex = /** @class */ (function () {
  87119. function Vertex(pos, normal, uv) {
  87120. this.pos = pos;
  87121. this.normal = normal;
  87122. this.uv = uv;
  87123. }
  87124. Vertex.prototype.clone = function () {
  87125. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  87126. };
  87127. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  87128. // orientation of a polygon is flipped.
  87129. Vertex.prototype.flip = function () {
  87130. this.normal = this.normal.scale(-1);
  87131. };
  87132. // Create a new vertex between this vertex and `other` by linearly
  87133. // interpolating all properties using a parameter of `t`. Subclasses should
  87134. // override this to interpolate additional properties.
  87135. Vertex.prototype.interpolate = function (other, t) {
  87136. 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));
  87137. };
  87138. return Vertex;
  87139. }());
  87140. // # class Plane
  87141. // Represents a plane in 3D space.
  87142. var Plane = /** @class */ (function () {
  87143. function Plane(normal, w) {
  87144. this.normal = normal;
  87145. this.w = w;
  87146. }
  87147. Plane.FromPoints = function (a, b, c) {
  87148. var v0 = c.subtract(a);
  87149. var v1 = b.subtract(a);
  87150. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  87151. return null;
  87152. }
  87153. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  87154. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  87155. };
  87156. Plane.prototype.clone = function () {
  87157. return new Plane(this.normal.clone(), this.w);
  87158. };
  87159. Plane.prototype.flip = function () {
  87160. this.normal.scaleInPlace(-1);
  87161. this.w = -this.w;
  87162. };
  87163. // Split `polygon` by this plane if needed, then put the polygon or polygon
  87164. // fragments in the appropriate lists. Coplanar polygons go into either
  87165. // `coplanarFront` or `coplanarBack` depending on their orientation with
  87166. // respect to this plane. Polygons in front or in back of this plane go into
  87167. // either `front` or `back`.
  87168. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  87169. var COPLANAR = 0;
  87170. var FRONT = 1;
  87171. var BACK = 2;
  87172. var SPANNING = 3;
  87173. // Classify each point as well as the entire polygon into one of the above
  87174. // four classes.
  87175. var polygonType = 0;
  87176. var types = [];
  87177. var i;
  87178. var t;
  87179. for (i = 0; i < polygon.vertices.length; i++) {
  87180. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  87181. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  87182. polygonType |= type;
  87183. types.push(type);
  87184. }
  87185. // Put the polygon in the correct list, splitting it when necessary.
  87186. switch (polygonType) {
  87187. case COPLANAR:
  87188. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  87189. break;
  87190. case FRONT:
  87191. front.push(polygon);
  87192. break;
  87193. case BACK:
  87194. back.push(polygon);
  87195. break;
  87196. case SPANNING:
  87197. var f = [], b = [];
  87198. for (i = 0; i < polygon.vertices.length; i++) {
  87199. var j = (i + 1) % polygon.vertices.length;
  87200. var ti = types[i], tj = types[j];
  87201. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  87202. if (ti !== BACK)
  87203. f.push(vi);
  87204. if (ti !== FRONT)
  87205. b.push(ti !== BACK ? vi.clone() : vi);
  87206. if ((ti | tj) === SPANNING) {
  87207. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  87208. var v = vi.interpolate(vj, t);
  87209. f.push(v);
  87210. b.push(v.clone());
  87211. }
  87212. }
  87213. var poly;
  87214. if (f.length >= 3) {
  87215. poly = new Polygon(f, polygon.shared);
  87216. if (poly.plane)
  87217. front.push(poly);
  87218. }
  87219. if (b.length >= 3) {
  87220. poly = new Polygon(b, polygon.shared);
  87221. if (poly.plane)
  87222. back.push(poly);
  87223. }
  87224. break;
  87225. }
  87226. };
  87227. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  87228. // point is on the plane.
  87229. Plane.EPSILON = 1e-5;
  87230. return Plane;
  87231. }());
  87232. // # class Polygon
  87233. // Represents a convex polygon. The vertices used to initialize a polygon must
  87234. // be coplanar and form a convex loop.
  87235. //
  87236. // Each convex polygon has a `shared` property, which is shared between all
  87237. // polygons that are clones of each other or were split from the same polygon.
  87238. // This can be used to define per-polygon properties (such as surface color).
  87239. var Polygon = /** @class */ (function () {
  87240. function Polygon(vertices, shared) {
  87241. this.vertices = vertices;
  87242. this.shared = shared;
  87243. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  87244. }
  87245. Polygon.prototype.clone = function () {
  87246. var vertices = this.vertices.map(function (v) { return v.clone(); });
  87247. return new Polygon(vertices, this.shared);
  87248. };
  87249. Polygon.prototype.flip = function () {
  87250. this.vertices.reverse().map(function (v) { v.flip(); });
  87251. this.plane.flip();
  87252. };
  87253. return Polygon;
  87254. }());
  87255. // # class Node
  87256. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  87257. // by picking a polygon to split along. That polygon (and all other coplanar
  87258. // polygons) are added directly to that node and the other polygons are added to
  87259. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  87260. // no distinction between internal and leaf nodes.
  87261. var Node = /** @class */ (function () {
  87262. function Node(polygons) {
  87263. this.plane = null;
  87264. this.front = null;
  87265. this.back = null;
  87266. this.polygons = new Array();
  87267. if (polygons) {
  87268. this.build(polygons);
  87269. }
  87270. }
  87271. Node.prototype.clone = function () {
  87272. var node = new Node();
  87273. node.plane = this.plane && this.plane.clone();
  87274. node.front = this.front && this.front.clone();
  87275. node.back = this.back && this.back.clone();
  87276. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  87277. return node;
  87278. };
  87279. // Convert solid space to empty space and empty space to solid space.
  87280. Node.prototype.invert = function () {
  87281. for (var i = 0; i < this.polygons.length; i++) {
  87282. this.polygons[i].flip();
  87283. }
  87284. if (this.plane) {
  87285. this.plane.flip();
  87286. }
  87287. if (this.front) {
  87288. this.front.invert();
  87289. }
  87290. if (this.back) {
  87291. this.back.invert();
  87292. }
  87293. var temp = this.front;
  87294. this.front = this.back;
  87295. this.back = temp;
  87296. };
  87297. // Recursively remove all polygons in `polygons` that are inside this BSP
  87298. // tree.
  87299. Node.prototype.clipPolygons = function (polygons) {
  87300. if (!this.plane)
  87301. return polygons.slice();
  87302. var front = new Array(), back = new Array();
  87303. for (var i = 0; i < polygons.length; i++) {
  87304. this.plane.splitPolygon(polygons[i], front, back, front, back);
  87305. }
  87306. if (this.front) {
  87307. front = this.front.clipPolygons(front);
  87308. }
  87309. if (this.back) {
  87310. back = this.back.clipPolygons(back);
  87311. }
  87312. else {
  87313. back = [];
  87314. }
  87315. return front.concat(back);
  87316. };
  87317. // Remove all polygons in this BSP tree that are inside the other BSP tree
  87318. // `bsp`.
  87319. Node.prototype.clipTo = function (bsp) {
  87320. this.polygons = bsp.clipPolygons(this.polygons);
  87321. if (this.front)
  87322. this.front.clipTo(bsp);
  87323. if (this.back)
  87324. this.back.clipTo(bsp);
  87325. };
  87326. // Return a list of all polygons in this BSP tree.
  87327. Node.prototype.allPolygons = function () {
  87328. var polygons = this.polygons.slice();
  87329. if (this.front)
  87330. polygons = polygons.concat(this.front.allPolygons());
  87331. if (this.back)
  87332. polygons = polygons.concat(this.back.allPolygons());
  87333. return polygons;
  87334. };
  87335. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  87336. // new polygons are filtered down to the bottom of the tree and become new
  87337. // nodes there. Each set of polygons is partitioned using the first polygon
  87338. // (no heuristic is used to pick a good split).
  87339. Node.prototype.build = function (polygons) {
  87340. if (!polygons.length)
  87341. return;
  87342. if (!this.plane)
  87343. this.plane = polygons[0].plane.clone();
  87344. var front = new Array(), back = new Array();
  87345. for (var i = 0; i < polygons.length; i++) {
  87346. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  87347. }
  87348. if (front.length) {
  87349. if (!this.front)
  87350. this.front = new Node();
  87351. this.front.build(front);
  87352. }
  87353. if (back.length) {
  87354. if (!this.back)
  87355. this.back = new Node();
  87356. this.back.build(back);
  87357. }
  87358. };
  87359. return Node;
  87360. }());
  87361. var CSG = /** @class */ (function () {
  87362. function CSG() {
  87363. this.polygons = new Array();
  87364. }
  87365. // Convert BABYLON.Mesh to BABYLON.CSG
  87366. CSG.FromMesh = function (mesh) {
  87367. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  87368. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  87369. if (mesh instanceof BABYLON.Mesh) {
  87370. mesh.computeWorldMatrix(true);
  87371. matrix = mesh.getWorldMatrix();
  87372. meshPosition = mesh.position.clone();
  87373. meshRotation = mesh.rotation.clone();
  87374. if (mesh.rotationQuaternion) {
  87375. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  87376. }
  87377. meshScaling = mesh.scaling.clone();
  87378. }
  87379. else {
  87380. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  87381. }
  87382. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87383. var subMeshes = mesh.subMeshes;
  87384. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  87385. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  87386. vertices = [];
  87387. for (var j = 0; j < 3; j++) {
  87388. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  87389. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  87390. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  87391. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  87392. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  87393. vertex = new Vertex(position, normal, uv);
  87394. vertices.push(vertex);
  87395. }
  87396. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  87397. // To handle the case of degenerated triangle
  87398. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  87399. if (polygon.plane)
  87400. polygons.push(polygon);
  87401. }
  87402. }
  87403. var csg = CSG.FromPolygons(polygons);
  87404. csg.matrix = matrix;
  87405. csg.position = meshPosition;
  87406. csg.rotation = meshRotation;
  87407. csg.scaling = meshScaling;
  87408. csg.rotationQuaternion = meshRotationQuaternion;
  87409. currentCSGMeshId++;
  87410. return csg;
  87411. };
  87412. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  87413. CSG.FromPolygons = function (polygons) {
  87414. var csg = new CSG();
  87415. csg.polygons = polygons;
  87416. return csg;
  87417. };
  87418. CSG.prototype.clone = function () {
  87419. var csg = new CSG();
  87420. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  87421. csg.copyTransformAttributes(this);
  87422. return csg;
  87423. };
  87424. CSG.prototype.union = function (csg) {
  87425. var a = new Node(this.clone().polygons);
  87426. var b = new Node(csg.clone().polygons);
  87427. a.clipTo(b);
  87428. b.clipTo(a);
  87429. b.invert();
  87430. b.clipTo(a);
  87431. b.invert();
  87432. a.build(b.allPolygons());
  87433. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87434. };
  87435. CSG.prototype.unionInPlace = function (csg) {
  87436. var a = new Node(this.polygons);
  87437. var b = new Node(csg.polygons);
  87438. a.clipTo(b);
  87439. b.clipTo(a);
  87440. b.invert();
  87441. b.clipTo(a);
  87442. b.invert();
  87443. a.build(b.allPolygons());
  87444. this.polygons = a.allPolygons();
  87445. };
  87446. CSG.prototype.subtract = function (csg) {
  87447. var a = new Node(this.clone().polygons);
  87448. var b = new Node(csg.clone().polygons);
  87449. a.invert();
  87450. a.clipTo(b);
  87451. b.clipTo(a);
  87452. b.invert();
  87453. b.clipTo(a);
  87454. b.invert();
  87455. a.build(b.allPolygons());
  87456. a.invert();
  87457. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87458. };
  87459. CSG.prototype.subtractInPlace = function (csg) {
  87460. var a = new Node(this.polygons);
  87461. var b = new Node(csg.polygons);
  87462. a.invert();
  87463. a.clipTo(b);
  87464. b.clipTo(a);
  87465. b.invert();
  87466. b.clipTo(a);
  87467. b.invert();
  87468. a.build(b.allPolygons());
  87469. a.invert();
  87470. this.polygons = a.allPolygons();
  87471. };
  87472. CSG.prototype.intersect = function (csg) {
  87473. var a = new Node(this.clone().polygons);
  87474. var b = new Node(csg.clone().polygons);
  87475. a.invert();
  87476. b.clipTo(a);
  87477. b.invert();
  87478. a.clipTo(b);
  87479. b.clipTo(a);
  87480. a.build(b.allPolygons());
  87481. a.invert();
  87482. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87483. };
  87484. CSG.prototype.intersectInPlace = function (csg) {
  87485. var a = new Node(this.polygons);
  87486. var b = new Node(csg.polygons);
  87487. a.invert();
  87488. b.clipTo(a);
  87489. b.invert();
  87490. a.clipTo(b);
  87491. b.clipTo(a);
  87492. a.build(b.allPolygons());
  87493. a.invert();
  87494. this.polygons = a.allPolygons();
  87495. };
  87496. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  87497. // not modified.
  87498. CSG.prototype.inverse = function () {
  87499. var csg = this.clone();
  87500. csg.inverseInPlace();
  87501. return csg;
  87502. };
  87503. CSG.prototype.inverseInPlace = function () {
  87504. this.polygons.map(function (p) { p.flip(); });
  87505. };
  87506. // This is used to keep meshes transformations so they can be restored
  87507. // when we build back a Babylon Mesh
  87508. // NB : All CSG operations are performed in world coordinates
  87509. CSG.prototype.copyTransformAttributes = function (csg) {
  87510. this.matrix = csg.matrix;
  87511. this.position = csg.position;
  87512. this.rotation = csg.rotation;
  87513. this.scaling = csg.scaling;
  87514. this.rotationQuaternion = csg.rotationQuaternion;
  87515. return this;
  87516. };
  87517. // Build Raw mesh from CSG
  87518. // Coordinates here are in world space
  87519. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  87520. var matrix = this.matrix.clone();
  87521. matrix.invert();
  87522. 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;
  87523. if (keepSubMeshes) {
  87524. // Sort Polygons, since subMeshes are indices range
  87525. polygons.sort(function (a, b) {
  87526. if (a.shared.meshId === b.shared.meshId) {
  87527. return a.shared.subMeshId - b.shared.subMeshId;
  87528. }
  87529. else {
  87530. return a.shared.meshId - b.shared.meshId;
  87531. }
  87532. });
  87533. }
  87534. for (var i = 0, il = polygons.length; i < il; i++) {
  87535. polygon = polygons[i];
  87536. // Building SubMeshes
  87537. if (!subMesh_dict[polygon.shared.meshId]) {
  87538. subMesh_dict[polygon.shared.meshId] = {};
  87539. }
  87540. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  87541. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  87542. indexStart: +Infinity,
  87543. indexEnd: -Infinity,
  87544. materialIndex: polygon.shared.materialIndex
  87545. };
  87546. }
  87547. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  87548. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  87549. polygonIndices[0] = 0;
  87550. polygonIndices[1] = j - 1;
  87551. polygonIndices[2] = j;
  87552. for (var k = 0; k < 3; k++) {
  87553. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  87554. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  87555. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  87556. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  87557. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  87558. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  87559. // Check if 2 points can be merged
  87560. if (!(typeof vertex_idx !== 'undefined' &&
  87561. normals[vertex_idx * 3] === localNormal.x &&
  87562. normals[vertex_idx * 3 + 1] === localNormal.y &&
  87563. normals[vertex_idx * 3 + 2] === localNormal.z &&
  87564. uvs[vertex_idx * 2] === uv.x &&
  87565. uvs[vertex_idx * 2 + 1] === uv.y)) {
  87566. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  87567. uvs.push(uv.x, uv.y);
  87568. normals.push(normal.x, normal.y, normal.z);
  87569. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  87570. }
  87571. indices.push(vertex_idx);
  87572. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  87573. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  87574. currentIndex++;
  87575. }
  87576. }
  87577. }
  87578. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  87579. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  87580. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  87581. mesh.setIndices(indices, null);
  87582. if (keepSubMeshes) {
  87583. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  87584. var materialIndexOffset = 0, materialMaxIndex;
  87585. mesh.subMeshes = new Array();
  87586. for (var m in subMesh_dict) {
  87587. materialMaxIndex = -1;
  87588. for (var sm in subMesh_dict[m]) {
  87589. subMesh_obj = subMesh_dict[m][sm];
  87590. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  87591. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  87592. }
  87593. materialIndexOffset += ++materialMaxIndex;
  87594. }
  87595. }
  87596. return mesh;
  87597. };
  87598. // Build Mesh from CSG taking material and transforms into account
  87599. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  87600. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  87601. mesh.material = material;
  87602. mesh.position.copyFrom(this.position);
  87603. mesh.rotation.copyFrom(this.rotation);
  87604. if (this.rotationQuaternion) {
  87605. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  87606. }
  87607. mesh.scaling.copyFrom(this.scaling);
  87608. mesh.computeWorldMatrix(true);
  87609. return mesh;
  87610. };
  87611. return CSG;
  87612. }());
  87613. BABYLON.CSG = CSG;
  87614. })(BABYLON || (BABYLON = {}));
  87615. //# sourceMappingURL=babylon.csg.js.map
  87616. var BABYLON;
  87617. (function (BABYLON) {
  87618. var LensFlare = /** @class */ (function () {
  87619. function LensFlare(size, position, color, imgUrl, system) {
  87620. this.size = size;
  87621. this.position = position;
  87622. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87623. this.color = color || new BABYLON.Color3(1, 1, 1);
  87624. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  87625. this._system = system;
  87626. system.lensFlares.push(this);
  87627. }
  87628. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  87629. return new LensFlare(size, position, color, imgUrl, system);
  87630. };
  87631. LensFlare.prototype.dispose = function () {
  87632. if (this.texture) {
  87633. this.texture.dispose();
  87634. }
  87635. // Remove from scene
  87636. var index = this._system.lensFlares.indexOf(this);
  87637. this._system.lensFlares.splice(index, 1);
  87638. };
  87639. ;
  87640. return LensFlare;
  87641. }());
  87642. BABYLON.LensFlare = LensFlare;
  87643. })(BABYLON || (BABYLON = {}));
  87644. //# sourceMappingURL=babylon.lensFlare.js.map
  87645. var BABYLON;
  87646. (function (BABYLON) {
  87647. // Adds the parser to the scene parsers.
  87648. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  87649. // Lens flares
  87650. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  87651. if (!container.lensFlareSystems) {
  87652. container.lensFlareSystems = new Array();
  87653. }
  87654. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  87655. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  87656. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  87657. container.lensFlareSystems.push(lf);
  87658. }
  87659. }
  87660. });
  87661. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  87662. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87663. if (this.lensFlareSystems[index].name === name) {
  87664. return this.lensFlareSystems[index];
  87665. }
  87666. }
  87667. return null;
  87668. };
  87669. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  87670. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87671. if (this.lensFlareSystems[index].id === id) {
  87672. return this.lensFlareSystems[index];
  87673. }
  87674. }
  87675. return null;
  87676. };
  87677. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  87678. var index = this.lensFlareSystems.indexOf(toRemove);
  87679. if (index !== -1) {
  87680. this.lensFlareSystems.splice(index, 1);
  87681. }
  87682. return index;
  87683. };
  87684. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  87685. this.lensFlareSystems.push(newLensFlareSystem);
  87686. };
  87687. /**
  87688. * Defines the lens flare scene component responsible to manage any lens flares
  87689. * in a given scene.
  87690. */
  87691. var LensFlareSystemSceneComponent = /** @class */ (function () {
  87692. /**
  87693. * Creates a new instance of the component for the given scene
  87694. * @param scene Defines the scene to register the component in
  87695. */
  87696. function LensFlareSystemSceneComponent(scene) {
  87697. /**
  87698. * The component name helpfull to identify the component in the list of scene components.
  87699. */
  87700. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  87701. this.scene = scene;
  87702. scene.lensFlareSystems = new Array();
  87703. }
  87704. /**
  87705. * Registers the component in a given scene
  87706. */
  87707. LensFlareSystemSceneComponent.prototype.register = function () {
  87708. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  87709. };
  87710. /**
  87711. * Rebuilds the elements related to this component in case of
  87712. * context lost for instance.
  87713. */
  87714. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  87715. // Nothing to do for lens flare
  87716. };
  87717. /**
  87718. * Adds all the element from the container to the scene
  87719. * @param container the container holding the elements
  87720. */
  87721. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  87722. var _this = this;
  87723. if (!container.lensFlareSystems) {
  87724. return;
  87725. }
  87726. container.lensFlareSystems.forEach(function (o) {
  87727. _this.scene.addLensFlareSystem(o);
  87728. });
  87729. };
  87730. /**
  87731. * Removes all the elements in the container from the scene
  87732. * @param container contains the elements to remove
  87733. */
  87734. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  87735. var _this = this;
  87736. if (!container.lensFlareSystems) {
  87737. return;
  87738. }
  87739. container.lensFlareSystems.forEach(function (o) {
  87740. _this.scene.removeLensFlareSystem(o);
  87741. });
  87742. };
  87743. /**
  87744. * Serializes the component data to the specified json object
  87745. * @param serializationObject The object to serialize to
  87746. */
  87747. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  87748. // Lens flares
  87749. serializationObject.lensFlareSystems = [];
  87750. var lensFlareSystems = this.scene.lensFlareSystems;
  87751. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  87752. var lensFlareSystem = lensFlareSystems_1[_i];
  87753. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  87754. }
  87755. };
  87756. /**
  87757. * Disposes the component and the associated ressources.
  87758. */
  87759. LensFlareSystemSceneComponent.prototype.dispose = function () {
  87760. var lensFlareSystems = this.scene.lensFlareSystems;
  87761. while (lensFlareSystems.length) {
  87762. lensFlareSystems[0].dispose();
  87763. }
  87764. };
  87765. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  87766. // Lens flares
  87767. if (this.scene.lensFlaresEnabled) {
  87768. var lensFlareSystems = this.scene.lensFlareSystems;
  87769. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87770. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  87771. var lensFlareSystem = lensFlareSystems_2[_i];
  87772. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  87773. lensFlareSystem.render();
  87774. }
  87775. }
  87776. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87777. }
  87778. };
  87779. return LensFlareSystemSceneComponent;
  87780. }());
  87781. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  87782. })(BABYLON || (BABYLON = {}));
  87783. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  87784. var BABYLON;
  87785. (function (BABYLON) {
  87786. var LensFlareSystem = /** @class */ (function () {
  87787. function LensFlareSystem(name, emitter, scene) {
  87788. this.name = name;
  87789. this.lensFlares = new Array();
  87790. this.borderLimit = 300;
  87791. this.viewportBorder = 0;
  87792. this.layerMask = 0x0FFFFFFF;
  87793. this._vertexBuffers = {};
  87794. this._isEnabled = true;
  87795. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87796. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  87797. if (!component) {
  87798. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  87799. scene._addComponent(component);
  87800. }
  87801. this._emitter = emitter;
  87802. this.id = name;
  87803. scene.lensFlareSystems.push(this);
  87804. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  87805. var engine = scene.getEngine();
  87806. // VBO
  87807. var vertices = [];
  87808. vertices.push(1, 1);
  87809. vertices.push(-1, 1);
  87810. vertices.push(-1, -1);
  87811. vertices.push(1, -1);
  87812. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87813. // Indices
  87814. var indices = [];
  87815. indices.push(0);
  87816. indices.push(1);
  87817. indices.push(2);
  87818. indices.push(0);
  87819. indices.push(2);
  87820. indices.push(3);
  87821. this._indexBuffer = engine.createIndexBuffer(indices);
  87822. // Effects
  87823. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  87824. }
  87825. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  87826. get: function () {
  87827. return this._isEnabled;
  87828. },
  87829. set: function (value) {
  87830. this._isEnabled = value;
  87831. },
  87832. enumerable: true,
  87833. configurable: true
  87834. });
  87835. LensFlareSystem.prototype.getScene = function () {
  87836. return this._scene;
  87837. };
  87838. LensFlareSystem.prototype.getEmitter = function () {
  87839. return this._emitter;
  87840. };
  87841. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  87842. this._emitter = newEmitter;
  87843. };
  87844. LensFlareSystem.prototype.getEmitterPosition = function () {
  87845. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  87846. };
  87847. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  87848. var position = this.getEmitterPosition();
  87849. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  87850. this._positionX = position.x;
  87851. this._positionY = position.y;
  87852. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  87853. if (this.viewportBorder > 0) {
  87854. globalViewport.x -= this.viewportBorder;
  87855. globalViewport.y -= this.viewportBorder;
  87856. globalViewport.width += this.viewportBorder * 2;
  87857. globalViewport.height += this.viewportBorder * 2;
  87858. position.x += this.viewportBorder;
  87859. position.y += this.viewportBorder;
  87860. this._positionX += this.viewportBorder;
  87861. this._positionY += this.viewportBorder;
  87862. }
  87863. if (position.z > 0) {
  87864. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  87865. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  87866. return true;
  87867. }
  87868. return true;
  87869. }
  87870. return false;
  87871. };
  87872. /** @hidden */
  87873. LensFlareSystem.prototype._isVisible = function () {
  87874. if (!this._isEnabled || !this._scene.activeCamera) {
  87875. return false;
  87876. }
  87877. var emitterPosition = this.getEmitterPosition();
  87878. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  87879. var distance = direction.length();
  87880. direction.normalize();
  87881. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  87882. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  87883. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  87884. };
  87885. LensFlareSystem.prototype.render = function () {
  87886. if (!this._effect.isReady() || !this._scene.activeCamera)
  87887. return false;
  87888. var engine = this._scene.getEngine();
  87889. var viewport = this._scene.activeCamera.viewport;
  87890. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  87891. // Position
  87892. if (!this.computeEffectivePosition(globalViewport)) {
  87893. return false;
  87894. }
  87895. // Visibility
  87896. if (!this._isVisible()) {
  87897. return false;
  87898. }
  87899. // Intensity
  87900. var awayX;
  87901. var awayY;
  87902. if (this._positionX < this.borderLimit + globalViewport.x) {
  87903. awayX = this.borderLimit + globalViewport.x - this._positionX;
  87904. }
  87905. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  87906. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  87907. }
  87908. else {
  87909. awayX = 0;
  87910. }
  87911. if (this._positionY < this.borderLimit + globalViewport.y) {
  87912. awayY = this.borderLimit + globalViewport.y - this._positionY;
  87913. }
  87914. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  87915. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  87916. }
  87917. else {
  87918. awayY = 0;
  87919. }
  87920. var away = (awayX > awayY) ? awayX : awayY;
  87921. away -= this.viewportBorder;
  87922. if (away > this.borderLimit) {
  87923. away = this.borderLimit;
  87924. }
  87925. var intensity = 1.0 - (away / this.borderLimit);
  87926. if (intensity < 0) {
  87927. return false;
  87928. }
  87929. if (intensity > 1.0) {
  87930. intensity = 1.0;
  87931. }
  87932. if (this.viewportBorder > 0) {
  87933. globalViewport.x += this.viewportBorder;
  87934. globalViewport.y += this.viewportBorder;
  87935. globalViewport.width -= this.viewportBorder * 2;
  87936. globalViewport.height -= this.viewportBorder * 2;
  87937. this._positionX -= this.viewportBorder;
  87938. this._positionY -= this.viewportBorder;
  87939. }
  87940. // Position
  87941. var centerX = globalViewport.x + globalViewport.width / 2;
  87942. var centerY = globalViewport.y + globalViewport.height / 2;
  87943. var distX = centerX - this._positionX;
  87944. var distY = centerY - this._positionY;
  87945. // Effects
  87946. engine.enableEffect(this._effect);
  87947. engine.setState(false);
  87948. engine.setDepthBuffer(false);
  87949. // VBOs
  87950. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  87951. // Flares
  87952. for (var index = 0; index < this.lensFlares.length; index++) {
  87953. var flare = this.lensFlares[index];
  87954. engine.setAlphaMode(flare.alphaMode);
  87955. var x = centerX - (distX * flare.position);
  87956. var y = centerY - (distY * flare.position);
  87957. var cw = flare.size;
  87958. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  87959. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  87960. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  87961. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  87962. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  87963. // Texture
  87964. this._effect.setTexture("textureSampler", flare.texture);
  87965. // Color
  87966. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  87967. // Draw order
  87968. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87969. }
  87970. engine.setDepthBuffer(true);
  87971. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87972. return true;
  87973. };
  87974. LensFlareSystem.prototype.dispose = function () {
  87975. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87976. if (vertexBuffer) {
  87977. vertexBuffer.dispose();
  87978. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87979. }
  87980. if (this._indexBuffer) {
  87981. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87982. this._indexBuffer = null;
  87983. }
  87984. while (this.lensFlares.length) {
  87985. this.lensFlares[0].dispose();
  87986. }
  87987. // Remove from scene
  87988. var index = this._scene.lensFlareSystems.indexOf(this);
  87989. this._scene.lensFlareSystems.splice(index, 1);
  87990. };
  87991. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  87992. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  87993. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  87994. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  87995. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  87996. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  87997. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  87998. var parsedFlare = parsedLensFlareSystem.flares[index];
  87999. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  88000. }
  88001. return lensFlareSystem;
  88002. };
  88003. LensFlareSystem.prototype.serialize = function () {
  88004. var serializationObject = {};
  88005. serializationObject.id = this.id;
  88006. serializationObject.name = this.name;
  88007. serializationObject.emitterId = this.getEmitter().id;
  88008. serializationObject.borderLimit = this.borderLimit;
  88009. serializationObject.flares = [];
  88010. for (var index = 0; index < this.lensFlares.length; index++) {
  88011. var flare = this.lensFlares[index];
  88012. serializationObject.flares.push({
  88013. size: flare.size,
  88014. position: flare.position,
  88015. color: flare.color.asArray(),
  88016. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  88017. });
  88018. }
  88019. return serializationObject;
  88020. };
  88021. return LensFlareSystem;
  88022. }());
  88023. BABYLON.LensFlareSystem = LensFlareSystem;
  88024. })(BABYLON || (BABYLON = {}));
  88025. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  88026. var BABYLON;
  88027. (function (BABYLON) {
  88028. /**
  88029. * This is a holder class for the physics joint created by the physics plugin.
  88030. * It holds a set of functions to control the underlying joint.
  88031. */
  88032. var PhysicsJoint = /** @class */ (function () {
  88033. function PhysicsJoint(type, jointData) {
  88034. this.type = type;
  88035. this.jointData = jointData;
  88036. jointData.nativeParams = jointData.nativeParams || {};
  88037. }
  88038. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  88039. get: function () {
  88040. return this._physicsJoint;
  88041. },
  88042. set: function (newJoint) {
  88043. if (this._physicsJoint) {
  88044. //remove from the wolrd
  88045. }
  88046. this._physicsJoint = newJoint;
  88047. },
  88048. enumerable: true,
  88049. configurable: true
  88050. });
  88051. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  88052. set: function (physicsPlugin) {
  88053. this._physicsPlugin = physicsPlugin;
  88054. },
  88055. enumerable: true,
  88056. configurable: true
  88057. });
  88058. /**
  88059. * Execute a function that is physics-plugin specific.
  88060. * @param {Function} func the function that will be executed.
  88061. * It accepts two parameters: the physics world and the physics joint.
  88062. */
  88063. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  88064. func(this._physicsPlugin.world, this._physicsJoint);
  88065. };
  88066. //TODO check if the native joints are the same
  88067. //Joint Types
  88068. PhysicsJoint.DistanceJoint = 0;
  88069. PhysicsJoint.HingeJoint = 1;
  88070. PhysicsJoint.BallAndSocketJoint = 2;
  88071. PhysicsJoint.WheelJoint = 3;
  88072. PhysicsJoint.SliderJoint = 4;
  88073. //OIMO
  88074. PhysicsJoint.PrismaticJoint = 5;
  88075. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  88076. PhysicsJoint.UniversalJoint = 6;
  88077. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  88078. //Cannon
  88079. //Similar to a Ball-Joint. Different in params
  88080. PhysicsJoint.PointToPointJoint = 8;
  88081. //Cannon only at the moment
  88082. PhysicsJoint.SpringJoint = 9;
  88083. PhysicsJoint.LockJoint = 10;
  88084. return PhysicsJoint;
  88085. }());
  88086. BABYLON.PhysicsJoint = PhysicsJoint;
  88087. /**
  88088. * A class representing a physics distance joint.
  88089. */
  88090. var DistanceJoint = /** @class */ (function (_super) {
  88091. __extends(DistanceJoint, _super);
  88092. function DistanceJoint(jointData) {
  88093. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  88094. }
  88095. /**
  88096. * Update the predefined distance.
  88097. */
  88098. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  88099. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  88100. };
  88101. return DistanceJoint;
  88102. }(PhysicsJoint));
  88103. BABYLON.DistanceJoint = DistanceJoint;
  88104. var MotorEnabledJoint = /** @class */ (function (_super) {
  88105. __extends(MotorEnabledJoint, _super);
  88106. function MotorEnabledJoint(type, jointData) {
  88107. return _super.call(this, type, jointData) || this;
  88108. }
  88109. /**
  88110. * Set the motor values.
  88111. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88112. * @param {number} force the force to apply
  88113. * @param {number} maxForce max force for this motor.
  88114. */
  88115. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  88116. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88117. };
  88118. /**
  88119. * Set the motor's limits.
  88120. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88121. */
  88122. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88123. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88124. };
  88125. return MotorEnabledJoint;
  88126. }(PhysicsJoint));
  88127. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  88128. /**
  88129. * This class represents a single hinge physics joint
  88130. */
  88131. var HingeJoint = /** @class */ (function (_super) {
  88132. __extends(HingeJoint, _super);
  88133. function HingeJoint(jointData) {
  88134. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  88135. }
  88136. /**
  88137. * Set the motor values.
  88138. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88139. * @param {number} force the force to apply
  88140. * @param {number} maxForce max force for this motor.
  88141. */
  88142. HingeJoint.prototype.setMotor = function (force, maxForce) {
  88143. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88144. };
  88145. /**
  88146. * Set the motor's limits.
  88147. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88148. */
  88149. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88150. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88151. };
  88152. return HingeJoint;
  88153. }(MotorEnabledJoint));
  88154. BABYLON.HingeJoint = HingeJoint;
  88155. /**
  88156. * This class represents a dual hinge physics joint (same as wheel joint)
  88157. */
  88158. var Hinge2Joint = /** @class */ (function (_super) {
  88159. __extends(Hinge2Joint, _super);
  88160. function Hinge2Joint(jointData) {
  88161. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  88162. }
  88163. /**
  88164. * Set the motor values.
  88165. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88166. * @param {number} force the force to apply
  88167. * @param {number} maxForce max force for this motor.
  88168. * @param {motorIndex} the motor's index, 0 or 1.
  88169. */
  88170. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  88171. if (motorIndex === void 0) { motorIndex = 0; }
  88172. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  88173. };
  88174. /**
  88175. * Set the motor limits.
  88176. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88177. * @param {number} upperLimit the upper limit
  88178. * @param {number} lowerLimit lower limit
  88179. * @param {motorIndex} the motor's index, 0 or 1.
  88180. */
  88181. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  88182. if (motorIndex === void 0) { motorIndex = 0; }
  88183. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  88184. };
  88185. return Hinge2Joint;
  88186. }(MotorEnabledJoint));
  88187. BABYLON.Hinge2Joint = Hinge2Joint;
  88188. })(BABYLON || (BABYLON = {}));
  88189. //# sourceMappingURL=babylon.physicsJoint.js.map
  88190. var BABYLON;
  88191. (function (BABYLON) {
  88192. var PhysicsImpostor = /** @class */ (function () {
  88193. function PhysicsImpostor(object, type, _options, _scene) {
  88194. if (_options === void 0) { _options = { mass: 0 }; }
  88195. var _this = this;
  88196. this.object = object;
  88197. this.type = type;
  88198. this._options = _options;
  88199. this._scene = _scene;
  88200. this._bodyUpdateRequired = false;
  88201. this._onBeforePhysicsStepCallbacks = new Array();
  88202. this._onAfterPhysicsStepCallbacks = new Array();
  88203. this._onPhysicsCollideCallbacks = [];
  88204. this._deltaPosition = BABYLON.Vector3.Zero();
  88205. this._isDisposed = false;
  88206. //temp variables for parent rotation calculations
  88207. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  88208. this._tmpQuat = new BABYLON.Quaternion();
  88209. this._tmpQuat2 = new BABYLON.Quaternion();
  88210. /**
  88211. * this function is executed by the physics engine.
  88212. */
  88213. this.beforeStep = function () {
  88214. if (!_this._physicsEngine) {
  88215. return;
  88216. }
  88217. _this.object.translate(_this._deltaPosition, -1);
  88218. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  88219. _this.object.computeWorldMatrix(false);
  88220. if (_this.object.parent && _this.object.rotationQuaternion) {
  88221. _this.getParentsRotation();
  88222. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  88223. }
  88224. else {
  88225. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  88226. }
  88227. if (!_this._options.disableBidirectionalTransformation) {
  88228. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  88229. }
  88230. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  88231. func(_this);
  88232. });
  88233. };
  88234. /**
  88235. * this function is executed by the physics engine.
  88236. */
  88237. this.afterStep = function () {
  88238. if (!_this._physicsEngine) {
  88239. return;
  88240. }
  88241. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  88242. func(_this);
  88243. });
  88244. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  88245. // object has now its world rotation. needs to be converted to local.
  88246. if (_this.object.parent && _this.object.rotationQuaternion) {
  88247. _this.getParentsRotation();
  88248. _this._tmpQuat.conjugateInPlace();
  88249. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  88250. }
  88251. // take the position set and make it the absolute position of this object.
  88252. _this.object.setAbsolutePosition(_this.object.position);
  88253. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  88254. _this.object.translate(_this._deltaPosition, 1);
  88255. };
  88256. /**
  88257. * Legacy collision detection event support
  88258. */
  88259. this.onCollideEvent = null;
  88260. //event and body object due to cannon's event-based architecture.
  88261. this.onCollide = function (e) {
  88262. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  88263. return;
  88264. }
  88265. if (!_this._physicsEngine) {
  88266. return;
  88267. }
  88268. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  88269. if (otherImpostor) {
  88270. // Legacy collision detection event support
  88271. if (_this.onCollideEvent) {
  88272. _this.onCollideEvent(_this, otherImpostor);
  88273. }
  88274. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  88275. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  88276. }).forEach(function (obj) {
  88277. obj.callback(_this, otherImpostor);
  88278. });
  88279. }
  88280. };
  88281. //sanity check!
  88282. if (!this.object) {
  88283. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  88284. return;
  88285. }
  88286. //legacy support for old syntax.
  88287. if (!this._scene && object.getScene) {
  88288. this._scene = object.getScene();
  88289. }
  88290. if (!this._scene) {
  88291. return;
  88292. }
  88293. this._physicsEngine = this._scene.getPhysicsEngine();
  88294. if (!this._physicsEngine) {
  88295. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  88296. }
  88297. else {
  88298. //set the object's quaternion, if not set
  88299. if (!this.object.rotationQuaternion) {
  88300. if (this.object.rotation) {
  88301. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  88302. }
  88303. else {
  88304. this.object.rotationQuaternion = new BABYLON.Quaternion();
  88305. }
  88306. }
  88307. //default options params
  88308. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  88309. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  88310. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  88311. this._joints = [];
  88312. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  88313. if (!this.object.parent || this._options.ignoreParent) {
  88314. this._init();
  88315. }
  88316. else if (this.object.parent.physicsImpostor) {
  88317. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  88318. }
  88319. }
  88320. }
  88321. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  88322. get: function () {
  88323. return this._isDisposed;
  88324. },
  88325. enumerable: true,
  88326. configurable: true
  88327. });
  88328. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  88329. get: function () {
  88330. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  88331. },
  88332. set: function (value) {
  88333. this.setMass(value);
  88334. },
  88335. enumerable: true,
  88336. configurable: true
  88337. });
  88338. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  88339. get: function () {
  88340. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  88341. },
  88342. set: function (value) {
  88343. if (!this._physicsEngine) {
  88344. return;
  88345. }
  88346. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  88347. },
  88348. enumerable: true,
  88349. configurable: true
  88350. });
  88351. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  88352. get: function () {
  88353. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  88354. },
  88355. set: function (value) {
  88356. if (!this._physicsEngine) {
  88357. return;
  88358. }
  88359. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  88360. },
  88361. enumerable: true,
  88362. configurable: true
  88363. });
  88364. /**
  88365. * This function will completly initialize this impostor.
  88366. * It will create a new body - but only if this mesh has no parent.
  88367. * If it has, this impostor will not be used other than to define the impostor
  88368. * of the child mesh.
  88369. * @hidden
  88370. */
  88371. PhysicsImpostor.prototype._init = function () {
  88372. if (!this._physicsEngine) {
  88373. return;
  88374. }
  88375. this._physicsEngine.removeImpostor(this);
  88376. this.physicsBody = null;
  88377. this._parent = this._parent || this._getPhysicsParent();
  88378. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  88379. this._physicsEngine.addImpostor(this);
  88380. }
  88381. };
  88382. PhysicsImpostor.prototype._getPhysicsParent = function () {
  88383. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  88384. var parentMesh = this.object.parent;
  88385. return parentMesh.physicsImpostor;
  88386. }
  88387. return null;
  88388. };
  88389. /**
  88390. * Should a new body be generated.
  88391. */
  88392. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  88393. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  88394. };
  88395. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  88396. this.forceUpdate();
  88397. };
  88398. /**
  88399. * Force a regeneration of this or the parent's impostor's body.
  88400. * Use under cautious - This will remove all joints already implemented.
  88401. */
  88402. PhysicsImpostor.prototype.forceUpdate = function () {
  88403. this._init();
  88404. if (this.parent && !this._options.ignoreParent) {
  88405. this.parent.forceUpdate();
  88406. }
  88407. };
  88408. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  88409. /*public get mesh(): AbstractMesh {
  88410. return this._mesh;
  88411. }*/
  88412. /**
  88413. * Gets the body that holds this impostor. Either its own, or its parent.
  88414. */
  88415. get: function () {
  88416. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  88417. },
  88418. /**
  88419. * Set the physics body. Used mainly by the physics engine/plugin
  88420. */
  88421. set: function (physicsBody) {
  88422. if (this._physicsBody && this._physicsEngine) {
  88423. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  88424. }
  88425. this._physicsBody = physicsBody;
  88426. this.resetUpdateFlags();
  88427. },
  88428. enumerable: true,
  88429. configurable: true
  88430. });
  88431. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  88432. get: function () {
  88433. return !this._options.ignoreParent && this._parent ? this._parent : null;
  88434. },
  88435. set: function (value) {
  88436. this._parent = value;
  88437. },
  88438. enumerable: true,
  88439. configurable: true
  88440. });
  88441. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  88442. this._bodyUpdateRequired = false;
  88443. };
  88444. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  88445. if (this.object.getBoundingInfo) {
  88446. var q = this.object.rotationQuaternion;
  88447. //reset rotation
  88448. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  88449. //calculate the world matrix with no rotation
  88450. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88451. var boundingInfo = this.object.getBoundingInfo();
  88452. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  88453. //bring back the rotation
  88454. this.object.rotationQuaternion = q;
  88455. //calculate the world matrix with the new rotation
  88456. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88457. return size;
  88458. }
  88459. else {
  88460. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  88461. }
  88462. };
  88463. PhysicsImpostor.prototype.getObjectCenter = function () {
  88464. if (this.object.getBoundingInfo) {
  88465. var boundingInfo = this.object.getBoundingInfo();
  88466. return boundingInfo.boundingBox.centerWorld;
  88467. }
  88468. else {
  88469. return this.object.position;
  88470. }
  88471. };
  88472. /**
  88473. * Get a specific parametes from the options parameter.
  88474. */
  88475. PhysicsImpostor.prototype.getParam = function (paramName) {
  88476. return this._options[paramName];
  88477. };
  88478. /**
  88479. * Sets a specific parameter in the options given to the physics plugin
  88480. */
  88481. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  88482. this._options[paramName] = value;
  88483. this._bodyUpdateRequired = true;
  88484. };
  88485. /**
  88486. * Specifically change the body's mass option. Won't recreate the physics body object
  88487. */
  88488. PhysicsImpostor.prototype.setMass = function (mass) {
  88489. if (this.getParam("mass") !== mass) {
  88490. this.setParam("mass", mass);
  88491. }
  88492. if (this._physicsEngine) {
  88493. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  88494. }
  88495. };
  88496. PhysicsImpostor.prototype.getLinearVelocity = function () {
  88497. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  88498. };
  88499. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  88500. if (this._physicsEngine) {
  88501. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  88502. }
  88503. };
  88504. PhysicsImpostor.prototype.getAngularVelocity = function () {
  88505. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  88506. };
  88507. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  88508. if (this._physicsEngine) {
  88509. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  88510. }
  88511. };
  88512. /**
  88513. * Execute a function with the physics plugin native code.
  88514. * Provide a function the will have two variables - the world object and the physics body object.
  88515. */
  88516. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  88517. if (this._physicsEngine) {
  88518. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  88519. }
  88520. };
  88521. /**
  88522. * Register a function that will be executed before the physics world is stepping forward.
  88523. */
  88524. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  88525. this._onBeforePhysicsStepCallbacks.push(func);
  88526. };
  88527. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  88528. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  88529. if (index > -1) {
  88530. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  88531. }
  88532. else {
  88533. BABYLON.Tools.Warn("Function to remove was not found");
  88534. }
  88535. };
  88536. /**
  88537. * Register a function that will be executed after the physics step
  88538. */
  88539. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  88540. this._onAfterPhysicsStepCallbacks.push(func);
  88541. };
  88542. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  88543. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  88544. if (index > -1) {
  88545. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  88546. }
  88547. else {
  88548. BABYLON.Tools.Warn("Function to remove was not found");
  88549. }
  88550. };
  88551. /**
  88552. * register a function that will be executed when this impostor collides against a different body.
  88553. */
  88554. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  88555. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88556. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  88557. };
  88558. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  88559. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88560. var index = -1;
  88561. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  88562. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  88563. // chcek the arrays match
  88564. var sameList = cbDef.otherImpostors.every(function (impostor) {
  88565. return collidedAgainstList.indexOf(impostor) > -1;
  88566. });
  88567. if (sameList) {
  88568. index = idx;
  88569. }
  88570. return sameList;
  88571. }
  88572. return false;
  88573. });
  88574. if (found) {
  88575. this._onPhysicsCollideCallbacks.splice(index, 1);
  88576. }
  88577. else {
  88578. BABYLON.Tools.Warn("Function to remove was not found");
  88579. }
  88580. };
  88581. PhysicsImpostor.prototype.getParentsRotation = function () {
  88582. var parent = this.object.parent;
  88583. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  88584. while (parent) {
  88585. if (parent.rotationQuaternion) {
  88586. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  88587. }
  88588. else {
  88589. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  88590. }
  88591. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  88592. parent = parent.parent;
  88593. }
  88594. return this._tmpQuat;
  88595. };
  88596. /**
  88597. * Apply a force
  88598. */
  88599. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  88600. if (this._physicsEngine) {
  88601. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  88602. }
  88603. return this;
  88604. };
  88605. /**
  88606. * Apply an impulse
  88607. */
  88608. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  88609. if (this._physicsEngine) {
  88610. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  88611. }
  88612. return this;
  88613. };
  88614. /**
  88615. * A help function to create a joint.
  88616. */
  88617. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  88618. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  88619. this.addJoint(otherImpostor, joint);
  88620. return this;
  88621. };
  88622. /**
  88623. * Add a joint to this impostor with a different impostor.
  88624. */
  88625. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  88626. this._joints.push({
  88627. otherImpostor: otherImpostor,
  88628. joint: joint
  88629. });
  88630. if (this._physicsEngine) {
  88631. this._physicsEngine.addJoint(this, otherImpostor, joint);
  88632. }
  88633. return this;
  88634. };
  88635. /**
  88636. * Will keep this body still, in a sleep mode.
  88637. */
  88638. PhysicsImpostor.prototype.sleep = function () {
  88639. if (this._physicsEngine) {
  88640. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  88641. }
  88642. return this;
  88643. };
  88644. /**
  88645. * Wake the body up.
  88646. */
  88647. PhysicsImpostor.prototype.wakeUp = function () {
  88648. if (this._physicsEngine) {
  88649. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  88650. }
  88651. return this;
  88652. };
  88653. PhysicsImpostor.prototype.clone = function (newObject) {
  88654. if (!newObject)
  88655. return null;
  88656. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  88657. };
  88658. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  88659. var _this = this;
  88660. //no dispose if no physics engine is available.
  88661. if (!this._physicsEngine) {
  88662. return;
  88663. }
  88664. this._joints.forEach(function (j) {
  88665. if (_this._physicsEngine) {
  88666. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  88667. }
  88668. });
  88669. //dispose the physics body
  88670. this._physicsEngine.removeImpostor(this);
  88671. if (this.parent) {
  88672. this.parent.forceUpdate();
  88673. }
  88674. else {
  88675. /*this._object.getChildMeshes().forEach(function(mesh) {
  88676. if (mesh.physicsImpostor) {
  88677. if (disposeChildren) {
  88678. mesh.physicsImpostor.dispose();
  88679. mesh.physicsImpostor = null;
  88680. }
  88681. }
  88682. })*/
  88683. }
  88684. this._isDisposed = true;
  88685. };
  88686. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  88687. this._deltaPosition.copyFrom(position);
  88688. };
  88689. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  88690. if (!this._deltaRotation) {
  88691. this._deltaRotation = new BABYLON.Quaternion();
  88692. }
  88693. this._deltaRotation.copyFrom(rotation);
  88694. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  88695. };
  88696. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  88697. if (this._physicsEngine) {
  88698. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  88699. }
  88700. return this;
  88701. };
  88702. PhysicsImpostor.prototype.getRadius = function () {
  88703. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  88704. };
  88705. /**
  88706. * Sync a bone with this impostor
  88707. * @param bone The bone to sync to the impostor.
  88708. * @param boneMesh The mesh that the bone is influencing.
  88709. * @param jointPivot The pivot of the joint / bone in local space.
  88710. * @param distToJoint Optional distance from the impostor to the joint.
  88711. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88712. */
  88713. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  88714. var tempVec = PhysicsImpostor._tmpVecs[0];
  88715. var mesh = this.object;
  88716. if (mesh.rotationQuaternion) {
  88717. if (adjustRotation) {
  88718. var tempQuat = PhysicsImpostor._tmpQuat;
  88719. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  88720. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  88721. }
  88722. else {
  88723. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  88724. }
  88725. }
  88726. tempVec.x = 0;
  88727. tempVec.y = 0;
  88728. tempVec.z = 0;
  88729. if (jointPivot) {
  88730. tempVec.x = jointPivot.x;
  88731. tempVec.y = jointPivot.y;
  88732. tempVec.z = jointPivot.z;
  88733. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  88734. if (distToJoint === undefined || distToJoint === null) {
  88735. distToJoint = jointPivot.length();
  88736. }
  88737. tempVec.x *= distToJoint;
  88738. tempVec.y *= distToJoint;
  88739. tempVec.z *= distToJoint;
  88740. }
  88741. if (bone.getParent()) {
  88742. tempVec.addInPlace(mesh.getAbsolutePosition());
  88743. bone.setAbsolutePosition(tempVec, boneMesh);
  88744. }
  88745. else {
  88746. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  88747. boneMesh.position.x -= tempVec.x;
  88748. boneMesh.position.y -= tempVec.y;
  88749. boneMesh.position.z -= tempVec.z;
  88750. }
  88751. };
  88752. /**
  88753. * Sync impostor to a bone
  88754. * @param bone The bone that the impostor will be synced to.
  88755. * @param boneMesh The mesh that the bone is influencing.
  88756. * @param jointPivot The pivot of the joint / bone in local space.
  88757. * @param distToJoint Optional distance from the impostor to the joint.
  88758. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88759. * @param boneAxis Optional vector3 axis the bone is aligned with
  88760. */
  88761. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  88762. var mesh = this.object;
  88763. if (mesh.rotationQuaternion) {
  88764. if (adjustRotation) {
  88765. var tempQuat = PhysicsImpostor._tmpQuat;
  88766. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  88767. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  88768. }
  88769. else {
  88770. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  88771. }
  88772. }
  88773. var pos = PhysicsImpostor._tmpVecs[0];
  88774. var boneDir = PhysicsImpostor._tmpVecs[1];
  88775. if (!boneAxis) {
  88776. boneAxis = PhysicsImpostor._tmpVecs[2];
  88777. boneAxis.x = 0;
  88778. boneAxis.y = 1;
  88779. boneAxis.z = 0;
  88780. }
  88781. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  88782. bone.getAbsolutePositionToRef(boneMesh, pos);
  88783. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  88784. distToJoint = jointPivot.length();
  88785. }
  88786. if (distToJoint !== undefined && distToJoint !== null) {
  88787. pos.x += boneDir.x * distToJoint;
  88788. pos.y += boneDir.y * distToJoint;
  88789. pos.z += boneDir.z * distToJoint;
  88790. }
  88791. mesh.setAbsolutePosition(pos);
  88792. };
  88793. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  88794. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  88795. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88796. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  88797. //Impostor types
  88798. PhysicsImpostor.NoImpostor = 0;
  88799. PhysicsImpostor.SphereImpostor = 1;
  88800. PhysicsImpostor.BoxImpostor = 2;
  88801. PhysicsImpostor.PlaneImpostor = 3;
  88802. PhysicsImpostor.MeshImpostor = 4;
  88803. PhysicsImpostor.CylinderImpostor = 7;
  88804. PhysicsImpostor.ParticleImpostor = 8;
  88805. PhysicsImpostor.HeightmapImpostor = 9;
  88806. return PhysicsImpostor;
  88807. }());
  88808. BABYLON.PhysicsImpostor = PhysicsImpostor;
  88809. })(BABYLON || (BABYLON = {}));
  88810. //# sourceMappingURL=babylon.physicsImpostor.js.map
  88811. var BABYLON;
  88812. (function (BABYLON) {
  88813. var PhysicsEngine = /** @class */ (function () {
  88814. function PhysicsEngine(gravity, _physicsPlugin) {
  88815. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  88816. this._physicsPlugin = _physicsPlugin;
  88817. //new methods and parameters
  88818. this._impostors = [];
  88819. this._joints = [];
  88820. if (!this._physicsPlugin.isSupported()) {
  88821. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  88822. + "Please make sure it is included.");
  88823. }
  88824. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  88825. this.setGravity(gravity);
  88826. this.setTimeStep();
  88827. }
  88828. PhysicsEngine.prototype.setGravity = function (gravity) {
  88829. this.gravity = gravity;
  88830. this._physicsPlugin.setGravity(this.gravity);
  88831. };
  88832. /**
  88833. * Set the time step of the physics engine.
  88834. * default is 1/60.
  88835. * To slow it down, enter 1/600 for example.
  88836. * To speed it up, 1/30
  88837. * @param {number} newTimeStep the new timestep to apply to this world.
  88838. */
  88839. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  88840. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  88841. this._physicsPlugin.setTimeStep(newTimeStep);
  88842. };
  88843. /**
  88844. * Get the time step of the physics engine.
  88845. */
  88846. PhysicsEngine.prototype.getTimeStep = function () {
  88847. return this._physicsPlugin.getTimeStep();
  88848. };
  88849. PhysicsEngine.prototype.dispose = function () {
  88850. this._impostors.forEach(function (impostor) {
  88851. impostor.dispose();
  88852. });
  88853. this._physicsPlugin.dispose();
  88854. };
  88855. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  88856. return this._physicsPlugin.name;
  88857. };
  88858. /**
  88859. * Adding a new impostor for the impostor tracking.
  88860. * This will be done by the impostor itself.
  88861. * @param {PhysicsImpostor} impostor the impostor to add
  88862. */
  88863. PhysicsEngine.prototype.addImpostor = function (impostor) {
  88864. impostor.uniqueId = this._impostors.push(impostor);
  88865. //if no parent, generate the body
  88866. if (!impostor.parent) {
  88867. this._physicsPlugin.generatePhysicsBody(impostor);
  88868. }
  88869. };
  88870. /**
  88871. * Remove an impostor from the engine.
  88872. * This impostor and its mesh will not longer be updated by the physics engine.
  88873. * @param {PhysicsImpostor} impostor the impostor to remove
  88874. */
  88875. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  88876. var index = this._impostors.indexOf(impostor);
  88877. if (index > -1) {
  88878. var removed = this._impostors.splice(index, 1);
  88879. //Is it needed?
  88880. if (removed.length) {
  88881. //this will also remove it from the world.
  88882. removed[0].physicsBody = null;
  88883. }
  88884. }
  88885. };
  88886. /**
  88887. * Add a joint to the physics engine
  88888. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  88889. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  88890. * @param {PhysicsJoint} the joint that will connect both impostors.
  88891. */
  88892. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  88893. var impostorJoint = {
  88894. mainImpostor: mainImpostor,
  88895. connectedImpostor: connectedImpostor,
  88896. joint: joint
  88897. };
  88898. joint.physicsPlugin = this._physicsPlugin;
  88899. this._joints.push(impostorJoint);
  88900. this._physicsPlugin.generateJoint(impostorJoint);
  88901. };
  88902. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  88903. var matchingJoints = this._joints.filter(function (impostorJoint) {
  88904. return (impostorJoint.connectedImpostor === connectedImpostor
  88905. && impostorJoint.joint === joint
  88906. && impostorJoint.mainImpostor === mainImpostor);
  88907. });
  88908. if (matchingJoints.length) {
  88909. this._physicsPlugin.removeJoint(matchingJoints[0]);
  88910. //TODO remove it from the list as well
  88911. }
  88912. };
  88913. /**
  88914. * Called by the scene. no need to call it.
  88915. * @hidden
  88916. */
  88917. PhysicsEngine.prototype._step = function (delta) {
  88918. var _this = this;
  88919. //check if any mesh has no body / requires an update
  88920. this._impostors.forEach(function (impostor) {
  88921. if (impostor.isBodyInitRequired()) {
  88922. _this._physicsPlugin.generatePhysicsBody(impostor);
  88923. }
  88924. });
  88925. if (delta > 0.1) {
  88926. delta = 0.1;
  88927. }
  88928. else if (delta <= 0) {
  88929. delta = 1.0 / 60.0;
  88930. }
  88931. this._physicsPlugin.executeStep(delta, this._impostors);
  88932. };
  88933. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  88934. return this._physicsPlugin;
  88935. };
  88936. PhysicsEngine.prototype.getImpostors = function () {
  88937. return this._impostors;
  88938. };
  88939. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  88940. for (var i = 0; i < this._impostors.length; ++i) {
  88941. if (this._impostors[i].object === object) {
  88942. return this._impostors[i];
  88943. }
  88944. }
  88945. return null;
  88946. };
  88947. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  88948. for (var i = 0; i < this._impostors.length; ++i) {
  88949. if (this._impostors[i].physicsBody === body) {
  88950. return this._impostors[i];
  88951. }
  88952. }
  88953. return null;
  88954. };
  88955. // Statics
  88956. PhysicsEngine.Epsilon = 0.001;
  88957. return PhysicsEngine;
  88958. }());
  88959. BABYLON.PhysicsEngine = PhysicsEngine;
  88960. })(BABYLON || (BABYLON = {}));
  88961. //# sourceMappingURL=babylon.physicsEngine.js.map
  88962. var BABYLON;
  88963. (function (BABYLON) {
  88964. var PhysicsHelper = /** @class */ (function () {
  88965. function PhysicsHelper(scene) {
  88966. this._scene = scene;
  88967. this._physicsEngine = this._scene.getPhysicsEngine();
  88968. if (!this._physicsEngine) {
  88969. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  88970. }
  88971. }
  88972. /**
  88973. * @param {Vector3} origin the origin of the explosion
  88974. * @param {number} radius the explosion radius
  88975. * @param {number} strength the explosion strength
  88976. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  88977. */
  88978. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  88979. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88980. if (!this._physicsEngine) {
  88981. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  88982. return null;
  88983. }
  88984. var impostors = this._physicsEngine.getImpostors();
  88985. if (impostors.length === 0) {
  88986. return null;
  88987. }
  88988. var event = new PhysicsRadialExplosionEvent(this._scene);
  88989. impostors.forEach(function (impostor) {
  88990. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  88991. if (!impostorForceAndContactPoint) {
  88992. return;
  88993. }
  88994. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88995. });
  88996. event.dispose(false);
  88997. return event;
  88998. };
  88999. /**
  89000. * @param {Vector3} origin the origin of the explosion
  89001. * @param {number} radius the explosion radius
  89002. * @param {number} strength the explosion strength
  89003. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89004. */
  89005. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  89006. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89007. if (!this._physicsEngine) {
  89008. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89009. return null;
  89010. }
  89011. var impostors = this._physicsEngine.getImpostors();
  89012. if (impostors.length === 0) {
  89013. return null;
  89014. }
  89015. var event = new PhysicsRadialExplosionEvent(this._scene);
  89016. impostors.forEach(function (impostor) {
  89017. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89018. if (!impostorForceAndContactPoint) {
  89019. return;
  89020. }
  89021. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89022. });
  89023. event.dispose(false);
  89024. return event;
  89025. };
  89026. /**
  89027. * @param {Vector3} origin the origin of the explosion
  89028. * @param {number} radius the explosion radius
  89029. * @param {number} strength the explosion strength
  89030. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89031. */
  89032. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  89033. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89034. if (!this._physicsEngine) {
  89035. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89036. return null;
  89037. }
  89038. var impostors = this._physicsEngine.getImpostors();
  89039. if (impostors.length === 0) {
  89040. return null;
  89041. }
  89042. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  89043. event.dispose(false);
  89044. return event;
  89045. };
  89046. /**
  89047. * @param {Vector3} origin the origin of the updraft
  89048. * @param {number} radius the radius of the updraft
  89049. * @param {number} strength the strength of the updraft
  89050. * @param {number} height the height of the updraft
  89051. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  89052. */
  89053. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  89054. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  89055. if (!this._physicsEngine) {
  89056. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89057. return null;
  89058. }
  89059. if (this._physicsEngine.getImpostors().length === 0) {
  89060. return null;
  89061. }
  89062. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  89063. event.dispose(false);
  89064. return event;
  89065. };
  89066. /**
  89067. * @param {Vector3} origin the of the vortex
  89068. * @param {number} radius the radius of the vortex
  89069. * @param {number} strength the strength of the vortex
  89070. * @param {number} height the height of the vortex
  89071. */
  89072. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  89073. if (!this._physicsEngine) {
  89074. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89075. return null;
  89076. }
  89077. if (this._physicsEngine.getImpostors().length === 0) {
  89078. return null;
  89079. }
  89080. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  89081. event.dispose(false);
  89082. return event;
  89083. };
  89084. return PhysicsHelper;
  89085. }());
  89086. BABYLON.PhysicsHelper = PhysicsHelper;
  89087. /***** Radial explosion *****/
  89088. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  89089. function PhysicsRadialExplosionEvent(scene) {
  89090. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  89091. this._rays = [];
  89092. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  89093. this._scene = scene;
  89094. }
  89095. /**
  89096. * Returns the data related to the radial explosion event (sphere & rays).
  89097. * @returns {PhysicsRadialExplosionEventData}
  89098. */
  89099. PhysicsRadialExplosionEvent.prototype.getData = function () {
  89100. this._dataFetched = true;
  89101. return {
  89102. sphere: this._sphere,
  89103. rays: this._rays,
  89104. };
  89105. };
  89106. /**
  89107. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  89108. * @param impostor
  89109. * @param {Vector3} origin the origin of the explosion
  89110. * @param {number} radius the explosion radius
  89111. * @param {number} strength the explosion strength
  89112. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  89113. * @returns {Nullable<PhysicsForceAndContactPoint>}
  89114. */
  89115. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  89116. if (impostor.mass === 0) {
  89117. return null;
  89118. }
  89119. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  89120. return null;
  89121. }
  89122. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89123. return null;
  89124. }
  89125. var impostorObjectCenter = impostor.getObjectCenter();
  89126. var direction = impostorObjectCenter.subtract(origin);
  89127. var ray = new BABYLON.Ray(origin, direction, radius);
  89128. this._rays.push(ray);
  89129. var hit = ray.intersectsMesh(impostor.object);
  89130. var contactPoint = hit.pickedPoint;
  89131. if (!contactPoint) {
  89132. return null;
  89133. }
  89134. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  89135. if (distanceFromOrigin > radius) {
  89136. return null;
  89137. }
  89138. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  89139. ? strength
  89140. : strength * (1 - (distanceFromOrigin / radius));
  89141. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89142. return { force: force, contactPoint: contactPoint };
  89143. };
  89144. /**
  89145. * Disposes the sphere.
  89146. * @param {bolean} force
  89147. */
  89148. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  89149. var _this = this;
  89150. if (force === void 0) { force = true; }
  89151. if (force) {
  89152. this._sphere.dispose();
  89153. }
  89154. else {
  89155. setTimeout(function () {
  89156. if (!_this._dataFetched) {
  89157. _this._sphere.dispose();
  89158. }
  89159. }, 0);
  89160. }
  89161. };
  89162. /*** Helpers ***/
  89163. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  89164. if (!this._sphere) {
  89165. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  89166. this._sphere.isVisible = false;
  89167. }
  89168. };
  89169. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  89170. var impostorObject = impostor.object;
  89171. this._prepareSphere();
  89172. this._sphere.position = origin;
  89173. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  89174. this._sphere._updateBoundingInfo();
  89175. this._sphere.computeWorldMatrix(true);
  89176. return this._sphere.intersectsMesh(impostorObject, true);
  89177. };
  89178. return PhysicsRadialExplosionEvent;
  89179. }());
  89180. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  89181. /***** Gravitational Field *****/
  89182. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  89183. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  89184. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89185. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89186. this._physicsHelper = physicsHelper;
  89187. this._scene = scene;
  89188. this._origin = origin;
  89189. this._radius = radius;
  89190. this._strength = strength;
  89191. this._falloff = falloff;
  89192. this._tickCallback = this._tick.bind(this);
  89193. }
  89194. /**
  89195. * Returns the data related to the gravitational field event (sphere).
  89196. * @returns {PhysicsGravitationalFieldEventData}
  89197. */
  89198. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  89199. this._dataFetched = true;
  89200. return {
  89201. sphere: this._sphere,
  89202. };
  89203. };
  89204. /**
  89205. * Enables the gravitational field.
  89206. */
  89207. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  89208. this._tickCallback.call(this);
  89209. this._scene.registerBeforeRender(this._tickCallback);
  89210. };
  89211. /**
  89212. * Disables the gravitational field.
  89213. */
  89214. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  89215. this._scene.unregisterBeforeRender(this._tickCallback);
  89216. };
  89217. /**
  89218. * Disposes the sphere.
  89219. * @param {bolean} force
  89220. */
  89221. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  89222. var _this = this;
  89223. if (force === void 0) { force = true; }
  89224. if (force) {
  89225. this._sphere.dispose();
  89226. }
  89227. else {
  89228. setTimeout(function () {
  89229. if (!_this._dataFetched) {
  89230. _this._sphere.dispose();
  89231. }
  89232. }, 0);
  89233. }
  89234. };
  89235. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  89236. // Since the params won't change, we fetch the event only once
  89237. if (this._sphere) {
  89238. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89239. }
  89240. else {
  89241. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89242. if (radialExplosionEvent) {
  89243. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  89244. }
  89245. }
  89246. };
  89247. return PhysicsGravitationalFieldEvent;
  89248. }());
  89249. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  89250. /***** Updraft *****/
  89251. var PhysicsUpdraftEvent = /** @class */ (function () {
  89252. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  89253. this._scene = _scene;
  89254. this._origin = _origin;
  89255. this._radius = _radius;
  89256. this._strength = _strength;
  89257. this._height = _height;
  89258. this._updraftMode = _updraftMode;
  89259. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89260. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  89261. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89262. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89263. this._physicsEngine = this._scene.getPhysicsEngine();
  89264. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89265. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89266. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89267. this._originDirection = this._origin.subtract(this._originTop).normalize();
  89268. }
  89269. this._tickCallback = this._tick.bind(this);
  89270. }
  89271. /**
  89272. * Returns the data related to the updraft event (cylinder).
  89273. * @returns {PhysicsUpdraftEventData}
  89274. */
  89275. PhysicsUpdraftEvent.prototype.getData = function () {
  89276. this._dataFetched = true;
  89277. return {
  89278. cylinder: this._cylinder,
  89279. };
  89280. };
  89281. /**
  89282. * Enables the updraft.
  89283. */
  89284. PhysicsUpdraftEvent.prototype.enable = function () {
  89285. this._tickCallback.call(this);
  89286. this._scene.registerBeforeRender(this._tickCallback);
  89287. };
  89288. /**
  89289. * Disables the cortex.
  89290. */
  89291. PhysicsUpdraftEvent.prototype.disable = function () {
  89292. this._scene.unregisterBeforeRender(this._tickCallback);
  89293. };
  89294. /**
  89295. * Disposes the sphere.
  89296. * @param {bolean} force
  89297. */
  89298. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  89299. var _this = this;
  89300. if (force === void 0) { force = true; }
  89301. if (force) {
  89302. this._cylinder.dispose();
  89303. }
  89304. else {
  89305. setTimeout(function () {
  89306. if (!_this._dataFetched) {
  89307. _this._cylinder.dispose();
  89308. }
  89309. }, 0);
  89310. }
  89311. };
  89312. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89313. if (impostor.mass === 0) {
  89314. return null;
  89315. }
  89316. if (!this._intersectsWithCylinder(impostor)) {
  89317. return null;
  89318. }
  89319. var impostorObjectCenter = impostor.getObjectCenter();
  89320. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89321. var direction = this._originDirection;
  89322. }
  89323. else {
  89324. var direction = impostorObjectCenter.subtract(this._originTop);
  89325. }
  89326. var multiplier = this._strength * -1;
  89327. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89328. return { force: force, contactPoint: impostorObjectCenter };
  89329. };
  89330. PhysicsUpdraftEvent.prototype._tick = function () {
  89331. var _this = this;
  89332. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89333. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89334. if (!impostorForceAndContactPoint) {
  89335. return;
  89336. }
  89337. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89338. });
  89339. };
  89340. /*** Helpers ***/
  89341. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  89342. if (!this._cylinder) {
  89343. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  89344. height: this._height,
  89345. diameter: this._radius * 2,
  89346. }, this._scene);
  89347. this._cylinder.isVisible = false;
  89348. }
  89349. };
  89350. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  89351. var impostorObject = impostor.object;
  89352. this._prepareCylinder();
  89353. this._cylinder.position = this._cylinderPosition;
  89354. return this._cylinder.intersectsMesh(impostorObject, true);
  89355. };
  89356. return PhysicsUpdraftEvent;
  89357. }());
  89358. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  89359. /***** Vortex *****/
  89360. var PhysicsVortexEvent = /** @class */ (function () {
  89361. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  89362. this._scene = _scene;
  89363. this._origin = _origin;
  89364. this._radius = _radius;
  89365. this._strength = _strength;
  89366. this._height = _height;
  89367. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89368. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  89369. this._updraftMultiplier = 0.02;
  89370. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89371. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89372. this._physicsEngine = this._scene.getPhysicsEngine();
  89373. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89374. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89375. this._tickCallback = this._tick.bind(this);
  89376. }
  89377. /**
  89378. * Returns the data related to the vortex event (cylinder).
  89379. * @returns {PhysicsVortexEventData}
  89380. */
  89381. PhysicsVortexEvent.prototype.getData = function () {
  89382. this._dataFetched = true;
  89383. return {
  89384. cylinder: this._cylinder,
  89385. };
  89386. };
  89387. /**
  89388. * Enables the vortex.
  89389. */
  89390. PhysicsVortexEvent.prototype.enable = function () {
  89391. this._tickCallback.call(this);
  89392. this._scene.registerBeforeRender(this._tickCallback);
  89393. };
  89394. /**
  89395. * Disables the cortex.
  89396. */
  89397. PhysicsVortexEvent.prototype.disable = function () {
  89398. this._scene.unregisterBeforeRender(this._tickCallback);
  89399. };
  89400. /**
  89401. * Disposes the sphere.
  89402. * @param {bolean} force
  89403. */
  89404. PhysicsVortexEvent.prototype.dispose = function (force) {
  89405. var _this = this;
  89406. if (force === void 0) { force = true; }
  89407. if (force) {
  89408. this._cylinder.dispose();
  89409. }
  89410. else {
  89411. setTimeout(function () {
  89412. if (!_this._dataFetched) {
  89413. _this._cylinder.dispose();
  89414. }
  89415. }, 0);
  89416. }
  89417. };
  89418. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89419. if (impostor.mass === 0) {
  89420. return null;
  89421. }
  89422. if (!this._intersectsWithCylinder(impostor)) {
  89423. return null;
  89424. }
  89425. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89426. return null;
  89427. }
  89428. var impostorObjectCenter = impostor.getObjectCenter();
  89429. 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)
  89430. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  89431. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  89432. var hit = ray.intersectsMesh(impostor.object);
  89433. var contactPoint = hit.pickedPoint;
  89434. if (!contactPoint) {
  89435. return null;
  89436. }
  89437. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  89438. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  89439. var directionToOrigin = contactPoint.normalize();
  89440. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89441. directionToOrigin = directionToOrigin.negate();
  89442. }
  89443. // TODO: find a more physically based solution
  89444. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89445. var forceX = directionToOrigin.x * this._strength / 8;
  89446. var forceY = directionToOrigin.y * this._updraftMultiplier;
  89447. var forceZ = directionToOrigin.z * this._strength / 8;
  89448. }
  89449. else {
  89450. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  89451. var forceY = this._originTop.y * this._updraftMultiplier;
  89452. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  89453. }
  89454. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  89455. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  89456. return { force: force, contactPoint: impostorObjectCenter };
  89457. };
  89458. PhysicsVortexEvent.prototype._tick = function () {
  89459. var _this = this;
  89460. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89461. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89462. if (!impostorForceAndContactPoint) {
  89463. return;
  89464. }
  89465. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89466. });
  89467. };
  89468. /*** Helpers ***/
  89469. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  89470. if (!this._cylinder) {
  89471. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  89472. height: this._height,
  89473. diameter: this._radius * 2,
  89474. }, this._scene);
  89475. this._cylinder.isVisible = false;
  89476. }
  89477. };
  89478. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  89479. var impostorObject = impostor.object;
  89480. this._prepareCylinder();
  89481. this._cylinder.position = this._cylinderPosition;
  89482. return this._cylinder.intersectsMesh(impostorObject, true);
  89483. };
  89484. return PhysicsVortexEvent;
  89485. }());
  89486. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  89487. /***** Enums *****/
  89488. /**
  89489. * The strenght of the force in correspondence to the distance of the affected object
  89490. */
  89491. var PhysicsRadialImpulseFalloff;
  89492. (function (PhysicsRadialImpulseFalloff) {
  89493. /** Defines that impulse is constant in strength across it's whole radius */
  89494. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  89495. /** DEfines that impulse gets weaker if it's further from the origin */
  89496. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  89497. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  89498. /**
  89499. * The strenght of the force in correspondence to the distance of the affected object
  89500. */
  89501. var PhysicsUpdraftMode;
  89502. (function (PhysicsUpdraftMode) {
  89503. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  89504. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  89505. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  89506. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  89507. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  89508. })(BABYLON || (BABYLON = {}));
  89509. //# sourceMappingURL=babylon.physicsHelper.js.map
  89510. var BABYLON;
  89511. (function (BABYLON) {
  89512. var CannonJSPlugin = /** @class */ (function () {
  89513. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  89514. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  89515. if (iterations === void 0) { iterations = 10; }
  89516. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  89517. this.name = "CannonJSPlugin";
  89518. this._physicsMaterials = new Array();
  89519. this._fixedTimeStep = 1 / 60;
  89520. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  89521. this.BJSCANNON = CANNON;
  89522. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  89523. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  89524. this._tmpPosition = BABYLON.Vector3.Zero();
  89525. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  89526. this._tmpUnityRotation = new BABYLON.Quaternion();
  89527. if (!this.isSupported()) {
  89528. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  89529. return;
  89530. }
  89531. this._extendNamespace();
  89532. this.world = new this.BJSCANNON.World();
  89533. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  89534. this.world.solver.iterations = iterations;
  89535. }
  89536. CannonJSPlugin.prototype.setGravity = function (gravity) {
  89537. this.world.gravity.copy(gravity);
  89538. };
  89539. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  89540. this._fixedTimeStep = timeStep;
  89541. };
  89542. CannonJSPlugin.prototype.getTimeStep = function () {
  89543. return this._fixedTimeStep;
  89544. };
  89545. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  89546. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  89547. };
  89548. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89549. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89550. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89551. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  89552. };
  89553. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89554. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89555. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89556. impostor.physicsBody.applyForce(impulse, worldPoint);
  89557. };
  89558. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89559. //parent-child relationship. Does this impostor has a parent impostor?
  89560. if (impostor.parent) {
  89561. if (impostor.physicsBody) {
  89562. this.removePhysicsBody(impostor);
  89563. //TODO is that needed?
  89564. impostor.forceUpdate();
  89565. }
  89566. return;
  89567. }
  89568. //should a new body be created for this impostor?
  89569. if (impostor.isBodyInitRequired()) {
  89570. var shape = this._createShape(impostor);
  89571. //unregister events, if body is being changed
  89572. var oldBody = impostor.physicsBody;
  89573. if (oldBody) {
  89574. this.removePhysicsBody(impostor);
  89575. }
  89576. //create the body and material
  89577. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  89578. var bodyCreationObject = {
  89579. mass: impostor.getParam("mass"),
  89580. material: material
  89581. };
  89582. // A simple extend, in case native options were used.
  89583. var nativeOptions = impostor.getParam("nativeOptions");
  89584. for (var key in nativeOptions) {
  89585. if (nativeOptions.hasOwnProperty(key)) {
  89586. bodyCreationObject[key] = nativeOptions[key];
  89587. }
  89588. }
  89589. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  89590. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  89591. this.world.addEventListener("preStep", impostor.beforeStep);
  89592. this.world.addEventListener("postStep", impostor.afterStep);
  89593. impostor.physicsBody.addShape(shape);
  89594. this.world.add(impostor.physicsBody);
  89595. //try to keep the body moving in the right direction by taking old properties.
  89596. //Should be tested!
  89597. if (oldBody) {
  89598. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  89599. impostor.physicsBody[param].copy(oldBody[param]);
  89600. });
  89601. }
  89602. this._processChildMeshes(impostor);
  89603. }
  89604. //now update the body's transformation
  89605. this._updatePhysicsBodyTransformation(impostor);
  89606. };
  89607. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  89608. var _this = this;
  89609. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  89610. var currentRotation = mainImpostor.object.rotationQuaternion;
  89611. if (meshChildren.length) {
  89612. var processMesh = function (localPosition, mesh) {
  89613. if (!currentRotation || !mesh.rotationQuaternion) {
  89614. return;
  89615. }
  89616. var childImpostor = mesh.getPhysicsImpostor();
  89617. if (childImpostor) {
  89618. var parent = childImpostor.parent;
  89619. if (parent !== mainImpostor) {
  89620. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  89621. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  89622. if (childImpostor.physicsBody) {
  89623. _this.removePhysicsBody(childImpostor);
  89624. childImpostor.physicsBody = null;
  89625. }
  89626. childImpostor.parent = mainImpostor;
  89627. childImpostor.resetUpdateFlags();
  89628. 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));
  89629. //Add the mass of the children.
  89630. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  89631. }
  89632. }
  89633. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  89634. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  89635. };
  89636. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  89637. }
  89638. };
  89639. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  89640. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  89641. this.world.removeEventListener("preStep", impostor.beforeStep);
  89642. this.world.removeEventListener("postStep", impostor.afterStep);
  89643. this.world.remove(impostor.physicsBody);
  89644. };
  89645. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  89646. var mainBody = impostorJoint.mainImpostor.physicsBody;
  89647. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  89648. if (!mainBody || !connectedBody) {
  89649. return;
  89650. }
  89651. var constraint;
  89652. var jointData = impostorJoint.joint.jointData;
  89653. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  89654. var constraintData = {
  89655. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  89656. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  89657. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  89658. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  89659. maxForce: jointData.nativeParams.maxForce,
  89660. collideConnected: !!jointData.collision
  89661. };
  89662. switch (impostorJoint.joint.type) {
  89663. case BABYLON.PhysicsJoint.HingeJoint:
  89664. case BABYLON.PhysicsJoint.Hinge2Joint:
  89665. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  89666. break;
  89667. case BABYLON.PhysicsJoint.DistanceJoint:
  89668. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  89669. break;
  89670. case BABYLON.PhysicsJoint.SpringJoint:
  89671. var springData = jointData;
  89672. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  89673. restLength: springData.length,
  89674. stiffness: springData.stiffness,
  89675. damping: springData.damping,
  89676. localAnchorA: constraintData.pivotA,
  89677. localAnchorB: constraintData.pivotB
  89678. });
  89679. break;
  89680. case BABYLON.PhysicsJoint.LockJoint:
  89681. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  89682. break;
  89683. case BABYLON.PhysicsJoint.PointToPointJoint:
  89684. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  89685. default:
  89686. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  89687. break;
  89688. }
  89689. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  89690. constraint.collideConnected = !!jointData.collision;
  89691. impostorJoint.joint.physicsJoint = constraint;
  89692. //don't add spring as constraint, as it is not one.
  89693. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89694. this.world.addConstraint(constraint);
  89695. }
  89696. else {
  89697. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  89698. constraint.applyForce();
  89699. };
  89700. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89701. }
  89702. };
  89703. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89704. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89705. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  89706. }
  89707. else {
  89708. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89709. }
  89710. };
  89711. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  89712. var index;
  89713. var mat;
  89714. for (index = 0; index < this._physicsMaterials.length; index++) {
  89715. mat = this._physicsMaterials[index];
  89716. if (mat.friction === friction && mat.restitution === restitution) {
  89717. return mat;
  89718. }
  89719. }
  89720. var currentMat = new this.BJSCANNON.Material(name);
  89721. currentMat.friction = friction;
  89722. currentMat.restitution = restitution;
  89723. this._physicsMaterials.push(currentMat);
  89724. return currentMat;
  89725. };
  89726. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  89727. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  89728. };
  89729. CannonJSPlugin.prototype._createShape = function (impostor) {
  89730. var object = impostor.object;
  89731. var returnValue;
  89732. var extendSize = impostor.getObjectExtendSize();
  89733. switch (impostor.type) {
  89734. case BABYLON.PhysicsImpostor.SphereImpostor:
  89735. var radiusX = extendSize.x;
  89736. var radiusY = extendSize.y;
  89737. var radiusZ = extendSize.z;
  89738. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  89739. break;
  89740. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  89741. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89742. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  89743. break;
  89744. case BABYLON.PhysicsImpostor.BoxImpostor:
  89745. var box = extendSize.scale(0.5);
  89746. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  89747. break;
  89748. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89749. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  89750. returnValue = new this.BJSCANNON.Plane();
  89751. break;
  89752. case BABYLON.PhysicsImpostor.MeshImpostor:
  89753. // should transform the vertex data to world coordinates!!
  89754. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  89755. var rawFaces = object.getIndices ? object.getIndices() : [];
  89756. if (!rawVerts)
  89757. return;
  89758. // get only scale! so the object could transform correctly.
  89759. var oldPosition = object.position.clone();
  89760. var oldRotation = object.rotation && object.rotation.clone();
  89761. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  89762. object.position.copyFromFloats(0, 0, 0);
  89763. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89764. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89765. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89766. var transform = object.computeWorldMatrix(true);
  89767. // convert rawVerts to object space
  89768. var temp = new Array();
  89769. var index;
  89770. for (index = 0; index < rawVerts.length; index += 3) {
  89771. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  89772. }
  89773. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  89774. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  89775. //now set back the transformation!
  89776. object.position.copyFrom(oldPosition);
  89777. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  89778. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  89779. break;
  89780. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  89781. var oldPosition2 = object.position.clone();
  89782. var oldRotation2 = object.rotation && object.rotation.clone();
  89783. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  89784. object.position.copyFromFloats(0, 0, 0);
  89785. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89786. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89787. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89788. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  89789. returnValue = this._createHeightmap(object);
  89790. object.position.copyFrom(oldPosition2);
  89791. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  89792. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  89793. object.computeWorldMatrix(true);
  89794. break;
  89795. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89796. returnValue = new this.BJSCANNON.Particle();
  89797. break;
  89798. }
  89799. return returnValue;
  89800. };
  89801. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  89802. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89803. var transform = object.computeWorldMatrix(true);
  89804. // convert rawVerts to object space
  89805. var temp = new Array();
  89806. var index;
  89807. for (index = 0; index < pos.length; index += 3) {
  89808. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  89809. }
  89810. pos = temp;
  89811. var matrix = new Array();
  89812. //For now pointDepth will not be used and will be automatically calculated.
  89813. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  89814. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  89815. var boundingInfo = object.getBoundingInfo();
  89816. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  89817. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  89818. var elementSize = dim * 2 / arraySize;
  89819. for (var i = 0; i < pos.length; i = i + 3) {
  89820. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  89821. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  89822. var y = -pos[i + 2] + minY;
  89823. if (!matrix[x]) {
  89824. matrix[x] = [];
  89825. }
  89826. if (!matrix[x][z]) {
  89827. matrix[x][z] = y;
  89828. }
  89829. matrix[x][z] = Math.max(y, matrix[x][z]);
  89830. }
  89831. for (var x = 0; x <= arraySize; ++x) {
  89832. if (!matrix[x]) {
  89833. var loc = 1;
  89834. while (!matrix[(x + loc) % arraySize]) {
  89835. loc++;
  89836. }
  89837. matrix[x] = matrix[(x + loc) % arraySize].slice();
  89838. //console.log("missing x", x);
  89839. }
  89840. for (var z = 0; z <= arraySize; ++z) {
  89841. if (!matrix[x][z]) {
  89842. var loc = 1;
  89843. var newValue;
  89844. while (newValue === undefined) {
  89845. newValue = matrix[x][(z + loc++) % arraySize];
  89846. }
  89847. matrix[x][z] = newValue;
  89848. }
  89849. }
  89850. }
  89851. var shape = new this.BJSCANNON.Heightfield(matrix, {
  89852. elementSize: elementSize
  89853. });
  89854. //For future reference, needed for body transformation
  89855. shape.minY = minY;
  89856. return shape;
  89857. };
  89858. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  89859. var object = impostor.object;
  89860. //make sure it is updated...
  89861. object.computeWorldMatrix && object.computeWorldMatrix(true);
  89862. // The delta between the mesh position and the mesh bounding box center
  89863. var bInfo = object.getBoundingInfo();
  89864. if (!bInfo)
  89865. return;
  89866. var center = impostor.getObjectCenter();
  89867. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  89868. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  89869. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  89870. this._tmpPosition.copyFrom(center);
  89871. var quaternion = object.rotationQuaternion;
  89872. if (!quaternion) {
  89873. return;
  89874. }
  89875. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  89876. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  89877. //-90 DEG in X, precalculated
  89878. quaternion = quaternion.multiply(this._minus90X);
  89879. //Invert! (Precalculated, 90 deg in X)
  89880. //No need to clone. this will never change.
  89881. impostor.setDeltaRotation(this._plus90X);
  89882. }
  89883. //If it is a heightfield, if should be centered.
  89884. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  89885. var mesh = object;
  89886. var boundingInfo = mesh.getBoundingInfo();
  89887. //calculate the correct body position:
  89888. var rotationQuaternion = mesh.rotationQuaternion;
  89889. mesh.rotationQuaternion = this._tmpUnityRotation;
  89890. mesh.computeWorldMatrix(true);
  89891. //get original center with no rotation
  89892. var c = center.clone();
  89893. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  89894. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  89895. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  89896. mesh.setPreTransformMatrix(p);
  89897. mesh.computeWorldMatrix(true);
  89898. //calculate the translation
  89899. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  89900. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  89901. //add it inverted to the delta
  89902. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  89903. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  89904. //rotation is back
  89905. mesh.rotationQuaternion = rotationQuaternion;
  89906. mesh.setPreTransformMatrix(oldPivot);
  89907. mesh.computeWorldMatrix(true);
  89908. }
  89909. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  89910. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  89911. //this._tmpPosition.copyFrom(object.position);
  89912. }
  89913. impostor.setDeltaPosition(this._tmpDeltaPosition);
  89914. //Now update the impostor object
  89915. impostor.physicsBody.position.copy(this._tmpPosition);
  89916. impostor.physicsBody.quaternion.copy(quaternion);
  89917. };
  89918. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89919. impostor.object.position.copyFrom(impostor.physicsBody.position);
  89920. if (impostor.object.rotationQuaternion) {
  89921. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  89922. }
  89923. };
  89924. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89925. impostor.physicsBody.position.copy(newPosition);
  89926. impostor.physicsBody.quaternion.copy(newRotation);
  89927. };
  89928. CannonJSPlugin.prototype.isSupported = function () {
  89929. return this.BJSCANNON !== undefined;
  89930. };
  89931. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89932. impostor.physicsBody.velocity.copy(velocity);
  89933. };
  89934. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89935. impostor.physicsBody.angularVelocity.copy(velocity);
  89936. };
  89937. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89938. var v = impostor.physicsBody.velocity;
  89939. if (!v) {
  89940. return null;
  89941. }
  89942. return new BABYLON.Vector3(v.x, v.y, v.z);
  89943. };
  89944. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89945. var v = impostor.physicsBody.angularVelocity;
  89946. if (!v) {
  89947. return null;
  89948. }
  89949. return new BABYLON.Vector3(v.x, v.y, v.z);
  89950. };
  89951. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89952. impostor.physicsBody.mass = mass;
  89953. impostor.physicsBody.updateMassProperties();
  89954. };
  89955. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  89956. return impostor.physicsBody.mass;
  89957. };
  89958. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  89959. return impostor.physicsBody.material.friction;
  89960. };
  89961. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89962. impostor.physicsBody.material.friction = friction;
  89963. };
  89964. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89965. return impostor.physicsBody.material.restitution;
  89966. };
  89967. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89968. impostor.physicsBody.material.restitution = restitution;
  89969. };
  89970. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  89971. impostor.physicsBody.sleep();
  89972. };
  89973. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  89974. impostor.physicsBody.wakeUp();
  89975. };
  89976. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89977. joint.physicsJoint.distance = maxDistance;
  89978. };
  89979. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  89980. // if (!motorIndex) {
  89981. // joint.physicsJoint.enableMotor();
  89982. // }
  89983. // }
  89984. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  89985. // if (!motorIndex) {
  89986. // joint.physicsJoint.disableMotor();
  89987. // }
  89988. // }
  89989. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89990. if (!motorIndex) {
  89991. joint.physicsJoint.enableMotor();
  89992. joint.physicsJoint.setMotorSpeed(speed);
  89993. if (maxForce) {
  89994. this.setLimit(joint, maxForce);
  89995. }
  89996. }
  89997. };
  89998. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  89999. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  90000. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  90001. };
  90002. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90003. var body = impostor.physicsBody;
  90004. mesh.position.x = body.position.x;
  90005. mesh.position.y = body.position.y;
  90006. mesh.position.z = body.position.z;
  90007. if (mesh.rotationQuaternion) {
  90008. mesh.rotationQuaternion.x = body.quaternion.x;
  90009. mesh.rotationQuaternion.y = body.quaternion.y;
  90010. mesh.rotationQuaternion.z = body.quaternion.z;
  90011. mesh.rotationQuaternion.w = body.quaternion.w;
  90012. }
  90013. };
  90014. CannonJSPlugin.prototype.getRadius = function (impostor) {
  90015. var shape = impostor.physicsBody.shapes[0];
  90016. return shape.boundingSphereRadius;
  90017. };
  90018. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90019. var shape = impostor.physicsBody.shapes[0];
  90020. result.x = shape.halfExtents.x * 2;
  90021. result.y = shape.halfExtents.y * 2;
  90022. result.z = shape.halfExtents.z * 2;
  90023. };
  90024. CannonJSPlugin.prototype.dispose = function () {
  90025. };
  90026. CannonJSPlugin.prototype._extendNamespace = function () {
  90027. //this will force cannon to execute at least one step when using interpolation
  90028. var step_tmp1 = new this.BJSCANNON.Vec3();
  90029. var Engine = this.BJSCANNON;
  90030. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  90031. maxSubSteps = maxSubSteps || 10;
  90032. timeSinceLastCalled = timeSinceLastCalled || 0;
  90033. if (timeSinceLastCalled === 0) {
  90034. this.internalStep(dt);
  90035. this.time += dt;
  90036. }
  90037. else {
  90038. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  90039. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  90040. var t0 = performance.now();
  90041. for (var i = 0; i !== internalSteps; i++) {
  90042. this.internalStep(dt);
  90043. if (performance.now() - t0 > dt * 1000) {
  90044. break;
  90045. }
  90046. }
  90047. this.time += timeSinceLastCalled;
  90048. var h = this.time % dt;
  90049. var h_div_dt = h / dt;
  90050. var interpvelo = step_tmp1;
  90051. var bodies = this.bodies;
  90052. for (var j = 0; j !== bodies.length; j++) {
  90053. var b = bodies[j];
  90054. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  90055. b.position.vsub(b.previousPosition, interpvelo);
  90056. interpvelo.scale(h_div_dt, interpvelo);
  90057. b.position.vadd(interpvelo, b.interpolatedPosition);
  90058. }
  90059. else {
  90060. b.interpolatedPosition.copy(b.position);
  90061. b.interpolatedQuaternion.copy(b.quaternion);
  90062. }
  90063. }
  90064. }
  90065. };
  90066. };
  90067. return CannonJSPlugin;
  90068. }());
  90069. BABYLON.CannonJSPlugin = CannonJSPlugin;
  90070. })(BABYLON || (BABYLON = {}));
  90071. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  90072. var BABYLON;
  90073. (function (BABYLON) {
  90074. var OimoJSPlugin = /** @class */ (function () {
  90075. function OimoJSPlugin(iterations) {
  90076. this.name = "OimoJSPlugin";
  90077. this._tmpImpostorsArray = [];
  90078. this._tmpPositionVector = BABYLON.Vector3.Zero();
  90079. this.BJSOIMO = OIMO;
  90080. this.world = new this.BJSOIMO.World({
  90081. iterations: iterations
  90082. });
  90083. this.world.clear();
  90084. }
  90085. OimoJSPlugin.prototype.setGravity = function (gravity) {
  90086. this.world.gravity.copy(gravity);
  90087. };
  90088. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  90089. this.world.timeStep = timeStep;
  90090. };
  90091. OimoJSPlugin.prototype.getTimeStep = function () {
  90092. return this.world.timeStep;
  90093. };
  90094. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  90095. var _this = this;
  90096. impostors.forEach(function (impostor) {
  90097. impostor.beforeStep();
  90098. });
  90099. this.world.step();
  90100. impostors.forEach(function (impostor) {
  90101. impostor.afterStep();
  90102. //update the ordered impostors array
  90103. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  90104. });
  90105. //check for collisions
  90106. var contact = this.world.contacts;
  90107. while (contact !== null) {
  90108. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  90109. contact = contact.next;
  90110. continue;
  90111. }
  90112. //is this body colliding with any other? get the impostor
  90113. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  90114. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  90115. if (!mainImpostor || !collidingImpostor) {
  90116. contact = contact.next;
  90117. continue;
  90118. }
  90119. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  90120. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  90121. contact = contact.next;
  90122. }
  90123. };
  90124. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90125. var mass = impostor.physicsBody.mass;
  90126. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  90127. };
  90128. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90129. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  90130. this.applyImpulse(impostor, force, contactPoint);
  90131. };
  90132. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90133. var _this = this;
  90134. //parent-child relationship. Does this impostor has a parent impostor?
  90135. if (impostor.parent) {
  90136. if (impostor.physicsBody) {
  90137. this.removePhysicsBody(impostor);
  90138. //TODO is that needed?
  90139. impostor.forceUpdate();
  90140. }
  90141. return;
  90142. }
  90143. if (impostor.isBodyInitRequired()) {
  90144. var bodyConfig = {
  90145. name: impostor.uniqueId,
  90146. //Oimo must have mass, also for static objects.
  90147. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  90148. size: [],
  90149. type: [],
  90150. pos: [],
  90151. posShape: [],
  90152. rot: [],
  90153. rotShape: [],
  90154. move: impostor.getParam("mass") !== 0,
  90155. density: impostor.getParam("mass"),
  90156. friction: impostor.getParam("friction"),
  90157. restitution: impostor.getParam("restitution"),
  90158. //Supporting older versions of Oimo
  90159. world: this.world
  90160. };
  90161. var impostors = [impostor];
  90162. var addToArray = function (parent) {
  90163. if (!parent.getChildMeshes)
  90164. return;
  90165. parent.getChildMeshes().forEach(function (m) {
  90166. if (m.physicsImpostor) {
  90167. impostors.push(m.physicsImpostor);
  90168. //m.physicsImpostor._init();
  90169. }
  90170. });
  90171. };
  90172. addToArray(impostor.object);
  90173. var checkWithEpsilon_1 = function (value) {
  90174. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  90175. };
  90176. var globalQuaternion_1 = new BABYLON.Quaternion();
  90177. impostors.forEach(function (i) {
  90178. if (!i.object.rotationQuaternion) {
  90179. return;
  90180. }
  90181. //get the correct bounding box
  90182. var oldQuaternion = i.object.rotationQuaternion;
  90183. globalQuaternion_1 = oldQuaternion.clone();
  90184. var rot = oldQuaternion.toEulerAngles();
  90185. var extendSize = i.getObjectExtendSize();
  90186. var radToDeg = 57.295779513082320876;
  90187. if (i === impostor) {
  90188. var center = impostor.getObjectCenter();
  90189. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  90190. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  90191. //Can also use Array.prototype.push.apply
  90192. bodyConfig.pos.push(center.x);
  90193. bodyConfig.pos.push(center.y);
  90194. bodyConfig.pos.push(center.z);
  90195. bodyConfig.posShape.push(0, 0, 0);
  90196. //tmp solution
  90197. bodyConfig.rot.push(0);
  90198. bodyConfig.rot.push(0);
  90199. bodyConfig.rot.push(0);
  90200. bodyConfig.rotShape.push(0, 0, 0);
  90201. }
  90202. else {
  90203. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  90204. bodyConfig.posShape.push(localPosition.x);
  90205. bodyConfig.posShape.push(localPosition.y);
  90206. bodyConfig.posShape.push(localPosition.z);
  90207. bodyConfig.pos.push(0, 0, 0);
  90208. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  90209. bodyConfig.rot.push(0);
  90210. bodyConfig.rot.push(0);
  90211. bodyConfig.rot.push(0);
  90212. bodyConfig.rotShape.push(rot.x * radToDeg);
  90213. bodyConfig.rotShape.push(rot.y * radToDeg);
  90214. bodyConfig.rotShape.push(rot.z * radToDeg);
  90215. }
  90216. // register mesh
  90217. switch (i.type) {
  90218. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90219. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  90220. case BABYLON.PhysicsImpostor.SphereImpostor:
  90221. var radiusX = extendSize.x;
  90222. var radiusY = extendSize.y;
  90223. var radiusZ = extendSize.z;
  90224. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  90225. bodyConfig.type.push('sphere');
  90226. //due to the way oimo works with compounds, add 3 times
  90227. bodyConfig.size.push(size);
  90228. bodyConfig.size.push(size);
  90229. bodyConfig.size.push(size);
  90230. break;
  90231. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90232. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  90233. var sizeY = checkWithEpsilon_1(extendSize.y);
  90234. bodyConfig.type.push('cylinder');
  90235. bodyConfig.size.push(sizeX);
  90236. bodyConfig.size.push(sizeY);
  90237. //due to the way oimo works with compounds, add one more value.
  90238. bodyConfig.size.push(sizeY);
  90239. break;
  90240. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90241. case BABYLON.PhysicsImpostor.BoxImpostor:
  90242. default:
  90243. var sizeX = checkWithEpsilon_1(extendSize.x);
  90244. var sizeY = checkWithEpsilon_1(extendSize.y);
  90245. var sizeZ = checkWithEpsilon_1(extendSize.z);
  90246. bodyConfig.type.push('box');
  90247. //if (i === impostor) {
  90248. bodyConfig.size.push(sizeX);
  90249. bodyConfig.size.push(sizeY);
  90250. bodyConfig.size.push(sizeZ);
  90251. //} else {
  90252. // bodyConfig.size.push(0,0,0);
  90253. //}
  90254. break;
  90255. }
  90256. //actually not needed, but hey...
  90257. i.object.rotationQuaternion = oldQuaternion;
  90258. });
  90259. impostor.physicsBody = this.world.add(bodyConfig);
  90260. // set the quaternion, ignoring the previously defined (euler) rotation
  90261. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  90262. // update with delta 0, so the body will reveive the new rotation.
  90263. impostor.physicsBody.updatePosition(0);
  90264. }
  90265. else {
  90266. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  90267. }
  90268. impostor.setDeltaPosition(this._tmpPositionVector);
  90269. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  90270. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  90271. };
  90272. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90273. //impostor.physicsBody.dispose();
  90274. //Same as : (older oimo versions)
  90275. this.world.removeRigidBody(impostor.physicsBody);
  90276. };
  90277. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90278. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90279. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90280. if (!mainBody || !connectedBody) {
  90281. return;
  90282. }
  90283. var jointData = impostorJoint.joint.jointData;
  90284. var options = jointData.nativeParams || {};
  90285. var type;
  90286. var nativeJointData = {
  90287. body1: mainBody,
  90288. body2: connectedBody,
  90289. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  90290. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  90291. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  90292. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  90293. min: options.min,
  90294. max: options.max,
  90295. collision: options.collision || jointData.collision,
  90296. spring: options.spring,
  90297. //supporting older version of Oimo
  90298. world: this.world
  90299. };
  90300. switch (impostorJoint.joint.type) {
  90301. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90302. type = "jointBall";
  90303. break;
  90304. case BABYLON.PhysicsJoint.SpringJoint:
  90305. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  90306. var springData = jointData;
  90307. nativeJointData.min = springData.length || nativeJointData.min;
  90308. //Max should also be set, just make sure it is at least min
  90309. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  90310. case BABYLON.PhysicsJoint.DistanceJoint:
  90311. type = "jointDistance";
  90312. nativeJointData.max = jointData.maxDistance;
  90313. break;
  90314. case BABYLON.PhysicsJoint.PrismaticJoint:
  90315. type = "jointPrisme";
  90316. break;
  90317. case BABYLON.PhysicsJoint.SliderJoint:
  90318. type = "jointSlide";
  90319. break;
  90320. case BABYLON.PhysicsJoint.WheelJoint:
  90321. type = "jointWheel";
  90322. break;
  90323. case BABYLON.PhysicsJoint.HingeJoint:
  90324. default:
  90325. type = "jointHinge";
  90326. break;
  90327. }
  90328. nativeJointData.type = type;
  90329. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  90330. };
  90331. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90332. //Bug in Oimo prevents us from disposing a joint in the playground
  90333. //joint.joint.physicsJoint.dispose();
  90334. //So we will bruteforce it!
  90335. try {
  90336. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  90337. }
  90338. catch (e) {
  90339. BABYLON.Tools.Warn(e);
  90340. }
  90341. };
  90342. OimoJSPlugin.prototype.isSupported = function () {
  90343. return this.BJSOIMO !== undefined;
  90344. };
  90345. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90346. if (!impostor.physicsBody.sleeping) {
  90347. //TODO check that
  90348. /*if (impostor.physicsBody.shapes.next) {
  90349. var parentShape = this._getLastShape(impostor.physicsBody);
  90350. impostor.object.position.copyFrom(parentShape.position);
  90351. console.log(parentShape.position);
  90352. } else {*/
  90353. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  90354. //}
  90355. if (impostor.object.rotationQuaternion) {
  90356. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  90357. }
  90358. }
  90359. };
  90360. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90361. var body = impostor.physicsBody;
  90362. body.position.copy(newPosition);
  90363. body.orientation.copy(newRotation);
  90364. body.syncShapes();
  90365. body.awake();
  90366. };
  90367. /*private _getLastShape(body: any): any {
  90368. var lastShape = body.shapes;
  90369. while (lastShape.next) {
  90370. lastShape = lastShape.next;
  90371. }
  90372. return lastShape;
  90373. }*/
  90374. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90375. impostor.physicsBody.linearVelocity.copy(velocity);
  90376. };
  90377. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90378. impostor.physicsBody.angularVelocity.copy(velocity);
  90379. };
  90380. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90381. var v = impostor.physicsBody.linearVelocity;
  90382. if (!v) {
  90383. return null;
  90384. }
  90385. return new BABYLON.Vector3(v.x, v.y, v.z);
  90386. };
  90387. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90388. var v = impostor.physicsBody.angularVelocity;
  90389. if (!v) {
  90390. return null;
  90391. }
  90392. return new BABYLON.Vector3(v.x, v.y, v.z);
  90393. };
  90394. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90395. var staticBody = mass === 0;
  90396. //this will actually set the body's density and not its mass.
  90397. //But this is how oimo treats the mass variable.
  90398. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  90399. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  90400. };
  90401. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  90402. return impostor.physicsBody.shapes.density;
  90403. };
  90404. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  90405. return impostor.physicsBody.shapes.friction;
  90406. };
  90407. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90408. impostor.physicsBody.shapes.friction = friction;
  90409. };
  90410. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90411. return impostor.physicsBody.shapes.restitution;
  90412. };
  90413. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90414. impostor.physicsBody.shapes.restitution = restitution;
  90415. };
  90416. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  90417. impostor.physicsBody.sleep();
  90418. };
  90419. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  90420. impostor.physicsBody.awake();
  90421. };
  90422. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90423. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  90424. if (minDistance !== void 0) {
  90425. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  90426. }
  90427. };
  90428. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90429. //TODO separate rotational and transational motors.
  90430. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90431. if (motor) {
  90432. motor.setMotor(speed, maxForce);
  90433. }
  90434. };
  90435. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  90436. //TODO separate rotational and transational motors.
  90437. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90438. if (motor) {
  90439. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  90440. }
  90441. };
  90442. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90443. var body = impostor.physicsBody;
  90444. mesh.position.x = body.position.x;
  90445. mesh.position.y = body.position.y;
  90446. mesh.position.z = body.position.z;
  90447. if (mesh.rotationQuaternion) {
  90448. mesh.rotationQuaternion.x = body.orientation.x;
  90449. mesh.rotationQuaternion.y = body.orientation.y;
  90450. mesh.rotationQuaternion.z = body.orientation.z;
  90451. mesh.rotationQuaternion.w = body.orientation.s;
  90452. }
  90453. };
  90454. OimoJSPlugin.prototype.getRadius = function (impostor) {
  90455. return impostor.physicsBody.shapes.radius;
  90456. };
  90457. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90458. var shape = impostor.physicsBody.shapes;
  90459. result.x = shape.halfWidth * 2;
  90460. result.y = shape.halfHeight * 2;
  90461. result.z = shape.halfDepth * 2;
  90462. };
  90463. OimoJSPlugin.prototype.dispose = function () {
  90464. this.world.clear();
  90465. };
  90466. return OimoJSPlugin;
  90467. }());
  90468. BABYLON.OimoJSPlugin = OimoJSPlugin;
  90469. })(BABYLON || (BABYLON = {}));
  90470. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  90471. var BABYLON;
  90472. (function (BABYLON) {
  90473. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  90474. // All values and structures referenced from:
  90475. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  90476. var DDS_MAGIC = 0x20534444;
  90477. var
  90478. //DDSD_CAPS = 0x1,
  90479. //DDSD_HEIGHT = 0x2,
  90480. //DDSD_WIDTH = 0x4,
  90481. //DDSD_PITCH = 0x8,
  90482. //DDSD_PIXELFORMAT = 0x1000,
  90483. DDSD_MIPMAPCOUNT = 0x20000;
  90484. //DDSD_LINEARSIZE = 0x80000,
  90485. //DDSD_DEPTH = 0x800000;
  90486. // var DDSCAPS_COMPLEX = 0x8,
  90487. // DDSCAPS_MIPMAP = 0x400000,
  90488. // DDSCAPS_TEXTURE = 0x1000;
  90489. var DDSCAPS2_CUBEMAP = 0x200;
  90490. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  90491. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  90492. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  90493. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  90494. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  90495. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  90496. // DDSCAPS2_VOLUME = 0x200000;
  90497. var
  90498. //DDPF_ALPHAPIXELS = 0x1,
  90499. //DDPF_ALPHA = 0x2,
  90500. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  90501. //DDPF_YUV = 0x200,
  90502. DDPF_LUMINANCE = 0x20000;
  90503. function FourCCToInt32(value) {
  90504. return value.charCodeAt(0) +
  90505. (value.charCodeAt(1) << 8) +
  90506. (value.charCodeAt(2) << 16) +
  90507. (value.charCodeAt(3) << 24);
  90508. }
  90509. function Int32ToFourCC(value) {
  90510. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  90511. }
  90512. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  90513. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  90514. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  90515. var FOURCC_DX10 = FourCCToInt32("DX10");
  90516. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  90517. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  90518. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  90519. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  90520. var headerLengthInt = 31; // The header length in 32 bit ints
  90521. // Offsets into the header array
  90522. var off_magic = 0;
  90523. var off_size = 1;
  90524. var off_flags = 2;
  90525. var off_height = 3;
  90526. var off_width = 4;
  90527. var off_mipmapCount = 7;
  90528. var off_pfFlags = 20;
  90529. var off_pfFourCC = 21;
  90530. var off_RGBbpp = 22;
  90531. var off_RMask = 23;
  90532. var off_GMask = 24;
  90533. var off_BMask = 25;
  90534. var off_AMask = 26;
  90535. // var off_caps1 = 27;
  90536. var off_caps2 = 28;
  90537. // var off_caps3 = 29;
  90538. // var off_caps4 = 30;
  90539. var off_dxgiFormat = 32;
  90540. ;
  90541. var DDSTools = /** @class */ (function () {
  90542. function DDSTools() {
  90543. }
  90544. DDSTools.GetDDSInfo = function (arrayBuffer) {
  90545. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90546. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  90547. var mipmapCount = 1;
  90548. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  90549. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90550. }
  90551. var fourCC = header[off_pfFourCC];
  90552. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  90553. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90554. switch (fourCC) {
  90555. case FOURCC_D3DFMT_R16G16B16A16F:
  90556. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90557. break;
  90558. case FOURCC_D3DFMT_R32G32B32A32F:
  90559. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90560. break;
  90561. case FOURCC_DX10:
  90562. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  90563. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90564. break;
  90565. }
  90566. }
  90567. return {
  90568. width: header[off_width],
  90569. height: header[off_height],
  90570. mipmapCount: mipmapCount,
  90571. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  90572. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  90573. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  90574. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  90575. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  90576. dxgiFormat: dxgiFormat,
  90577. textureType: textureType
  90578. };
  90579. };
  90580. DDSTools._ToHalfFloat = function (value) {
  90581. if (!DDSTools._FloatView) {
  90582. DDSTools._FloatView = new Float32Array(1);
  90583. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  90584. }
  90585. DDSTools._FloatView[0] = value;
  90586. var x = DDSTools._Int32View[0];
  90587. var bits = (x >> 16) & 0x8000; /* Get the sign */
  90588. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  90589. var e = (x >> 23) & 0xff; /* Using int is faster here */
  90590. /* If zero, or denormal, or exponent underflows too much for a denormal
  90591. * half, return signed zero. */
  90592. if (e < 103) {
  90593. return bits;
  90594. }
  90595. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  90596. if (e > 142) {
  90597. bits |= 0x7c00;
  90598. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  90599. * not Inf, so make sure we set one mantissa bit too. */
  90600. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  90601. return bits;
  90602. }
  90603. /* If exponent underflows but not too much, return a denormal */
  90604. if (e < 113) {
  90605. m |= 0x0800;
  90606. /* Extra rounding may overflow and set mantissa to 0 and exponent
  90607. * to 1, which is OK. */
  90608. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  90609. return bits;
  90610. }
  90611. bits |= ((e - 112) << 10) | (m >> 1);
  90612. bits += m & 1;
  90613. return bits;
  90614. };
  90615. DDSTools._FromHalfFloat = function (value) {
  90616. var s = (value & 0x8000) >> 15;
  90617. var e = (value & 0x7C00) >> 10;
  90618. var f = value & 0x03FF;
  90619. if (e === 0) {
  90620. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  90621. }
  90622. else if (e == 0x1F) {
  90623. return f ? NaN : ((s ? -1 : 1) * Infinity);
  90624. }
  90625. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  90626. };
  90627. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90628. var destArray = new Float32Array(dataLength);
  90629. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90630. var index = 0;
  90631. for (var y = 0; y < height; y++) {
  90632. for (var x = 0; x < width; x++) {
  90633. var srcPos = (x + y * width) * 4;
  90634. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  90635. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  90636. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  90637. if (DDSTools.StoreLODInAlphaChannel) {
  90638. destArray[index + 3] = lod;
  90639. }
  90640. else {
  90641. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  90642. }
  90643. index += 4;
  90644. }
  90645. }
  90646. return destArray;
  90647. };
  90648. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90649. if (DDSTools.StoreLODInAlphaChannel) {
  90650. var destArray = new Uint16Array(dataLength);
  90651. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90652. var index = 0;
  90653. for (var y = 0; y < height; y++) {
  90654. for (var x = 0; x < width; x++) {
  90655. var srcPos = (x + y * width) * 4;
  90656. destArray[index] = srcData[srcPos];
  90657. destArray[index + 1] = srcData[srcPos + 1];
  90658. destArray[index + 2] = srcData[srcPos + 2];
  90659. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  90660. index += 4;
  90661. }
  90662. }
  90663. return destArray;
  90664. }
  90665. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  90666. };
  90667. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90668. if (DDSTools.StoreLODInAlphaChannel) {
  90669. var destArray = new Float32Array(dataLength);
  90670. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90671. var index = 0;
  90672. for (var y = 0; y < height; y++) {
  90673. for (var x = 0; x < width; x++) {
  90674. var srcPos = (x + y * width) * 4;
  90675. destArray[index] = srcData[srcPos];
  90676. destArray[index + 1] = srcData[srcPos + 1];
  90677. destArray[index + 2] = srcData[srcPos + 2];
  90678. destArray[index + 3] = lod;
  90679. index += 4;
  90680. }
  90681. }
  90682. return destArray;
  90683. }
  90684. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  90685. };
  90686. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90687. var destArray = new Uint8Array(dataLength);
  90688. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90689. var index = 0;
  90690. for (var y = 0; y < height; y++) {
  90691. for (var x = 0; x < width; x++) {
  90692. var srcPos = (x + y * width) * 4;
  90693. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  90694. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  90695. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  90696. if (DDSTools.StoreLODInAlphaChannel) {
  90697. destArray[index + 3] = lod;
  90698. }
  90699. else {
  90700. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  90701. }
  90702. index += 4;
  90703. }
  90704. }
  90705. return destArray;
  90706. };
  90707. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90708. var destArray = new Uint8Array(dataLength);
  90709. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90710. var index = 0;
  90711. for (var y = 0; y < height; y++) {
  90712. for (var x = 0; x < width; x++) {
  90713. var srcPos = (x + y * width) * 4;
  90714. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  90715. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  90716. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  90717. if (DDSTools.StoreLODInAlphaChannel) {
  90718. destArray[index + 3] = lod;
  90719. }
  90720. else {
  90721. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  90722. }
  90723. index += 4;
  90724. }
  90725. }
  90726. return destArray;
  90727. };
  90728. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  90729. var byteArray = new Uint8Array(dataLength);
  90730. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90731. var index = 0;
  90732. for (var y = 0; y < height; y++) {
  90733. for (var x = 0; x < width; x++) {
  90734. var srcPos = (x + y * width) * 4;
  90735. byteArray[index] = srcData[srcPos + rOffset];
  90736. byteArray[index + 1] = srcData[srcPos + gOffset];
  90737. byteArray[index + 2] = srcData[srcPos + bOffset];
  90738. byteArray[index + 3] = srcData[srcPos + aOffset];
  90739. index += 4;
  90740. }
  90741. }
  90742. return byteArray;
  90743. };
  90744. DDSTools._ExtractLongWordOrder = function (value) {
  90745. if (value === 0 || value === 255 || value === -16777216) {
  90746. return 0;
  90747. }
  90748. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  90749. };
  90750. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  90751. var byteArray = new Uint8Array(dataLength);
  90752. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90753. var index = 0;
  90754. for (var y = 0; y < height; y++) {
  90755. for (var x = 0; x < width; x++) {
  90756. var srcPos = (x + y * width) * 3;
  90757. byteArray[index] = srcData[srcPos + rOffset];
  90758. byteArray[index + 1] = srcData[srcPos + gOffset];
  90759. byteArray[index + 2] = srcData[srcPos + bOffset];
  90760. index += 3;
  90761. }
  90762. }
  90763. return byteArray;
  90764. };
  90765. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  90766. var byteArray = new Uint8Array(dataLength);
  90767. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90768. var index = 0;
  90769. for (var y = 0; y < height; y++) {
  90770. for (var x = 0; x < width; x++) {
  90771. var srcPos = (x + y * width);
  90772. byteArray[index] = srcData[srcPos];
  90773. index++;
  90774. }
  90775. }
  90776. return byteArray;
  90777. };
  90778. /**
  90779. * Uploads DDS Levels to a Babylon Texture
  90780. * @hidden
  90781. */
  90782. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  90783. if (lodIndex === void 0) { lodIndex = -1; }
  90784. var sphericalPolynomialFaces = null;
  90785. if (info.sphericalPolynomial) {
  90786. sphericalPolynomialFaces = new Array();
  90787. }
  90788. var ext = engine.getCaps().s3tc;
  90789. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90790. var fourCC, width, height, dataLength = 0, dataOffset;
  90791. var byteArray, mipmapCount, mip;
  90792. var internalCompressedFormat = 0;
  90793. var blockBytes = 1;
  90794. if (header[off_magic] !== DDS_MAGIC) {
  90795. BABYLON.Tools.Error("Invalid magic number in DDS header");
  90796. return;
  90797. }
  90798. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  90799. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  90800. return;
  90801. }
  90802. if (info.isCompressed && !ext) {
  90803. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  90804. return;
  90805. }
  90806. var bpp = header[off_RGBbpp];
  90807. dataOffset = header[off_size] + 4;
  90808. var computeFormats = false;
  90809. if (info.isFourCC) {
  90810. fourCC = header[off_pfFourCC];
  90811. switch (fourCC) {
  90812. case FOURCC_DXT1:
  90813. blockBytes = 8;
  90814. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  90815. break;
  90816. case FOURCC_DXT3:
  90817. blockBytes = 16;
  90818. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  90819. break;
  90820. case FOURCC_DXT5:
  90821. blockBytes = 16;
  90822. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  90823. break;
  90824. case FOURCC_D3DFMT_R16G16B16A16F:
  90825. computeFormats = true;
  90826. break;
  90827. case FOURCC_D3DFMT_R32G32B32A32F:
  90828. computeFormats = true;
  90829. break;
  90830. case FOURCC_DX10:
  90831. // There is an additionnal header so dataOffset need to be changed
  90832. dataOffset += 5 * 4; // 5 uints
  90833. var supported = false;
  90834. switch (info.dxgiFormat) {
  90835. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  90836. computeFormats = true;
  90837. supported = true;
  90838. break;
  90839. case DXGI_FORMAT_B8G8R8X8_UNORM:
  90840. info.isRGB = true;
  90841. info.isFourCC = false;
  90842. bpp = 32;
  90843. supported = true;
  90844. break;
  90845. }
  90846. if (supported) {
  90847. break;
  90848. }
  90849. default:
  90850. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  90851. return;
  90852. }
  90853. }
  90854. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  90855. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  90856. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  90857. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  90858. if (computeFormats) {
  90859. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  90860. }
  90861. mipmapCount = 1;
  90862. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  90863. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90864. }
  90865. for (var face = 0; face < faces; face++) {
  90866. width = header[off_width];
  90867. height = header[off_height];
  90868. for (mip = 0; mip < mipmapCount; ++mip) {
  90869. if (lodIndex === -1 || lodIndex === mip) {
  90870. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  90871. var i = (lodIndex === -1) ? mip : 0;
  90872. if (!info.isCompressed && info.isFourCC) {
  90873. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90874. dataLength = width * height * 4;
  90875. var floatArray = null;
  90876. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  90877. if (bpp === 128) {
  90878. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90879. if (sphericalPolynomialFaces && i == 0) {
  90880. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90881. }
  90882. }
  90883. else if (bpp === 64) {
  90884. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90885. if (sphericalPolynomialFaces && i == 0) {
  90886. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90887. }
  90888. }
  90889. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90890. }
  90891. else {
  90892. if (bpp === 128) {
  90893. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90894. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90895. if (sphericalPolynomialFaces && i == 0) {
  90896. sphericalPolynomialFaces.push(floatArray);
  90897. }
  90898. }
  90899. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  90900. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90901. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90902. if (sphericalPolynomialFaces && i == 0) {
  90903. sphericalPolynomialFaces.push(floatArray);
  90904. }
  90905. }
  90906. else { // 64
  90907. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90908. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90909. if (sphericalPolynomialFaces && i == 0) {
  90910. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90911. }
  90912. }
  90913. }
  90914. if (floatArray) {
  90915. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  90916. }
  90917. }
  90918. else if (info.isRGB) {
  90919. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90920. if (bpp === 24) {
  90921. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  90922. dataLength = width * height * 3;
  90923. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  90924. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90925. }
  90926. else { // 32
  90927. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90928. dataLength = width * height * 4;
  90929. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  90930. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90931. }
  90932. }
  90933. else if (info.isLuminance) {
  90934. var unpackAlignment = engine._getUnpackAlignement();
  90935. var unpaddedRowSize = width;
  90936. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  90937. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  90938. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  90939. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  90940. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90941. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90942. }
  90943. else {
  90944. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  90945. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  90946. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90947. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  90948. }
  90949. }
  90950. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  90951. width *= 0.5;
  90952. height *= 0.5;
  90953. width = Math.max(1.0, width);
  90954. height = Math.max(1.0, height);
  90955. }
  90956. if (currentFace !== undefined) {
  90957. // Loading a single face
  90958. break;
  90959. }
  90960. }
  90961. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  90962. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  90963. size: header[off_width],
  90964. right: sphericalPolynomialFaces[0],
  90965. left: sphericalPolynomialFaces[1],
  90966. up: sphericalPolynomialFaces[2],
  90967. down: sphericalPolynomialFaces[3],
  90968. front: sphericalPolynomialFaces[4],
  90969. back: sphericalPolynomialFaces[5],
  90970. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  90971. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  90972. gammaSpace: false,
  90973. });
  90974. }
  90975. else {
  90976. info.sphericalPolynomial = undefined;
  90977. }
  90978. };
  90979. DDSTools.StoreLODInAlphaChannel = false;
  90980. return DDSTools;
  90981. }());
  90982. BABYLON.DDSTools = DDSTools;
  90983. })(BABYLON || (BABYLON = {}));
  90984. //# sourceMappingURL=babylon.dds.js.map
  90985. var BABYLON;
  90986. (function (BABYLON) {
  90987. /**
  90988. * Implementation of the DDS Texture Loader.
  90989. */
  90990. var DDSTextureLoader = /** @class */ (function () {
  90991. function DDSTextureLoader() {
  90992. /**
  90993. * Defines wether the loader supports cascade loading the different faces.
  90994. */
  90995. this.supportCascades = true;
  90996. }
  90997. /**
  90998. * This returns if the loader support the current file information.
  90999. * @param extension defines the file extension of the file being loaded
  91000. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91001. * @param fallback defines the fallback internal texture if any
  91002. * @param isBase64 defines whether the texture is encoded as a base64
  91003. * @param isBuffer defines whether the texture data are stored as a buffer
  91004. * @returns true if the loader can load the specified file
  91005. */
  91006. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91007. return extension.indexOf(".dds") === 0;
  91008. };
  91009. /**
  91010. * Transform the url before loading if required.
  91011. * @param rootUrl the url of the texture
  91012. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91013. * @returns the transformed texture
  91014. */
  91015. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91016. return rootUrl;
  91017. };
  91018. /**
  91019. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91020. * @param rootUrl the url of the texture
  91021. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91022. * @returns the fallback texture
  91023. */
  91024. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91025. return null;
  91026. };
  91027. /**
  91028. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91029. * @param data contains the texture data
  91030. * @param texture defines the BabylonJS internal texture
  91031. * @param createPolynomials will be true if polynomials have been requested
  91032. * @param onLoad defines the callback to trigger once the texture is ready
  91033. * @param onError defines the callback to trigger in case of error
  91034. */
  91035. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  91036. var engine = texture.getEngine();
  91037. var info;
  91038. var loadMipmap = false;
  91039. if (Array.isArray(imgs)) {
  91040. for (var index = 0; index < imgs.length; index++) {
  91041. var data_1 = imgs[index];
  91042. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  91043. texture.width = info.width;
  91044. texture.height = info.height;
  91045. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91046. engine._unpackFlipY(info.isCompressed);
  91047. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  91048. if (!info.isFourCC && info.mipmapCount === 1) {
  91049. engine.generateMipMapsForCubemap(texture);
  91050. }
  91051. }
  91052. }
  91053. else {
  91054. var data = imgs;
  91055. info = BABYLON.DDSTools.GetDDSInfo(data);
  91056. texture.width = info.width;
  91057. texture.height = info.height;
  91058. if (createPolynomials) {
  91059. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  91060. }
  91061. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91062. engine._unpackFlipY(info.isCompressed);
  91063. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  91064. if (!info.isFourCC && info.mipmapCount === 1) {
  91065. engine.generateMipMapsForCubemap(texture);
  91066. }
  91067. }
  91068. engine._setCubeMapTextureParams(loadMipmap);
  91069. texture.isReady = true;
  91070. if (onLoad) {
  91071. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  91072. }
  91073. };
  91074. /**
  91075. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91076. * @param data contains the texture data
  91077. * @param texture defines the BabylonJS internal texture
  91078. * @param callback defines the method to call once ready to upload
  91079. */
  91080. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  91081. var info = BABYLON.DDSTools.GetDDSInfo(data);
  91082. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  91083. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  91084. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  91085. });
  91086. };
  91087. return DDSTextureLoader;
  91088. }());
  91089. // Register the loader.
  91090. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  91091. })(BABYLON || (BABYLON = {}));
  91092. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  91093. var BABYLON;
  91094. (function (BABYLON) {
  91095. /*
  91096. * Based on jsTGALoader - Javascript loader for TGA file
  91097. * By Vincent Thibault
  91098. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  91099. */
  91100. var TGATools = /** @class */ (function () {
  91101. function TGATools() {
  91102. }
  91103. TGATools.GetTGAHeader = function (data) {
  91104. var offset = 0;
  91105. var header = {
  91106. id_length: data[offset++],
  91107. colormap_type: data[offset++],
  91108. image_type: data[offset++],
  91109. colormap_index: data[offset++] | data[offset++] << 8,
  91110. colormap_length: data[offset++] | data[offset++] << 8,
  91111. colormap_size: data[offset++],
  91112. origin: [
  91113. data[offset++] | data[offset++] << 8,
  91114. data[offset++] | data[offset++] << 8
  91115. ],
  91116. width: data[offset++] | data[offset++] << 8,
  91117. height: data[offset++] | data[offset++] << 8,
  91118. pixel_size: data[offset++],
  91119. flags: data[offset++]
  91120. };
  91121. return header;
  91122. };
  91123. /**
  91124. * Uploads TGA content to a Babylon Texture
  91125. * @hidden
  91126. */
  91127. TGATools.UploadContent = function (texture, data) {
  91128. // Not enough data to contain header ?
  91129. if (data.length < 19) {
  91130. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  91131. return;
  91132. }
  91133. // Read Header
  91134. var offset = 18;
  91135. var header = TGATools.GetTGAHeader(data);
  91136. // Assume it's a valid Targa file.
  91137. if (header.id_length + offset > data.length) {
  91138. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  91139. return;
  91140. }
  91141. // Skip not needed data
  91142. offset += header.id_length;
  91143. var use_rle = false;
  91144. var use_pal = false;
  91145. var use_grey = false;
  91146. // Get some informations.
  91147. switch (header.image_type) {
  91148. case TGATools._TYPE_RLE_INDEXED:
  91149. use_rle = true;
  91150. case TGATools._TYPE_INDEXED:
  91151. use_pal = true;
  91152. break;
  91153. case TGATools._TYPE_RLE_RGB:
  91154. use_rle = true;
  91155. case TGATools._TYPE_RGB:
  91156. // use_rgb = true;
  91157. break;
  91158. case TGATools._TYPE_RLE_GREY:
  91159. use_rle = true;
  91160. case TGATools._TYPE_GREY:
  91161. use_grey = true;
  91162. break;
  91163. }
  91164. var pixel_data;
  91165. // var numAlphaBits = header.flags & 0xf;
  91166. var pixel_size = header.pixel_size >> 3;
  91167. var pixel_total = header.width * header.height * pixel_size;
  91168. // Read palettes
  91169. var palettes;
  91170. if (use_pal) {
  91171. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  91172. }
  91173. // Read LRE
  91174. if (use_rle) {
  91175. pixel_data = new Uint8Array(pixel_total);
  91176. var c, count, i;
  91177. var localOffset = 0;
  91178. var pixels = new Uint8Array(pixel_size);
  91179. while (offset < pixel_total && localOffset < pixel_total) {
  91180. c = data[offset++];
  91181. count = (c & 0x7f) + 1;
  91182. // RLE pixels
  91183. if (c & 0x80) {
  91184. // Bind pixel tmp array
  91185. for (i = 0; i < pixel_size; ++i) {
  91186. pixels[i] = data[offset++];
  91187. }
  91188. // Copy pixel array
  91189. for (i = 0; i < count; ++i) {
  91190. pixel_data.set(pixels, localOffset + i * pixel_size);
  91191. }
  91192. localOffset += pixel_size * count;
  91193. }
  91194. // Raw pixels
  91195. else {
  91196. count *= pixel_size;
  91197. for (i = 0; i < count; ++i) {
  91198. pixel_data[localOffset + i] = data[offset++];
  91199. }
  91200. localOffset += count;
  91201. }
  91202. }
  91203. }
  91204. // RAW Pixels
  91205. else {
  91206. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  91207. }
  91208. // Load to texture
  91209. var x_start, y_start, x_step, y_step, y_end, x_end;
  91210. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  91211. default:
  91212. case TGATools._ORIGIN_UL:
  91213. x_start = 0;
  91214. x_step = 1;
  91215. x_end = header.width;
  91216. y_start = 0;
  91217. y_step = 1;
  91218. y_end = header.height;
  91219. break;
  91220. case TGATools._ORIGIN_BL:
  91221. x_start = 0;
  91222. x_step = 1;
  91223. x_end = header.width;
  91224. y_start = header.height - 1;
  91225. y_step = -1;
  91226. y_end = -1;
  91227. break;
  91228. case TGATools._ORIGIN_UR:
  91229. x_start = header.width - 1;
  91230. x_step = -1;
  91231. x_end = -1;
  91232. y_start = 0;
  91233. y_step = 1;
  91234. y_end = header.height;
  91235. break;
  91236. case TGATools._ORIGIN_BR:
  91237. x_start = header.width - 1;
  91238. x_step = -1;
  91239. x_end = -1;
  91240. y_start = header.height - 1;
  91241. y_step = -1;
  91242. y_end = -1;
  91243. break;
  91244. }
  91245. // Load the specify method
  91246. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  91247. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  91248. var engine = texture.getEngine();
  91249. engine._uploadDataToTextureDirectly(texture, imageData);
  91250. };
  91251. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91252. var image = pixel_data, colormap = palettes;
  91253. var width = header.width, height = header.height;
  91254. var color, i = 0, x, y;
  91255. var imageData = new Uint8Array(width * height * 4);
  91256. for (y = y_start; y !== y_end; y += y_step) {
  91257. for (x = x_start; x !== x_end; x += x_step, i++) {
  91258. color = image[i];
  91259. imageData[(x + width * y) * 4 + 3] = 255;
  91260. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  91261. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  91262. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  91263. }
  91264. }
  91265. return imageData;
  91266. };
  91267. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91268. var image = pixel_data;
  91269. var width = header.width, height = header.height;
  91270. var color, i = 0, x, y;
  91271. var imageData = new Uint8Array(width * height * 4);
  91272. for (y = y_start; y !== y_end; y += y_step) {
  91273. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91274. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  91275. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  91276. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  91277. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  91278. imageData[(x + width * y) * 4 + 0] = r;
  91279. imageData[(x + width * y) * 4 + 1] = g;
  91280. imageData[(x + width * y) * 4 + 2] = b;
  91281. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  91282. }
  91283. }
  91284. return imageData;
  91285. };
  91286. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91287. var image = pixel_data;
  91288. var width = header.width, height = header.height;
  91289. var i = 0, x, y;
  91290. var imageData = new Uint8Array(width * height * 4);
  91291. for (y = y_start; y !== y_end; y += y_step) {
  91292. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  91293. imageData[(x + width * y) * 4 + 3] = 255;
  91294. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91295. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91296. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91297. }
  91298. }
  91299. return imageData;
  91300. };
  91301. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91302. var image = pixel_data;
  91303. var width = header.width, height = header.height;
  91304. var i = 0, x, y;
  91305. var imageData = new Uint8Array(width * height * 4);
  91306. for (y = y_start; y !== y_end; y += y_step) {
  91307. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  91308. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91309. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91310. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91311. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  91312. }
  91313. }
  91314. return imageData;
  91315. };
  91316. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91317. var image = pixel_data;
  91318. var width = header.width, height = header.height;
  91319. var color, i = 0, x, y;
  91320. var imageData = new Uint8Array(width * height * 4);
  91321. for (y = y_start; y !== y_end; y += y_step) {
  91322. for (x = x_start; x !== x_end; x += x_step, i++) {
  91323. color = image[i];
  91324. imageData[(x + width * y) * 4 + 0] = color;
  91325. imageData[(x + width * y) * 4 + 1] = color;
  91326. imageData[(x + width * y) * 4 + 2] = color;
  91327. imageData[(x + width * y) * 4 + 3] = 255;
  91328. }
  91329. }
  91330. return imageData;
  91331. };
  91332. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91333. var image = pixel_data;
  91334. var width = header.width, height = header.height;
  91335. var i = 0, x, y;
  91336. var imageData = new Uint8Array(width * height * 4);
  91337. for (y = y_start; y !== y_end; y += y_step) {
  91338. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91339. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  91340. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  91341. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91342. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  91343. }
  91344. }
  91345. return imageData;
  91346. };
  91347. //private static _TYPE_NO_DATA = 0;
  91348. TGATools._TYPE_INDEXED = 1;
  91349. TGATools._TYPE_RGB = 2;
  91350. TGATools._TYPE_GREY = 3;
  91351. TGATools._TYPE_RLE_INDEXED = 9;
  91352. TGATools._TYPE_RLE_RGB = 10;
  91353. TGATools._TYPE_RLE_GREY = 11;
  91354. TGATools._ORIGIN_MASK = 0x30;
  91355. TGATools._ORIGIN_SHIFT = 0x04;
  91356. TGATools._ORIGIN_BL = 0x00;
  91357. TGATools._ORIGIN_BR = 0x01;
  91358. TGATools._ORIGIN_UL = 0x02;
  91359. TGATools._ORIGIN_UR = 0x03;
  91360. return TGATools;
  91361. }());
  91362. BABYLON.TGATools = TGATools;
  91363. })(BABYLON || (BABYLON = {}));
  91364. //# sourceMappingURL=babylon.tga.js.map
  91365. var BABYLON;
  91366. (function (BABYLON) {
  91367. /**
  91368. * Implementation of the TGA Texture Loader.
  91369. */
  91370. var TGATextureLoader = /** @class */ (function () {
  91371. function TGATextureLoader() {
  91372. /**
  91373. * Defines wether the loader supports cascade loading the different faces.
  91374. */
  91375. this.supportCascades = false;
  91376. }
  91377. /**
  91378. * This returns if the loader support the current file information.
  91379. * @param extension defines the file extension of the file being loaded
  91380. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91381. * @param fallback defines the fallback internal texture if any
  91382. * @param isBase64 defines whether the texture is encoded as a base64
  91383. * @param isBuffer defines whether the texture data are stored as a buffer
  91384. * @returns true if the loader can load the specified file
  91385. */
  91386. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91387. return extension.indexOf(".tga") === 0;
  91388. };
  91389. /**
  91390. * Transform the url before loading if required.
  91391. * @param rootUrl the url of the texture
  91392. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91393. * @returns the transformed texture
  91394. */
  91395. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91396. return rootUrl;
  91397. };
  91398. /**
  91399. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91400. * @param rootUrl the url of the texture
  91401. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91402. * @returns the fallback texture
  91403. */
  91404. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91405. return null;
  91406. };
  91407. /**
  91408. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91409. * @param data contains the texture data
  91410. * @param texture defines the BabylonJS internal texture
  91411. * @param createPolynomials will be true if polynomials have been requested
  91412. * @param onLoad defines the callback to trigger once the texture is ready
  91413. * @param onError defines the callback to trigger in case of error
  91414. */
  91415. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91416. throw ".env not supported in Cube.";
  91417. };
  91418. /**
  91419. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91420. * @param data contains the texture data
  91421. * @param texture defines the BabylonJS internal texture
  91422. * @param callback defines the method to call once ready to upload
  91423. */
  91424. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  91425. var uintData = new Uint8Array(data);
  91426. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  91427. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  91428. BABYLON.TGATools.UploadContent(texture, uintData);
  91429. });
  91430. };
  91431. return TGATextureLoader;
  91432. }());
  91433. // Register the loader.
  91434. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  91435. })(BABYLON || (BABYLON = {}));
  91436. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  91437. var BABYLON;
  91438. (function (BABYLON) {
  91439. /**
  91440. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  91441. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  91442. */
  91443. var KhronosTextureContainer = /** @class */ (function () {
  91444. /**
  91445. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  91446. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  91447. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  91448. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  91449. */
  91450. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  91451. this.arrayBuffer = arrayBuffer;
  91452. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  91453. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  91454. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  91455. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  91456. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  91457. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  91458. BABYLON.Tools.Error("texture missing KTX identifier");
  91459. return;
  91460. }
  91461. // load the reset of the header in native 32 bit int
  91462. var header = new Int32Array(this.arrayBuffer, 12, 13);
  91463. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  91464. var oppositeEndianess = header[0] === 0x01020304;
  91465. // read all the header elements in order they exist in the file, without modification (sans endainness)
  91466. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  91467. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  91468. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  91469. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  91470. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  91471. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  91472. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  91473. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  91474. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  91475. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  91476. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  91477. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  91478. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  91479. if (this.glType !== 0) {
  91480. BABYLON.Tools.Error("only compressed formats currently supported");
  91481. return;
  91482. }
  91483. else {
  91484. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  91485. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  91486. }
  91487. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  91488. BABYLON.Tools.Error("only 2D textures currently supported");
  91489. return;
  91490. }
  91491. if (this.numberOfArrayElements !== 0) {
  91492. BABYLON.Tools.Error("texture arrays not currently supported");
  91493. return;
  91494. }
  91495. if (this.numberOfFaces !== facesExpected) {
  91496. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  91497. return;
  91498. }
  91499. // we now have a completely validated file, so could use existence of loadType as success
  91500. // would need to make this more elaborate & adjust checks above to support more than one load type
  91501. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  91502. }
  91503. // not as fast hardware based, but will probably never need to use
  91504. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  91505. return ((val & 0xFF) << 24)
  91506. | ((val & 0xFF00) << 8)
  91507. | ((val >> 8) & 0xFF00)
  91508. | ((val >> 24) & 0xFF);
  91509. };
  91510. /**
  91511. * Uploads KTX content to a Babylon Texture.
  91512. * It is assumed that the texture has already been created & is currently bound
  91513. * @hidden
  91514. */
  91515. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  91516. switch (this.loadType) {
  91517. case KhronosTextureContainer.COMPRESSED_2D:
  91518. this._upload2DCompressedLevels(texture, loadMipmaps);
  91519. break;
  91520. case KhronosTextureContainer.TEX_2D:
  91521. case KhronosTextureContainer.COMPRESSED_3D:
  91522. case KhronosTextureContainer.TEX_3D:
  91523. }
  91524. };
  91525. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  91526. // initialize width & height for level 1
  91527. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  91528. var width = this.pixelWidth;
  91529. var height = this.pixelHeight;
  91530. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  91531. for (var level = 0; level < mipmapCount; level++) {
  91532. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  91533. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  91534. for (var face = 0; face < this.numberOfFaces; face++) {
  91535. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  91536. var engine = texture.getEngine();
  91537. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  91538. dataOffset += imageSize; // add size of the image for the next face/mipmap
  91539. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  91540. }
  91541. width = Math.max(1.0, width * 0.5);
  91542. height = Math.max(1.0, height * 0.5);
  91543. }
  91544. };
  91545. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  91546. // load types
  91547. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  91548. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  91549. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  91550. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  91551. return KhronosTextureContainer;
  91552. }());
  91553. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  91554. })(BABYLON || (BABYLON = {}));
  91555. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  91556. var BABYLON;
  91557. (function (BABYLON) {
  91558. /**
  91559. * Implementation of the KTX Texture Loader.
  91560. */
  91561. var KTXTextureLoader = /** @class */ (function () {
  91562. function KTXTextureLoader() {
  91563. /**
  91564. * Defines wether the loader supports cascade loading the different faces.
  91565. */
  91566. this.supportCascades = false;
  91567. }
  91568. /**
  91569. * This returns if the loader support the current file information.
  91570. * @param extension defines the file extension of the file being loaded
  91571. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91572. * @param fallback defines the fallback internal texture if any
  91573. * @param isBase64 defines whether the texture is encoded as a base64
  91574. * @param isBuffer defines whether the texture data are stored as a buffer
  91575. * @returns true if the loader can load the specified file
  91576. */
  91577. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91578. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  91579. return true;
  91580. }
  91581. return false;
  91582. };
  91583. /**
  91584. * Transform the url before loading if required.
  91585. * @param rootUrl the url of the texture
  91586. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91587. * @returns the transformed texture
  91588. */
  91589. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91590. var lastDot = rootUrl.lastIndexOf('.');
  91591. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  91592. };
  91593. /**
  91594. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91595. * @param rootUrl the url of the texture
  91596. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91597. * @returns the fallback texture
  91598. */
  91599. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91600. // remove the format appended to the rootUrl in the original createCubeTexture call.
  91601. var exp = new RegExp("" + textureFormatInUse + "$");
  91602. return rootUrl.replace(exp, "");
  91603. };
  91604. /**
  91605. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91606. * @param data contains the texture data
  91607. * @param texture defines the BabylonJS internal texture
  91608. * @param createPolynomials will be true if polynomials have been requested
  91609. * @param onLoad defines the callback to trigger once the texture is ready
  91610. * @param onError defines the callback to trigger in case of error
  91611. */
  91612. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91613. if (Array.isArray(data)) {
  91614. return;
  91615. }
  91616. var engine = texture.getEngine();
  91617. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  91618. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  91619. engine._unpackFlipY(true);
  91620. ktx.uploadLevels(texture, texture.generateMipMaps);
  91621. texture.width = ktx.pixelWidth;
  91622. texture.height = ktx.pixelHeight;
  91623. engine._setCubeMapTextureParams(loadMipmap);
  91624. texture.isReady = true;
  91625. };
  91626. /**
  91627. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91628. * @param data contains the texture data
  91629. * @param texture defines the BabylonJS internal texture
  91630. * @param callback defines the method to call once ready to upload
  91631. */
  91632. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  91633. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  91634. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  91635. ktx.uploadLevels(texture, texture.generateMipMaps);
  91636. });
  91637. };
  91638. return KTXTextureLoader;
  91639. }());
  91640. // Register the loader.
  91641. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  91642. })(BABYLON || (BABYLON = {}));
  91643. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  91644. var BABYLON;
  91645. (function (BABYLON) {
  91646. /**
  91647. * Sets of helpers addressing the serialization and deserialization of environment texture
  91648. * stored in a BabylonJS env file.
  91649. * Those files are usually stored as .env files.
  91650. */
  91651. var EnvironmentTextureTools = /** @class */ (function () {
  91652. function EnvironmentTextureTools() {
  91653. }
  91654. /**
  91655. * Gets the environment info from an env file.
  91656. * @param data The array buffer containing the .env bytes.
  91657. * @returns the environment file info (the json header) if successfully parsed.
  91658. */
  91659. EnvironmentTextureTools.GetEnvInfo = function (data) {
  91660. var dataView = new DataView(data);
  91661. var pos = 0;
  91662. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91663. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  91664. BABYLON.Tools.Error('Not a babylon environment map');
  91665. return null;
  91666. }
  91667. }
  91668. // Read json manifest - collect characters up to null terminator
  91669. var manifestString = '';
  91670. var charCode = 0x00;
  91671. while ((charCode = dataView.getUint8(pos++))) {
  91672. manifestString += String.fromCharCode(charCode);
  91673. }
  91674. var manifest = JSON.parse(manifestString);
  91675. if (manifest.specular) {
  91676. // Extend the header with the position of the payload.
  91677. manifest.specular.specularDataPosition = pos;
  91678. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  91679. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  91680. }
  91681. return manifest;
  91682. };
  91683. /**
  91684. * Creates an environment texture from a loaded cube texture.
  91685. * @param texture defines the cube texture to convert in env file
  91686. * @return a promise containing the environment data if succesfull.
  91687. */
  91688. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  91689. var _this = this;
  91690. var internalTexture = texture.getInternalTexture();
  91691. if (!internalTexture) {
  91692. return Promise.reject("The cube texture is invalid.");
  91693. }
  91694. if (!texture._prefiltered) {
  91695. return Promise.reject("The cube texture is invalid (not prefiltered).");
  91696. }
  91697. var engine = internalTexture.getEngine();
  91698. if (engine && engine.premultipliedAlpha) {
  91699. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  91700. }
  91701. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  91702. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  91703. }
  91704. var canvas = engine.getRenderingCanvas();
  91705. if (!canvas) {
  91706. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  91707. }
  91708. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91709. if (!engine.getCaps().textureFloatRender) {
  91710. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91711. if (!engine.getCaps().textureHalfFloatRender) {
  91712. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  91713. }
  91714. }
  91715. var cubeWidth = internalTexture.width;
  91716. var hostingScene = new BABYLON.Scene(engine);
  91717. var specularTextures = {};
  91718. var promises = [];
  91719. // Read and collect all mipmaps data from the cube.
  91720. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  91721. mipmapsCount = Math.round(mipmapsCount);
  91722. var _loop_1 = function (i) {
  91723. var faceWidth = Math.pow(2, mipmapsCount - i);
  91724. var _loop_2 = function (face) {
  91725. var data = texture.readPixels(face, i);
  91726. // Creates a temp texture with the face data.
  91727. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  91728. // And rgbdEncode them.
  91729. var promise = new Promise(function (resolve, reject) {
  91730. 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);
  91731. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91732. rgbdPostProcess.onApply = function (effect) {
  91733. effect._bindTexture("textureSampler", tempTexture);
  91734. };
  91735. // As the process needs to happen on the main canvas, keep track of the current size
  91736. var currentW = engine.getRenderWidth();
  91737. var currentH = engine.getRenderHeight();
  91738. // Set the desired size for the texture
  91739. engine.setSize(faceWidth, faceWidth);
  91740. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  91741. // Reading datas from WebGL
  91742. BABYLON.Tools.ToBlob(canvas, function (blob) {
  91743. var fileReader = new FileReader();
  91744. fileReader.onload = function (event) {
  91745. var arrayBuffer = event.target.result;
  91746. specularTextures[i * 6 + face] = arrayBuffer;
  91747. resolve();
  91748. };
  91749. fileReader.readAsArrayBuffer(blob);
  91750. });
  91751. // Reapply the previous canvas size
  91752. engine.setSize(currentW, currentH);
  91753. });
  91754. });
  91755. promises.push(promise);
  91756. };
  91757. // All faces of the cube.
  91758. for (var face = 0; face < 6; face++) {
  91759. _loop_2(face);
  91760. }
  91761. };
  91762. for (var i = 0; i <= mipmapsCount; i++) {
  91763. _loop_1(i);
  91764. }
  91765. // Once all the textures haves been collected as RGBD stored in PNGs
  91766. return Promise.all(promises).then(function () {
  91767. // We can delete the hosting scene keeping track of all the creation objects
  91768. hostingScene.dispose();
  91769. // Creates the json header for the env texture
  91770. var info = {
  91771. version: 1,
  91772. width: cubeWidth,
  91773. irradiance: _this._CreateEnvTextureIrradiance(texture),
  91774. specular: {
  91775. mipmaps: [],
  91776. lodGenerationScale: texture.lodGenerationScale
  91777. }
  91778. };
  91779. // Sets the specular image data information
  91780. var position = 0;
  91781. for (var i = 0; i <= mipmapsCount; i++) {
  91782. for (var face = 0; face < 6; face++) {
  91783. var byteLength = specularTextures[i * 6 + face].byteLength;
  91784. info.specular.mipmaps.push({
  91785. length: byteLength,
  91786. position: position
  91787. });
  91788. position += byteLength;
  91789. }
  91790. }
  91791. // Encode the JSON as an array buffer
  91792. var infoString = JSON.stringify(info);
  91793. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  91794. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  91795. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  91796. infoView[i] = infoString.charCodeAt(i);
  91797. }
  91798. // Ends up with a null terminator for easier parsing
  91799. infoView[infoString.length] = 0x00;
  91800. // Computes the final required size and creates the storage
  91801. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  91802. var finalBuffer = new ArrayBuffer(totalSize);
  91803. var finalBufferView = new Uint8Array(finalBuffer);
  91804. var dataView = new DataView(finalBuffer);
  91805. // Copy the magic bytes identifying the file in
  91806. var pos = 0;
  91807. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91808. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  91809. }
  91810. // Add the json info
  91811. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  91812. pos += infoBuffer.byteLength;
  91813. // Finally inserts the texture data
  91814. for (var i = 0; i <= mipmapsCount; i++) {
  91815. for (var face = 0; face < 6; face++) {
  91816. var dataBuffer = specularTextures[i * 6 + face];
  91817. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  91818. pos += dataBuffer.byteLength;
  91819. }
  91820. }
  91821. // Voila
  91822. return finalBuffer;
  91823. });
  91824. };
  91825. /**
  91826. * Creates a JSON representation of the spherical data.
  91827. * @param texture defines the texture containing the polynomials
  91828. * @return the JSON representation of the spherical info
  91829. */
  91830. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  91831. var polynmials = texture.sphericalPolynomial;
  91832. if (polynmials == null) {
  91833. return null;
  91834. }
  91835. return {
  91836. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  91837. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  91838. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  91839. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  91840. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  91841. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  91842. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  91843. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  91844. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  91845. };
  91846. };
  91847. /**
  91848. * Uploads the texture info contained in the env file to the GPU.
  91849. * @param texture defines the internal texture to upload to
  91850. * @param arrayBuffer defines the buffer cotaining the data to load
  91851. * @param info defines the texture info retrieved through the GetEnvInfo method
  91852. * @returns a promise
  91853. */
  91854. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  91855. if (info.version !== 1) {
  91856. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  91857. }
  91858. var specularInfo = info.specular;
  91859. if (!specularInfo) {
  91860. // Nothing else parsed so far
  91861. return Promise.resolve();
  91862. }
  91863. // Double checks the enclosed info
  91864. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  91865. mipmapsCount = Math.round(mipmapsCount) + 1;
  91866. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  91867. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  91868. }
  91869. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  91870. var imageData = new Array(mipmapsCount);
  91871. for (var i = 0; i < mipmapsCount; i++) {
  91872. imageData[i] = new Array(6);
  91873. for (var face = 0; face < 6; face++) {
  91874. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  91875. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  91876. }
  91877. }
  91878. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  91879. };
  91880. /**
  91881. * Uploads the levels of image data to the GPU.
  91882. * @param texture defines the internal texture to upload to
  91883. * @param imageData defines the array buffer views of image data [mipmap][face]
  91884. * @returns a promise
  91885. */
  91886. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  91887. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  91888. throw new Error("Texture size must be a power of two");
  91889. }
  91890. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  91891. // Gets everything ready.
  91892. var engine = texture.getEngine();
  91893. var expandTexture = false;
  91894. var generateNonLODTextures = false;
  91895. var rgbdPostProcess = null;
  91896. var cubeRtt = null;
  91897. var lodTextures = null;
  91898. var caps = engine.getCaps();
  91899. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91900. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91901. texture.generateMipMaps = true;
  91902. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  91903. // Add extra process if texture lod is not supported
  91904. if (!caps.textureLOD) {
  91905. expandTexture = false;
  91906. generateNonLODTextures = true;
  91907. lodTextures = {};
  91908. }
  91909. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  91910. else if (engine.webGLVersion < 2) {
  91911. expandTexture = false;
  91912. }
  91913. // If half float available we can uncompress the texture
  91914. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  91915. expandTexture = true;
  91916. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91917. }
  91918. // If full float available we can uncompress the texture
  91919. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  91920. expandTexture = true;
  91921. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91922. }
  91923. // Expand the texture if possible
  91924. if (expandTexture) {
  91925. // Simply run through the decode PP
  91926. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  91927. texture._isRGBD = false;
  91928. texture.invertY = false;
  91929. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  91930. generateDepthBuffer: false,
  91931. generateMipMaps: true,
  91932. generateStencilBuffer: false,
  91933. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  91934. type: texture.type,
  91935. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  91936. });
  91937. }
  91938. else {
  91939. texture._isRGBD = true;
  91940. texture.invertY = true;
  91941. // In case of missing support, applies the same patch than DDS files.
  91942. if (generateNonLODTextures) {
  91943. var mipSlices = 3;
  91944. var scale = texture._lodGenerationScale;
  91945. var offset = texture._lodGenerationOffset;
  91946. for (var i = 0; i < mipSlices; i++) {
  91947. //compute LOD from even spacing in smoothness (matching shader calculation)
  91948. var smoothness = i / (mipSlices - 1);
  91949. var roughness = 1 - smoothness;
  91950. var minLODIndex = offset; // roughness = 0
  91951. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  91952. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  91953. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  91954. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  91955. glTextureFromLod.isCube = true;
  91956. glTextureFromLod.invertY = true;
  91957. glTextureFromLod.generateMipMaps = false;
  91958. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  91959. // Wrap in a base texture for easy binding.
  91960. var lodTexture = new BABYLON.BaseTexture(null);
  91961. lodTexture.isCube = true;
  91962. lodTexture._texture = glTextureFromLod;
  91963. lodTextures[mipmapIndex] = lodTexture;
  91964. switch (i) {
  91965. case 0:
  91966. texture._lodTextureLow = lodTexture;
  91967. break;
  91968. case 1:
  91969. texture._lodTextureMid = lodTexture;
  91970. break;
  91971. case 2:
  91972. texture._lodTextureHigh = lodTexture;
  91973. break;
  91974. }
  91975. }
  91976. }
  91977. }
  91978. var promises = [];
  91979. var _loop_3 = function (i) {
  91980. var _loop_4 = function (face) {
  91981. // Constructs an image element from image data
  91982. var bytes = imageData[i][face];
  91983. var blob = new Blob([bytes], { type: 'image/png' });
  91984. var url = URL.createObjectURL(blob);
  91985. var image = new Image();
  91986. image.src = url;
  91987. // Enqueue promise to upload to the texture.
  91988. var promise = new Promise(function (resolve, reject) {
  91989. image.onload = function () {
  91990. if (expandTexture) {
  91991. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  91992. reject(message);
  91993. }, image);
  91994. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91995. // Uncompress the data to a RTT
  91996. rgbdPostProcess.onApply = function (effect) {
  91997. effect._bindTexture("textureSampler", tempTexture_1);
  91998. effect.setFloat2("scale", 1, 1);
  91999. };
  92000. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  92001. // Cleanup
  92002. engine.restoreDefaultFramebuffer();
  92003. tempTexture_1.dispose();
  92004. window.URL.revokeObjectURL(url);
  92005. resolve();
  92006. });
  92007. }
  92008. else {
  92009. engine._uploadImageToTexture(texture, image, face, i);
  92010. // Upload the face to the non lod texture support
  92011. if (generateNonLODTextures) {
  92012. var lodTexture = lodTextures[i];
  92013. if (lodTexture) {
  92014. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  92015. }
  92016. }
  92017. resolve();
  92018. }
  92019. };
  92020. image.onerror = function (error) {
  92021. reject(error);
  92022. };
  92023. });
  92024. promises.push(promise);
  92025. };
  92026. // All faces
  92027. for (var face = 0; face < 6; face++) {
  92028. _loop_4(face);
  92029. }
  92030. };
  92031. // All mipmaps up to provided number of images
  92032. for (var i = 0; i < imageData.length; i++) {
  92033. _loop_3(i);
  92034. }
  92035. // Fill remaining mipmaps with black textures.
  92036. if (imageData.length < mipmapsCount) {
  92037. var data = void 0;
  92038. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  92039. var dataLength = size * size * 4;
  92040. switch (texture.type) {
  92041. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  92042. data = new Uint8Array(dataLength);
  92043. break;
  92044. }
  92045. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  92046. data = new Uint16Array(dataLength);
  92047. break;
  92048. }
  92049. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  92050. data = new Float32Array(dataLength);
  92051. break;
  92052. }
  92053. }
  92054. for (var i = imageData.length; i < mipmapsCount; i++) {
  92055. for (var face = 0; face < 6; face++) {
  92056. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  92057. }
  92058. }
  92059. }
  92060. // Once all done, finishes the cleanup and return
  92061. return Promise.all(promises).then(function () {
  92062. // Release temp RTT.
  92063. if (cubeRtt) {
  92064. engine._releaseFramebufferObjects(cubeRtt);
  92065. cubeRtt._swapAndDie(texture);
  92066. }
  92067. // Release temp Post Process.
  92068. if (rgbdPostProcess) {
  92069. rgbdPostProcess.dispose();
  92070. }
  92071. // Flag internal texture as ready in case they are in use.
  92072. if (generateNonLODTextures) {
  92073. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  92074. texture._lodTextureHigh._texture.isReady = true;
  92075. }
  92076. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  92077. texture._lodTextureMid._texture.isReady = true;
  92078. }
  92079. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  92080. texture._lodTextureLow._texture.isReady = true;
  92081. }
  92082. }
  92083. });
  92084. };
  92085. /**
  92086. * Uploads spherical polynomials information to the texture.
  92087. * @param texture defines the texture we are trying to upload the information to
  92088. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  92089. */
  92090. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  92091. if (info.version !== 1) {
  92092. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  92093. }
  92094. var irradianceInfo = info.irradiance;
  92095. if (!irradianceInfo) {
  92096. return;
  92097. }
  92098. var sp = new BABYLON.SphericalPolynomial();
  92099. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  92100. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  92101. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  92102. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  92103. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  92104. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  92105. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  92106. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  92107. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  92108. texture._sphericalPolynomial = sp;
  92109. };
  92110. /**
  92111. * Magic number identifying the env file.
  92112. */
  92113. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  92114. return EnvironmentTextureTools;
  92115. }());
  92116. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  92117. })(BABYLON || (BABYLON = {}));
  92118. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  92119. var BABYLON;
  92120. (function (BABYLON) {
  92121. /**
  92122. * Implementation of the ENV Texture Loader.
  92123. */
  92124. var ENVTextureLoader = /** @class */ (function () {
  92125. function ENVTextureLoader() {
  92126. /**
  92127. * Defines wether the loader supports cascade loading the different faces.
  92128. */
  92129. this.supportCascades = false;
  92130. }
  92131. /**
  92132. * This returns if the loader support the current file information.
  92133. * @param extension defines the file extension of the file being loaded
  92134. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92135. * @param fallback defines the fallback internal texture if any
  92136. * @param isBase64 defines whether the texture is encoded as a base64
  92137. * @param isBuffer defines whether the texture data are stored as a buffer
  92138. * @returns true if the loader can load the specified file
  92139. */
  92140. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92141. return extension.indexOf(".env") === 0;
  92142. };
  92143. /**
  92144. * Transform the url before loading if required.
  92145. * @param rootUrl the url of the texture
  92146. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92147. * @returns the transformed texture
  92148. */
  92149. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92150. return rootUrl;
  92151. };
  92152. /**
  92153. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92154. * @param rootUrl the url of the texture
  92155. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92156. * @returns the fallback texture
  92157. */
  92158. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92159. return null;
  92160. };
  92161. /**
  92162. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92163. * @param data contains the texture data
  92164. * @param texture defines the BabylonJS internal texture
  92165. * @param createPolynomials will be true if polynomials have been requested
  92166. * @param onLoad defines the callback to trigger once the texture is ready
  92167. * @param onError defines the callback to trigger in case of error
  92168. */
  92169. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92170. if (Array.isArray(data)) {
  92171. return;
  92172. }
  92173. data = data;
  92174. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  92175. if (info) {
  92176. texture.width = info.width;
  92177. texture.height = info.width;
  92178. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  92179. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  92180. texture.isReady = true;
  92181. if (onLoad) {
  92182. onLoad();
  92183. }
  92184. });
  92185. }
  92186. else if (onError) {
  92187. onError("Can not parse the environment file", null);
  92188. }
  92189. };
  92190. /**
  92191. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92192. * @param data contains the texture data
  92193. * @param texture defines the BabylonJS internal texture
  92194. * @param callback defines the method to call once ready to upload
  92195. */
  92196. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  92197. throw ".env not supported in 2d.";
  92198. };
  92199. return ENVTextureLoader;
  92200. }());
  92201. // Register the loader.
  92202. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  92203. })(BABYLON || (BABYLON = {}));
  92204. //# sourceMappingURL=babylon.envTextureLoader.js.map
  92205. var BABYLON;
  92206. (function (BABYLON) {
  92207. /**
  92208. * Renders a layer on top of an existing scene
  92209. */
  92210. var UtilityLayerRenderer = /** @class */ (function () {
  92211. /**
  92212. * Instantiates a UtilityLayerRenderer
  92213. * @param originalScene the original scene that will be rendered on top of
  92214. */
  92215. function UtilityLayerRenderer(
  92216. /** the original scene that will be rendered on top of */
  92217. originalScene) {
  92218. var _this = this;
  92219. this.originalScene = originalScene;
  92220. this._pointerCaptures = {};
  92221. this._lastPointerEvents = {};
  92222. /**
  92223. * If the utility layer should automatically be rendered on top of existing scene
  92224. */
  92225. this.shouldRender = true;
  92226. /**
  92227. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  92228. */
  92229. this.onlyCheckPointerDownEvents = true;
  92230. /**
  92231. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  92232. */
  92233. this.processAllEvents = false;
  92234. /**
  92235. * Observable raised when the pointer move from the utility layer scene to the main scene
  92236. */
  92237. this.onPointerOutObservable = new BABYLON.Observable();
  92238. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  92239. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  92240. this.utilityLayerScene._allowPostProcessClearColor = false;
  92241. originalScene.getEngine().scenes.pop();
  92242. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  92243. this.utilityLayerScene.detachControl();
  92244. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  92245. if (!_this.processAllEvents) {
  92246. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  92247. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  92248. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  92249. return;
  92250. }
  92251. }
  92252. var pointerEvent = (prePointerInfo.event);
  92253. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  92254. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92255. return;
  92256. }
  92257. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  92258. if (!prePointerInfo.ray && utilityScenePick) {
  92259. prePointerInfo.ray = utilityScenePick.ray;
  92260. }
  92261. // always fire the prepointer oversvable
  92262. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  92263. // allow every non pointer down event to flow to the utility layer
  92264. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  92265. if (!prePointerInfo.skipOnPointerObservable) {
  92266. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92267. }
  92268. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  92269. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92270. }
  92271. return;
  92272. }
  92273. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  92274. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  92275. if (utilityScenePick && utilityScenePick.hit) {
  92276. if (!prePointerInfo.skipOnPointerObservable) {
  92277. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92278. }
  92279. prePointerInfo.skipOnPointerObservable = true;
  92280. }
  92281. }
  92282. else {
  92283. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  92284. var pointerEvent_1 = (prePointerInfo.event);
  92285. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  92286. if (originalScenePick && utilityScenePick) {
  92287. // No pick in utility scene
  92288. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  92289. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92290. // We touched an utility mesh present in the main scene
  92291. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92292. prePointerInfo.skipOnPointerObservable = true;
  92293. }
  92294. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92295. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  92296. }
  92297. }
  92298. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  92299. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  92300. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  92301. // If a previous utility layer set this, do not unset this
  92302. if (!prePointerInfo.skipOnPointerObservable) {
  92303. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  92304. }
  92305. }
  92306. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  92307. // We have a pick in both scenes but main is closer than utility
  92308. // We touched an utility mesh present in the main scene
  92309. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92310. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92311. prePointerInfo.skipOnPointerObservable = true;
  92312. }
  92313. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  92314. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  92315. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  92316. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  92317. }
  92318. }
  92319. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  92320. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  92321. }
  92322. }
  92323. }
  92324. });
  92325. // Render directly on top of existing scene without clearing
  92326. this.utilityLayerScene.autoClear = false;
  92327. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  92328. if (_this.shouldRender) {
  92329. _this.render();
  92330. }
  92331. });
  92332. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  92333. _this.dispose();
  92334. });
  92335. this._updateCamera();
  92336. }
  92337. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  92338. /**
  92339. * 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)
  92340. */
  92341. get: function () {
  92342. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  92343. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92344. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92345. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92346. });
  92347. }
  92348. return UtilityLayerRenderer._DefaultUtilityLayer;
  92349. },
  92350. enumerable: true,
  92351. configurable: true
  92352. });
  92353. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  92354. /**
  92355. * 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)
  92356. */
  92357. get: function () {
  92358. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  92359. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92360. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  92361. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92362. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92363. });
  92364. }
  92365. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  92366. },
  92367. enumerable: true,
  92368. configurable: true
  92369. });
  92370. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  92371. if (!prePointerInfo.skipOnPointerObservable) {
  92372. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  92373. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  92374. }
  92375. };
  92376. /**
  92377. * Renders the utility layers scene on top of the original scene
  92378. */
  92379. UtilityLayerRenderer.prototype.render = function () {
  92380. this._updateCamera();
  92381. if (this.utilityLayerScene.activeCamera) {
  92382. // Set the camera's scene to utility layers scene
  92383. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  92384. var camera = this.utilityLayerScene.activeCamera;
  92385. camera._scene = this.utilityLayerScene;
  92386. if (camera.leftCamera) {
  92387. camera.leftCamera._scene = this.utilityLayerScene;
  92388. }
  92389. if (camera.rightCamera) {
  92390. camera.rightCamera._scene = this.utilityLayerScene;
  92391. }
  92392. this.utilityLayerScene.render(false);
  92393. // Reset camera's scene back to original
  92394. camera._scene = oldScene;
  92395. if (camera.leftCamera) {
  92396. camera.leftCamera._scene = oldScene;
  92397. }
  92398. if (camera.rightCamera) {
  92399. camera.rightCamera._scene = oldScene;
  92400. }
  92401. }
  92402. };
  92403. /**
  92404. * Disposes of the renderer
  92405. */
  92406. UtilityLayerRenderer.prototype.dispose = function () {
  92407. this.onPointerOutObservable.clear();
  92408. if (this._afterRenderObserver) {
  92409. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  92410. }
  92411. if (this._sceneDisposeObserver) {
  92412. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  92413. }
  92414. if (this._originalPointerObserver) {
  92415. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  92416. }
  92417. this.utilityLayerScene.dispose();
  92418. };
  92419. UtilityLayerRenderer.prototype._updateCamera = function () {
  92420. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  92421. };
  92422. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92423. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92424. return UtilityLayerRenderer;
  92425. }());
  92426. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  92427. })(BABYLON || (BABYLON = {}));
  92428. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  92429. //# sourceMappingURL=babylon.behavior.js.map
  92430. var BABYLON;
  92431. (function (BABYLON) {
  92432. /**
  92433. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  92434. */
  92435. var PointerDragBehavior = /** @class */ (function () {
  92436. /**
  92437. * Creates a pointer drag behavior that can be attached to a mesh
  92438. * @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)
  92439. */
  92440. function PointerDragBehavior(options) {
  92441. /**
  92442. * 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)
  92443. */
  92444. this.maxDragAngle = 0;
  92445. /**
  92446. * @hidden
  92447. */
  92448. this._useAlternatePickedPointAboveMaxDragAngle = false;
  92449. /**
  92450. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  92451. */
  92452. this.currentDraggingPointerID = -1;
  92453. /**
  92454. * If the behavior is currently in a dragging state
  92455. */
  92456. this.dragging = false;
  92457. /**
  92458. * 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)
  92459. */
  92460. this.dragDeltaRatio = 0.2;
  92461. /**
  92462. * If the drag plane orientation should be updated during the dragging (Default: true)
  92463. */
  92464. this.updateDragPlane = true;
  92465. // Debug mode will display drag planes to help visualize behavior
  92466. this._debugMode = false;
  92467. this._moving = false;
  92468. /**
  92469. * Fires each time the attached mesh is dragged with the pointer
  92470. * * delta between last drag position and current drag position in world space
  92471. * * dragDistance along the drag axis
  92472. * * dragPlaneNormal normal of the current drag plane used during the drag
  92473. * * dragPlanePoint in world space where the drag intersects the drag plane
  92474. */
  92475. this.onDragObservable = new BABYLON.Observable();
  92476. /**
  92477. * Fires each time a drag begins (eg. mouse down on mesh)
  92478. */
  92479. this.onDragStartObservable = new BABYLON.Observable();
  92480. /**
  92481. * Fires each time a drag ends (eg. mouse release after drag)
  92482. */
  92483. this.onDragEndObservable = new BABYLON.Observable();
  92484. /**
  92485. * If the attached mesh should be moved when dragged
  92486. */
  92487. this.moveAttached = true;
  92488. /**
  92489. * If the drag behavior will react to drag events (Default: true)
  92490. */
  92491. this.enabled = true;
  92492. /**
  92493. * If camera controls should be detached during the drag
  92494. */
  92495. this.detachCameraControls = true;
  92496. /**
  92497. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  92498. */
  92499. this.useObjectOrienationForDragging = true;
  92500. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92501. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  92502. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  92503. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92504. this._attachedElement = null;
  92505. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92506. this._lastPointerRay = {};
  92507. this._dragDelta = new BABYLON.Vector3();
  92508. // Variables to avoid instantiation in the below method
  92509. this._pointA = new BABYLON.Vector3(0, 0, 0);
  92510. this._pointB = new BABYLON.Vector3(0, 0, 0);
  92511. this._pointC = new BABYLON.Vector3(0, 0, 0);
  92512. this._lineA = new BABYLON.Vector3(0, 0, 0);
  92513. this._lineB = new BABYLON.Vector3(0, 0, 0);
  92514. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  92515. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  92516. this._options = options ? options : {};
  92517. var optionCount = 0;
  92518. if (this._options.dragAxis) {
  92519. optionCount++;
  92520. }
  92521. if (this._options.dragPlaneNormal) {
  92522. optionCount++;
  92523. }
  92524. if (optionCount > 1) {
  92525. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  92526. }
  92527. }
  92528. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  92529. /**
  92530. * The name of the behavior
  92531. */
  92532. get: function () {
  92533. return "PointerDrag";
  92534. },
  92535. enumerable: true,
  92536. configurable: true
  92537. });
  92538. /**
  92539. * Initializes the behavior
  92540. */
  92541. PointerDragBehavior.prototype.init = function () { };
  92542. /**
  92543. * Attaches the drag behavior the passed in mesh
  92544. * @param ownerNode The mesh that will be dragged around once attached
  92545. */
  92546. PointerDragBehavior.prototype.attach = function (ownerNode) {
  92547. var _this = this;
  92548. this._scene = ownerNode.getScene();
  92549. this._attachedNode = ownerNode;
  92550. // Initialize drag plane to not interfere with existing scene
  92551. if (!PointerDragBehavior._planeScene) {
  92552. if (this._debugMode) {
  92553. PointerDragBehavior._planeScene = this._scene;
  92554. }
  92555. else {
  92556. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  92557. PointerDragBehavior._planeScene.detachControl();
  92558. this._scene.getEngine().scenes.pop();
  92559. this._scene.onDisposeObservable.addOnce(function () {
  92560. PointerDragBehavior._planeScene.dispose();
  92561. PointerDragBehavior._planeScene = null;
  92562. });
  92563. }
  92564. }
  92565. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  92566. // State of the drag
  92567. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  92568. var pickPredicate = function (m) {
  92569. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  92570. };
  92571. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92572. if (!_this.enabled) {
  92573. return;
  92574. }
  92575. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92576. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92577. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  92578. }
  92579. }
  92580. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  92581. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  92582. _this.releaseDrag();
  92583. }
  92584. }
  92585. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  92586. var pointerId = pointerInfo.event.pointerId;
  92587. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  92588. if (!_this._lastPointerRay[pointerId]) {
  92589. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92590. }
  92591. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  92592. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  92593. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  92594. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  92595. _this._moveDrag(pointerInfo.pickInfo.ray);
  92596. }
  92597. }
  92598. }
  92599. });
  92600. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  92601. if (_this._moving && _this.moveAttached) {
  92602. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  92603. // Slowly move mesh to avoid jitter
  92604. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  92605. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  92606. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  92607. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  92608. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  92609. }
  92610. });
  92611. };
  92612. PointerDragBehavior.prototype.releaseDrag = function () {
  92613. this.dragging = false;
  92614. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  92615. this.currentDraggingPointerID = -1;
  92616. this._moving = false;
  92617. // Reattach camera controls
  92618. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92619. this._scene.activeCamera.attachControl(this._attachedElement, true);
  92620. }
  92621. };
  92622. /**
  92623. * Simulates the start of a pointer drag event on the behavior
  92624. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  92625. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  92626. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  92627. */
  92628. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  92629. if (pointerId === void 0) { pointerId = 1; }
  92630. this._startDrag(pointerId, fromRay, startPickedPoint);
  92631. if (this._lastPointerRay[pointerId]) {
  92632. // if there was a last pointer ray drag the object there
  92633. this._moveDrag(this._lastPointerRay[pointerId]);
  92634. }
  92635. };
  92636. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  92637. if (pointerId === void 0) { pointerId = 1; }
  92638. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  92639. return;
  92640. }
  92641. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  92642. // Create start ray from the camera to the object
  92643. if (fromRay) {
  92644. this._startDragRay.direction.copyFrom(fromRay.direction);
  92645. this._startDragRay.origin.copyFrom(fromRay.origin);
  92646. }
  92647. else {
  92648. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  92649. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  92650. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  92651. }
  92652. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  92653. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  92654. if (pickedPoint) {
  92655. this.dragging = true;
  92656. this.currentDraggingPointerID = pointerId;
  92657. this.lastDragPosition.copyFrom(pickedPoint);
  92658. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  92659. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  92660. // Detatch camera controls
  92661. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92662. if (this._scene.activeCamera.inputs.attachedElement) {
  92663. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  92664. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  92665. }
  92666. else {
  92667. this._attachedElement = null;
  92668. }
  92669. }
  92670. }
  92671. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  92672. };
  92673. PointerDragBehavior.prototype._moveDrag = function (ray) {
  92674. this._moving = true;
  92675. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  92676. if (pickedPoint) {
  92677. if (this.updateDragPlane) {
  92678. this._updateDragPlanePosition(ray, pickedPoint);
  92679. }
  92680. var dragLength = 0;
  92681. // depending on the drag mode option drag accordingly
  92682. if (this._options.dragAxis) {
  92683. // Convert local drag axis to world
  92684. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  92685. // Project delta drag from the drag plane onto the drag axis
  92686. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  92687. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  92688. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  92689. }
  92690. else {
  92691. dragLength = this._dragDelta.length();
  92692. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  92693. }
  92694. this._targetPosition.addInPlace(this._dragDelta);
  92695. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  92696. this.lastDragPosition.copyFrom(pickedPoint);
  92697. }
  92698. };
  92699. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  92700. var _this = this;
  92701. if (!ray) {
  92702. return null;
  92703. }
  92704. // Calculate angle between plane normal and ray
  92705. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  92706. // Correct if ray is casted from oposite side
  92707. if (angle > Math.PI / 2) {
  92708. angle = Math.PI - angle;
  92709. }
  92710. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  92711. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  92712. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  92713. // Invert ray direction along the towards object axis
  92714. this._tmpVector.copyFrom(ray.direction);
  92715. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  92716. this._alternatePickedPoint.normalize();
  92717. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  92718. this._tmpVector.addInPlace(this._alternatePickedPoint);
  92719. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  92720. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  92721. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  92722. this._alternatePickedPoint.addInPlace(this._tmpVector);
  92723. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  92724. return this._alternatePickedPoint;
  92725. }
  92726. else {
  92727. return null;
  92728. }
  92729. }
  92730. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  92731. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  92732. return pickResult.pickedPoint;
  92733. }
  92734. else {
  92735. return null;
  92736. }
  92737. };
  92738. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  92739. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  92740. this._pointA.copyFrom(dragPlanePosition);
  92741. if (this._options.dragAxis) {
  92742. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  92743. // Calculate plane normal in direction of camera but perpendicular to drag axis
  92744. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  92745. ray.origin.subtractToRef(this._pointA, this._pointC);
  92746. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  92747. // Get perpendicular line from direction to camera and drag axis
  92748. this._pointB.subtractToRef(this._pointA, this._lineA);
  92749. this._pointC.subtractToRef(this._pointA, this._lineB);
  92750. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  92751. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  92752. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  92753. this._lookAt.normalize();
  92754. this._dragPlane.position.copyFrom(this._pointA);
  92755. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  92756. this._dragPlane.lookAt(this._lookAt);
  92757. }
  92758. else if (this._options.dragPlaneNormal) {
  92759. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  92760. this._dragPlane.position.copyFrom(this._pointA);
  92761. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  92762. this._dragPlane.lookAt(this._lookAt);
  92763. }
  92764. else {
  92765. this._dragPlane.position.copyFrom(this._pointA);
  92766. this._dragPlane.lookAt(ray.origin);
  92767. }
  92768. this._dragPlane.computeWorldMatrix(true);
  92769. };
  92770. /**
  92771. * Detaches the behavior from the mesh
  92772. */
  92773. PointerDragBehavior.prototype.detach = function () {
  92774. if (this._pointerObserver) {
  92775. this._scene.onPointerObservable.remove(this._pointerObserver);
  92776. }
  92777. if (this._beforeRenderObserver) {
  92778. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92779. }
  92780. };
  92781. return PointerDragBehavior;
  92782. }());
  92783. BABYLON.PointerDragBehavior = PointerDragBehavior;
  92784. })(BABYLON || (BABYLON = {}));
  92785. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  92786. var BABYLON;
  92787. (function (BABYLON) {
  92788. /**
  92789. * A behavior that when attached to a mesh will allow the mesh to be scaled
  92790. */
  92791. var MultiPointerScaleBehavior = /** @class */ (function () {
  92792. function MultiPointerScaleBehavior() {
  92793. this._startDistance = 0;
  92794. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  92795. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  92796. this._sceneRenderObserver = null;
  92797. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  92798. this._dragBehaviorA.moveAttached = false;
  92799. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  92800. this._dragBehaviorB.moveAttached = false;
  92801. }
  92802. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  92803. /**
  92804. * The name of the behavior
  92805. */
  92806. get: function () {
  92807. return "MultiPointerScale";
  92808. },
  92809. enumerable: true,
  92810. configurable: true
  92811. });
  92812. /**
  92813. * Initializes the behavior
  92814. */
  92815. MultiPointerScaleBehavior.prototype.init = function () { };
  92816. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  92817. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  92818. };
  92819. /**
  92820. * Attaches the scale behavior the passed in mesh
  92821. * @param ownerNode The mesh that will be scaled around once attached
  92822. */
  92823. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  92824. var _this = this;
  92825. this._ownerNode = ownerNode;
  92826. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  92827. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  92828. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92829. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92830. _this._dragBehaviorA.releaseDrag();
  92831. }
  92832. else {
  92833. _this._initialScale.copyFrom(ownerNode.scaling);
  92834. _this._startDistance = _this._getCurrentDistance();
  92835. }
  92836. }
  92837. });
  92838. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  92839. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92840. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92841. _this._dragBehaviorB.releaseDrag();
  92842. }
  92843. else {
  92844. _this._initialScale.copyFrom(ownerNode.scaling);
  92845. _this._startDistance = _this._getCurrentDistance();
  92846. }
  92847. }
  92848. });
  92849. // Once both drag behaviors are active scale based on the distance between the two pointers
  92850. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92851. behavior.onDragObservable.add(function () {
  92852. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92853. var ratio = _this._getCurrentDistance() / _this._startDistance;
  92854. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  92855. }
  92856. });
  92857. });
  92858. ownerNode.addBehavior(this._dragBehaviorA);
  92859. ownerNode.addBehavior(this._dragBehaviorB);
  92860. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  92861. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  92862. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92863. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  92864. if (change.length() > 0.01) {
  92865. ownerNode.scaling.addInPlace(change);
  92866. }
  92867. }
  92868. });
  92869. };
  92870. /**
  92871. * Detaches the behavior from the mesh
  92872. */
  92873. MultiPointerScaleBehavior.prototype.detach = function () {
  92874. var _this = this;
  92875. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  92876. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92877. behavior.onDragStartObservable.clear();
  92878. behavior.onDragObservable.clear();
  92879. _this._ownerNode.removeBehavior(behavior);
  92880. });
  92881. };
  92882. return MultiPointerScaleBehavior;
  92883. }());
  92884. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  92885. })(BABYLON || (BABYLON = {}));
  92886. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  92887. var BABYLON;
  92888. (function (BABYLON) {
  92889. /**
  92890. * 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
  92891. */
  92892. var SixDofDragBehavior = /** @class */ (function () {
  92893. function SixDofDragBehavior() {
  92894. this._sceneRenderObserver = null;
  92895. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92896. this._moving = false;
  92897. this._startingOrientation = new BABYLON.Quaternion();
  92898. /**
  92899. * 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)
  92900. */
  92901. this.zDragFactor = 3;
  92902. /**
  92903. * If the behavior is currently in a dragging state
  92904. */
  92905. this.dragging = false;
  92906. /**
  92907. * 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)
  92908. */
  92909. this.dragDeltaRatio = 0.2;
  92910. /**
  92911. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  92912. */
  92913. this.currentDraggingPointerID = -1;
  92914. /**
  92915. * If camera controls should be detached during the drag
  92916. */
  92917. this.detachCameraControls = true;
  92918. }
  92919. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  92920. /**
  92921. * The name of the behavior
  92922. */
  92923. get: function () {
  92924. return "SixDofDrag";
  92925. },
  92926. enumerable: true,
  92927. configurable: true
  92928. });
  92929. /**
  92930. * Initializes the behavior
  92931. */
  92932. SixDofDragBehavior.prototype.init = function () { };
  92933. /**
  92934. * Attaches the scale behavior the passed in mesh
  92935. * @param ownerNode The mesh that will be scaled around once attached
  92936. */
  92937. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  92938. var _this = this;
  92939. this._ownerNode = ownerNode;
  92940. this._scene = this._ownerNode.getScene();
  92941. if (!SixDofDragBehavior._virtualScene) {
  92942. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  92943. this._scene.getEngine().scenes.pop();
  92944. }
  92945. var pickedMesh = null;
  92946. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  92947. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  92948. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92949. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  92950. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92951. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  92952. var pickPredicate = function (m) {
  92953. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  92954. };
  92955. var attachedElement = null;
  92956. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92957. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92958. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92959. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  92960. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  92961. }
  92962. pickedMesh = _this._ownerNode;
  92963. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  92964. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  92965. // Set position and orientation of the controller
  92966. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  92967. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  92968. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  92969. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  92970. pickedMesh.computeWorldMatrix();
  92971. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  92972. if (!pickedMesh.rotationQuaternion) {
  92973. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  92974. }
  92975. var oldParent = pickedMesh.parent;
  92976. pickedMesh.setParent(null);
  92977. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  92978. pickedMesh.setParent(oldParent);
  92979. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  92980. // Update state
  92981. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  92982. _this.dragging = true;
  92983. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  92984. // Detatch camera controls
  92985. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  92986. if (_this._scene.activeCamera.inputs.attachedElement) {
  92987. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  92988. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  92989. }
  92990. else {
  92991. attachedElement = null;
  92992. }
  92993. }
  92994. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  92995. }
  92996. }
  92997. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  92998. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  92999. _this.dragging = false;
  93000. _this._moving = false;
  93001. _this.currentDraggingPointerID = -1;
  93002. pickedMesh = null;
  93003. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93004. // Reattach camera controls
  93005. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93006. _this._scene.activeCamera.attachControl(attachedElement, true);
  93007. }
  93008. }
  93009. }
  93010. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93011. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  93012. var zDragFactor = _this.zDragFactor;
  93013. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93014. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93015. zDragFactor = 0;
  93016. }
  93017. // Calculate controller drag distance in controller space
  93018. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  93019. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93020. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  93021. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93022. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  93023. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  93024. if (_this._virtualDragMesh.position.z < 0) {
  93025. _this._virtualDragMesh.position.z = 0;
  93026. }
  93027. // Update the controller position
  93028. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93029. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93030. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93031. // Move the virtualObjectsPosition into the picked mesh's space if needed
  93032. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93033. if (pickedMesh.parent) {
  93034. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  93035. }
  93036. if (!_this._moving) {
  93037. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  93038. }
  93039. _this._moving = true;
  93040. }
  93041. }
  93042. });
  93043. var tmpQuaternion = new BABYLON.Quaternion();
  93044. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93045. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93046. if (_this.dragging && _this._moving && pickedMesh) {
  93047. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93048. // Slowly move mesh to avoid jitter
  93049. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  93050. // Get change in rotation
  93051. tmpQuaternion.copyFrom(_this._startingOrientation);
  93052. tmpQuaternion.x = -tmpQuaternion.x;
  93053. tmpQuaternion.y = -tmpQuaternion.y;
  93054. tmpQuaternion.z = -tmpQuaternion.z;
  93055. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  93056. // Convert change in rotation to only y axis rotation
  93057. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  93058. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  93059. // Slowly move mesh to avoid jitter
  93060. var oldParent = pickedMesh.parent;
  93061. pickedMesh.setParent(null);
  93062. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  93063. pickedMesh.setParent(oldParent);
  93064. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93065. }
  93066. });
  93067. };
  93068. /**
  93069. * Detaches the behavior from the mesh
  93070. */
  93071. SixDofDragBehavior.prototype.detach = function () {
  93072. if (this._scene) {
  93073. this._scene.onPointerObservable.remove(this._pointerObserver);
  93074. }
  93075. if (this._ownerNode) {
  93076. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93077. }
  93078. if (this._virtualOriginMesh) {
  93079. this._virtualOriginMesh.dispose();
  93080. }
  93081. if (this._virtualDragMesh) {
  93082. this._virtualDragMesh.dispose();
  93083. }
  93084. };
  93085. return SixDofDragBehavior;
  93086. }());
  93087. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  93088. })(BABYLON || (BABYLON = {}));
  93089. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  93090. var BABYLON;
  93091. (function (BABYLON) {
  93092. /**
  93093. * @hidden
  93094. */
  93095. var FaceDirectionInfo = /** @class */ (function () {
  93096. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  93097. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  93098. if (diff === void 0) { diff = 0; }
  93099. if (ignore === void 0) { ignore = false; }
  93100. this.direction = direction;
  93101. this.rotatedDirection = rotatedDirection;
  93102. this.diff = diff;
  93103. this.ignore = ignore;
  93104. }
  93105. return FaceDirectionInfo;
  93106. }());
  93107. /**
  93108. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  93109. */
  93110. var AttachToBoxBehavior = /** @class */ (function () {
  93111. /**
  93112. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  93113. * @param ui The transform node that should be attched to the mesh
  93114. */
  93115. function AttachToBoxBehavior(ui) {
  93116. this.ui = ui;
  93117. /**
  93118. * The name of the behavior
  93119. */
  93120. this.name = "AttachToBoxBehavior";
  93121. /**
  93122. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  93123. */
  93124. this.distanceAwayFromFace = 0.15;
  93125. /**
  93126. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  93127. */
  93128. this.distanceAwayFromBottomOfFace = 0.15;
  93129. 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))];
  93130. this._tmpMatrix = new BABYLON.Matrix();
  93131. this._tmpVector = new BABYLON.Vector3();
  93132. this._zeroVector = BABYLON.Vector3.Zero();
  93133. this._lookAtTmpMatrix = new BABYLON.Matrix();
  93134. /* Does nothing */
  93135. }
  93136. /**
  93137. * Initializes the behavior
  93138. */
  93139. AttachToBoxBehavior.prototype.init = function () {
  93140. /* Does nothing */
  93141. };
  93142. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  93143. var _this = this;
  93144. // Go over each face and calculate the angle between the face's normal and targetDirection
  93145. this._faceVectors.forEach(function (v) {
  93146. if (!_this._target.rotationQuaternion) {
  93147. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  93148. }
  93149. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  93150. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  93151. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  93152. });
  93153. // Return the face information of the one with the normal closeset to target direction
  93154. return this._faceVectors.reduce(function (min, p) {
  93155. if (min.ignore) {
  93156. return p;
  93157. }
  93158. else if (p.ignore) {
  93159. return min;
  93160. }
  93161. else {
  93162. return min.diff < p.diff ? min : p;
  93163. }
  93164. }, this._faceVectors[0]);
  93165. };
  93166. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  93167. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  93168. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  93169. this._lookAtTmpMatrix.invert();
  93170. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  93171. };
  93172. /**
  93173. * Attaches the AttachToBoxBehavior to the passed in mesh
  93174. * @param target The mesh that the specified node will be attached to
  93175. */
  93176. AttachToBoxBehavior.prototype.attach = function (target) {
  93177. var _this = this;
  93178. this._target = target;
  93179. this._scene = this._target.getScene();
  93180. // Every frame, update the app bars position
  93181. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93182. if (!_this._scene.activeCamera) {
  93183. return;
  93184. }
  93185. // Find the face closest to the cameras position
  93186. var cameraPos = _this._scene.activeCamera.position;
  93187. if (_this._scene.activeCamera.devicePosition) {
  93188. cameraPos = _this._scene.activeCamera.devicePosition;
  93189. }
  93190. var facing = _this._closestFace(cameraPos.subtract(target.position));
  93191. if (_this._scene.activeCamera.leftCamera) {
  93192. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93193. }
  93194. else {
  93195. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93196. }
  93197. // Get camera up direction
  93198. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  93199. // Ignore faces to not select a parrelel face for the up vector of the UI
  93200. _this._faceVectors.forEach(function (v) {
  93201. if (facing.direction.x && v.direction.x) {
  93202. v.ignore = true;
  93203. }
  93204. if (facing.direction.y && v.direction.y) {
  93205. v.ignore = true;
  93206. }
  93207. if (facing.direction.z && v.direction.z) {
  93208. v.ignore = true;
  93209. }
  93210. });
  93211. var facingUp = _this._closestFace(_this._tmpVector);
  93212. // Unignore faces
  93213. _this._faceVectors.forEach(function (v) {
  93214. v.ignore = false;
  93215. });
  93216. // Position the app bar on that face
  93217. _this.ui.position.copyFrom(target.position);
  93218. if (facing.direction.x) {
  93219. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93220. _this.ui.position.addInPlace(_this._tmpVector);
  93221. }
  93222. if (facing.direction.y) {
  93223. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93224. _this.ui.position.addInPlace(_this._tmpVector);
  93225. }
  93226. if (facing.direction.z) {
  93227. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93228. _this.ui.position.addInPlace(_this._tmpVector);
  93229. }
  93230. // Rotate to be oriented properly to the camera
  93231. if (!_this.ui.rotationQuaternion) {
  93232. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  93233. }
  93234. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  93235. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  93236. // Place ui the correct distance from the bottom of the mesh
  93237. if (facingUp.direction.x) {
  93238. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  93239. }
  93240. if (facingUp.direction.y) {
  93241. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  93242. }
  93243. if (facingUp.direction.z) {
  93244. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  93245. }
  93246. _this.ui.position.addInPlace(_this._tmpVector);
  93247. });
  93248. };
  93249. /**
  93250. * Detaches the behavior from the mesh
  93251. */
  93252. AttachToBoxBehavior.prototype.detach = function () {
  93253. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  93254. };
  93255. return AttachToBoxBehavior;
  93256. }());
  93257. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  93258. })(BABYLON || (BABYLON = {}));
  93259. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  93260. var BABYLON;
  93261. (function (BABYLON) {
  93262. /**
  93263. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  93264. */
  93265. var FadeInOutBehavior = /** @class */ (function () {
  93266. /**
  93267. * Instatiates the FadeInOutBehavior
  93268. */
  93269. function FadeInOutBehavior() {
  93270. var _this = this;
  93271. /**
  93272. * Time in milliseconds to delay before fading in (Default: 0)
  93273. */
  93274. this.delay = 0;
  93275. /**
  93276. * Time in milliseconds for the mesh to fade in (Default: 300)
  93277. */
  93278. this.fadeInTime = 300;
  93279. this._millisecondsPerFrame = 1000 / 60;
  93280. this._hovered = false;
  93281. this._hoverValue = 0;
  93282. this._ownerNode = null;
  93283. this._update = function () {
  93284. if (_this._ownerNode) {
  93285. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  93286. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  93287. if (_this._ownerNode.visibility > 1) {
  93288. _this._setAllVisibility(_this._ownerNode, 1);
  93289. _this._hoverValue = _this.fadeInTime + _this.delay;
  93290. return;
  93291. }
  93292. else if (_this._ownerNode.visibility < 0) {
  93293. _this._setAllVisibility(_this._ownerNode, 0);
  93294. if (_this._hoverValue < 0) {
  93295. _this._hoverValue = 0;
  93296. return;
  93297. }
  93298. }
  93299. setTimeout(_this._update, _this._millisecondsPerFrame);
  93300. }
  93301. };
  93302. }
  93303. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  93304. /**
  93305. * The name of the behavior
  93306. */
  93307. get: function () {
  93308. return "FadeInOut";
  93309. },
  93310. enumerable: true,
  93311. configurable: true
  93312. });
  93313. /**
  93314. * Initializes the behavior
  93315. */
  93316. FadeInOutBehavior.prototype.init = function () {
  93317. };
  93318. /**
  93319. * Attaches the fade behavior on the passed in mesh
  93320. * @param ownerNode The mesh that will be faded in/out once attached
  93321. */
  93322. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  93323. this._ownerNode = ownerNode;
  93324. this._setAllVisibility(this._ownerNode, 0);
  93325. };
  93326. /**
  93327. * Detaches the behavior from the mesh
  93328. */
  93329. FadeInOutBehavior.prototype.detach = function () {
  93330. this._ownerNode = null;
  93331. };
  93332. /**
  93333. * Triggers the mesh to begin fading in or out
  93334. * @param value if the object should fade in or out (true to fade in)
  93335. */
  93336. FadeInOutBehavior.prototype.fadeIn = function (value) {
  93337. this._hovered = value;
  93338. this._update();
  93339. };
  93340. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  93341. var _this = this;
  93342. mesh.visibility = value;
  93343. mesh.getChildMeshes().forEach(function (c) {
  93344. _this._setAllVisibility(c, value);
  93345. });
  93346. };
  93347. return FadeInOutBehavior;
  93348. }());
  93349. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  93350. })(BABYLON || (BABYLON = {}));
  93351. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  93352. var BABYLON;
  93353. (function (BABYLON) {
  93354. /**
  93355. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  93356. */
  93357. var Gizmo = /** @class */ (function () {
  93358. /**
  93359. * Creates a gizmo
  93360. * @param gizmoLayer The utility layer the gizmo will be added to
  93361. */
  93362. function Gizmo(
  93363. /** The utility layer the gizmo will be added to */
  93364. gizmoLayer) {
  93365. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93366. var _this = this;
  93367. this.gizmoLayer = gizmoLayer;
  93368. /**
  93369. * Ratio for the scale of the gizmo (Default: 1)
  93370. */
  93371. this.scaleRatio = 1;
  93372. this._tmpMatrix = new BABYLON.Matrix();
  93373. /**
  93374. * If a custom mesh has been set (Default: false)
  93375. */
  93376. this._customMeshSet = false;
  93377. /**
  93378. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  93379. */
  93380. this.updateGizmoRotationToMatchAttachedMesh = true;
  93381. /**
  93382. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  93383. */
  93384. this.updateGizmoPositionToMatchAttachedMesh = true;
  93385. /**
  93386. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  93387. */
  93388. this._updateScale = true;
  93389. this._interactionsEnabled = true;
  93390. this._tempVector = new BABYLON.Vector3();
  93391. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  93392. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  93393. _this._update();
  93394. });
  93395. this.attachedMesh = null;
  93396. }
  93397. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  93398. /**
  93399. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  93400. * * When set, interactions will be enabled
  93401. */
  93402. get: function () {
  93403. return this._attachedMesh;
  93404. },
  93405. set: function (value) {
  93406. this._attachedMesh = value;
  93407. this._rootMesh.setEnabled(value ? true : false);
  93408. this._attachedMeshChanged(value);
  93409. },
  93410. enumerable: true,
  93411. configurable: true
  93412. });
  93413. /**
  93414. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93415. * @param mesh The mesh to replace the default mesh of the gizmo
  93416. */
  93417. Gizmo.prototype.setCustomMesh = function (mesh) {
  93418. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  93419. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  93420. }
  93421. this._rootMesh.getChildMeshes().forEach(function (c) {
  93422. c.dispose();
  93423. });
  93424. mesh.parent = this._rootMesh;
  93425. this._customMeshSet = true;
  93426. };
  93427. Gizmo.prototype._attachedMeshChanged = function (value) {
  93428. };
  93429. /**
  93430. * @hidden
  93431. * Updates the gizmo to match the attached mesh's position/rotation
  93432. */
  93433. Gizmo.prototype._update = function () {
  93434. if (this.attachedMesh) {
  93435. if (this.updateGizmoRotationToMatchAttachedMesh) {
  93436. if (!this._rootMesh.rotationQuaternion) {
  93437. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  93438. }
  93439. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  93440. this._tempVector.copyFrom(this.attachedMesh.scaling);
  93441. if (this.attachedMesh.scaling.x < 0) {
  93442. this.attachedMesh.scaling.x *= -1;
  93443. }
  93444. if (this.attachedMesh.scaling.y < 0) {
  93445. this.attachedMesh.scaling.y *= -1;
  93446. }
  93447. if (this.attachedMesh.scaling.z < 0) {
  93448. this.attachedMesh.scaling.z *= -1;
  93449. }
  93450. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  93451. this.attachedMesh.scaling.copyFrom(this._tempVector);
  93452. this.attachedMesh.computeWorldMatrix();
  93453. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  93454. }
  93455. else if (this._rootMesh.rotationQuaternion) {
  93456. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  93457. }
  93458. if (this.updateGizmoPositionToMatchAttachedMesh) {
  93459. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  93460. }
  93461. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  93462. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  93463. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  93464. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  93465. }
  93466. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  93467. var dist = this._tempVector.length() * this.scaleRatio;
  93468. this._rootMesh.scaling.set(dist, dist, dist);
  93469. }
  93470. }
  93471. };
  93472. /**
  93473. * Disposes of the gizmo
  93474. */
  93475. Gizmo.prototype.dispose = function () {
  93476. this._rootMesh.dispose();
  93477. if (this._beforeRenderObserver) {
  93478. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  93479. }
  93480. };
  93481. return Gizmo;
  93482. }());
  93483. BABYLON.Gizmo = Gizmo;
  93484. })(BABYLON || (BABYLON = {}));
  93485. //# sourceMappingURL=babylon.gizmo.js.map
  93486. var BABYLON;
  93487. (function (BABYLON) {
  93488. /**
  93489. * Single axis drag gizmo
  93490. */
  93491. var AxisDragGizmo = /** @class */ (function (_super) {
  93492. __extends(AxisDragGizmo, _super);
  93493. /**
  93494. * Creates an AxisDragGizmo
  93495. * @param gizmoLayer The utility layer the gizmo will be added to
  93496. * @param dragAxis The axis which the gizmo will be able to drag on
  93497. * @param color The color of the gizmo
  93498. */
  93499. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  93500. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93501. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93502. var _this = _super.call(this, gizmoLayer) || this;
  93503. _this._pointerObserver = null;
  93504. /**
  93505. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93506. */
  93507. _this.snapDistance = 0;
  93508. /**
  93509. * Event that fires each time the gizmo snaps to a new location.
  93510. * * snapDistance is the the change in distance
  93511. */
  93512. _this.onSnapObservable = new BABYLON.Observable();
  93513. // Create Material
  93514. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93515. coloredMaterial.disableLighting = true;
  93516. coloredMaterial.emissiveColor = color;
  93517. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93518. hoverMaterial.disableLighting = true;
  93519. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93520. // Build mesh on root node
  93521. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93522. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  93523. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93524. arrowTail.color = coloredMaterial.emissiveColor;
  93525. arrow.addChild(arrowMesh);
  93526. arrow.addChild(arrowTail);
  93527. // Position arrow pointing in its drag axis
  93528. arrowMesh.scaling.scaleInPlace(0.05);
  93529. arrowMesh.material = coloredMaterial;
  93530. arrowMesh.rotation.x = Math.PI / 2;
  93531. arrowMesh.position.z += 0.3;
  93532. arrowTail.scaling.scaleInPlace(0.26);
  93533. arrowTail.rotation.x = Math.PI / 2;
  93534. arrowTail.material = coloredMaterial;
  93535. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93536. arrow.scaling.scaleInPlace(1 / 3);
  93537. _this._rootMesh.addChild(arrow);
  93538. var currentSnapDragDistance = 0;
  93539. var tmpVector = new BABYLON.Vector3();
  93540. var tmpSnapEvent = { snapDistance: 0 };
  93541. // Add drag behavior to handle events when the gizmo is dragged
  93542. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93543. _this.dragBehavior.moveAttached = false;
  93544. _this._rootMesh.addBehavior(_this.dragBehavior);
  93545. var localDelta = new BABYLON.Vector3();
  93546. var tmpMatrix = new BABYLON.Matrix();
  93547. _this.dragBehavior.onDragObservable.add(function (event) {
  93548. if (_this.attachedMesh) {
  93549. // Convert delta to local translation if it has a parent
  93550. if (_this.attachedMesh.parent) {
  93551. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93552. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  93553. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  93554. }
  93555. else {
  93556. localDelta.copyFrom(event.delta);
  93557. }
  93558. // Snapping logic
  93559. if (_this.snapDistance == 0) {
  93560. _this.attachedMesh.position.addInPlace(localDelta);
  93561. }
  93562. else {
  93563. currentSnapDragDistance += event.dragDistance;
  93564. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93565. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  93566. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93567. localDelta.normalizeToRef(tmpVector);
  93568. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  93569. _this.attachedMesh.position.addInPlace(tmpVector);
  93570. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93571. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93572. }
  93573. }
  93574. }
  93575. });
  93576. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93577. if (_this._customMeshSet) {
  93578. return;
  93579. }
  93580. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93581. var material = isHovered ? hoverMaterial : coloredMaterial;
  93582. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93583. m.material = material;
  93584. if (m.color) {
  93585. m.color = material.emissiveColor;
  93586. }
  93587. });
  93588. });
  93589. return _this;
  93590. }
  93591. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  93592. if (this.dragBehavior) {
  93593. this.dragBehavior.enabled = value ? true : false;
  93594. }
  93595. };
  93596. /**
  93597. * Disposes of the gizmo
  93598. */
  93599. AxisDragGizmo.prototype.dispose = function () {
  93600. this.onSnapObservable.clear();
  93601. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93602. this.dragBehavior.detach();
  93603. _super.prototype.dispose.call(this);
  93604. };
  93605. return AxisDragGizmo;
  93606. }(BABYLON.Gizmo));
  93607. BABYLON.AxisDragGizmo = AxisDragGizmo;
  93608. })(BABYLON || (BABYLON = {}));
  93609. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  93610. var BABYLON;
  93611. (function (BABYLON) {
  93612. /**
  93613. * Single axis scale gizmo
  93614. */
  93615. var AxisScaleGizmo = /** @class */ (function (_super) {
  93616. __extends(AxisScaleGizmo, _super);
  93617. /**
  93618. * Creates an AxisScaleGizmo
  93619. * @param gizmoLayer The utility layer the gizmo will be added to
  93620. * @param dragAxis The axis which the gizmo will be able to scale on
  93621. * @param color The color of the gizmo
  93622. */
  93623. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  93624. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93625. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93626. var _this = _super.call(this, gizmoLayer) || this;
  93627. _this._pointerObserver = null;
  93628. /**
  93629. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93630. */
  93631. _this.snapDistance = 0;
  93632. /**
  93633. * Event that fires each time the gizmo snaps to a new location.
  93634. * * snapDistance is the the change in distance
  93635. */
  93636. _this.onSnapObservable = new BABYLON.Observable();
  93637. /**
  93638. * If the scaling operation should be done on all axis (default: false)
  93639. */
  93640. _this.uniformScaling = false;
  93641. // Create Material
  93642. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93643. _this._coloredMaterial.disableLighting = true;
  93644. _this._coloredMaterial.emissiveColor = color;
  93645. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93646. hoverMaterial.disableLighting = true;
  93647. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93648. // Build mesh on root node
  93649. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93650. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  93651. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93652. arrowTail.color = _this._coloredMaterial.emissiveColor;
  93653. arrow.addChild(arrowMesh);
  93654. arrow.addChild(arrowTail);
  93655. // Position arrow pointing in its drag axis
  93656. arrowMesh.scaling.scaleInPlace(0.1);
  93657. arrowMesh.material = _this._coloredMaterial;
  93658. arrowMesh.rotation.x = Math.PI / 2;
  93659. arrowMesh.position.z += 0.3;
  93660. arrowTail.scaling.scaleInPlace(0.26);
  93661. arrowTail.rotation.x = Math.PI / 2;
  93662. arrowTail.material = _this._coloredMaterial;
  93663. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93664. _this._rootMesh.addChild(arrow);
  93665. arrow.scaling.scaleInPlace(1 / 3);
  93666. // Add drag behavior to handle events when the gizmo is dragged
  93667. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93668. _this.dragBehavior.moveAttached = false;
  93669. _this._rootMesh.addBehavior(_this.dragBehavior);
  93670. var currentSnapDragDistance = 0;
  93671. var tmpVector = new BABYLON.Vector3();
  93672. var tmpSnapEvent = { snapDistance: 0 };
  93673. _this.dragBehavior.onDragObservable.add(function (event) {
  93674. if (_this.attachedMesh) {
  93675. // Snapping logic
  93676. var snapped = false;
  93677. var dragSteps = 0;
  93678. if (_this.uniformScaling) {
  93679. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  93680. if (tmpVector.y < 0) {
  93681. tmpVector.scaleInPlace(-1);
  93682. }
  93683. }
  93684. else {
  93685. tmpVector.copyFrom(dragAxis);
  93686. }
  93687. if (_this.snapDistance == 0) {
  93688. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  93689. }
  93690. else {
  93691. currentSnapDragDistance += event.dragDistance;
  93692. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93693. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93694. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93695. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  93696. snapped = true;
  93697. }
  93698. else {
  93699. tmpVector.scaleInPlace(0);
  93700. }
  93701. }
  93702. _this.attachedMesh.scaling.addInPlace(tmpVector);
  93703. if (snapped) {
  93704. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93705. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93706. }
  93707. }
  93708. });
  93709. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93710. if (_this._customMeshSet) {
  93711. return;
  93712. }
  93713. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93714. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  93715. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93716. m.material = material;
  93717. if (m.color) {
  93718. m.color = material.emissiveColor;
  93719. }
  93720. });
  93721. });
  93722. return _this;
  93723. }
  93724. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  93725. if (this.dragBehavior) {
  93726. this.dragBehavior.enabled = value ? true : false;
  93727. }
  93728. };
  93729. /**
  93730. * Disposes of the gizmo
  93731. */
  93732. AxisScaleGizmo.prototype.dispose = function () {
  93733. this.onSnapObservable.clear();
  93734. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93735. this.dragBehavior.detach();
  93736. _super.prototype.dispose.call(this);
  93737. };
  93738. /**
  93739. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93740. * @param mesh The mesh to replace the default mesh of the gizmo
  93741. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  93742. */
  93743. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  93744. var _this = this;
  93745. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  93746. _super.prototype.setCustomMesh.call(this, mesh);
  93747. if (useGizmoMaterial) {
  93748. this._rootMesh.getChildMeshes().forEach(function (m) {
  93749. m.material = _this._coloredMaterial;
  93750. if (m.color) {
  93751. m.color = _this._coloredMaterial.emissiveColor;
  93752. }
  93753. });
  93754. this._customMeshSet = false;
  93755. }
  93756. };
  93757. return AxisScaleGizmo;
  93758. }(BABYLON.Gizmo));
  93759. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  93760. })(BABYLON || (BABYLON = {}));
  93761. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  93762. var BABYLON;
  93763. (function (BABYLON) {
  93764. /**
  93765. * Single plane rotation gizmo
  93766. */
  93767. var PlaneRotationGizmo = /** @class */ (function (_super) {
  93768. __extends(PlaneRotationGizmo, _super);
  93769. /**
  93770. * Creates a PlaneRotationGizmo
  93771. * @param gizmoLayer The utility layer the gizmo will be added to
  93772. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  93773. * @param color The color of the gizmo
  93774. */
  93775. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  93776. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93777. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93778. var _this = _super.call(this, gizmoLayer) || this;
  93779. _this._pointerObserver = null;
  93780. /**
  93781. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  93782. */
  93783. _this.snapDistance = 0;
  93784. /**
  93785. * Event that fires each time the gizmo snaps to a new location.
  93786. * * snapDistance is the the change in distance
  93787. */
  93788. _this.onSnapObservable = new BABYLON.Observable();
  93789. // Create Material
  93790. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93791. coloredMaterial.disableLighting = true;
  93792. coloredMaterial.emissiveColor = color;
  93793. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93794. hoverMaterial.disableLighting = true;
  93795. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93796. // Build mesh on root node
  93797. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93798. // Create circle out of lines
  93799. var tessellation = 20;
  93800. var radius = 0.8;
  93801. var points = new Array();
  93802. for (var i = 0; i < tessellation; i++) {
  93803. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  93804. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  93805. }
  93806. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  93807. rotationMesh.color = coloredMaterial.emissiveColor;
  93808. // Position arrow pointing in its drag axis
  93809. rotationMesh.scaling.scaleInPlace(0.26);
  93810. rotationMesh.material = coloredMaterial;
  93811. rotationMesh.rotation.x = Math.PI / 2;
  93812. parentMesh.addChild(rotationMesh);
  93813. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  93814. _this._rootMesh.addChild(parentMesh);
  93815. parentMesh.scaling.scaleInPlace(1 / 3);
  93816. // Add drag behavior to handle events when the gizmo is dragged
  93817. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  93818. _this.dragBehavior.moveAttached = false;
  93819. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  93820. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  93821. _this._rootMesh.addBehavior(_this.dragBehavior);
  93822. var lastDragPosition = new BABYLON.Vector3();
  93823. _this.dragBehavior.onDragStartObservable.add(function (e) {
  93824. if (_this.attachedMesh) {
  93825. lastDragPosition.copyFrom(e.dragPlanePoint);
  93826. }
  93827. });
  93828. var rotationMatrix = new BABYLON.Matrix();
  93829. var planeNormalTowardsCamera = new BABYLON.Vector3();
  93830. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  93831. var tmpSnapEvent = { snapDistance: 0 };
  93832. var currentSnapDragDistance = 0;
  93833. var tmpMatrix = new BABYLON.Matrix();
  93834. var tmpVector = new BABYLON.Vector3();
  93835. var amountToRotate = new BABYLON.Quaternion();
  93836. _this.dragBehavior.onDragObservable.add(function (event) {
  93837. if (_this.attachedMesh) {
  93838. if (!_this.attachedMesh.rotationQuaternion) {
  93839. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93840. }
  93841. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  93842. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  93843. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  93844. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  93845. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  93846. var angle = Math.atan2(cross.length(), dot);
  93847. planeNormalTowardsCamera.copyFrom(planeNormal);
  93848. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  93849. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93850. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  93851. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  93852. }
  93853. // Flip up vector depending on which side the camera is on
  93854. if (gizmoLayer.utilityLayerScene.activeCamera) {
  93855. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  93856. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  93857. planeNormalTowardsCamera.scaleInPlace(-1);
  93858. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  93859. }
  93860. }
  93861. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  93862. if (halfCircleSide)
  93863. angle = -angle;
  93864. // Snapping logic
  93865. var snapped = false;
  93866. if (_this.snapDistance != 0) {
  93867. currentSnapDragDistance += angle;
  93868. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93869. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93870. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93871. angle = _this.snapDistance * dragSteps;
  93872. snapped = true;
  93873. }
  93874. else {
  93875. angle = 0;
  93876. }
  93877. }
  93878. // If the mesh has a parent, convert needed world rotation to local rotation
  93879. tmpMatrix.reset();
  93880. if (_this.attachedMesh.parent) {
  93881. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93882. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  93883. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  93884. }
  93885. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  93886. var quaternionCoefficient = Math.sin(angle / 2);
  93887. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  93888. // 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
  93889. if (tmpMatrix.determinant() > 0) {
  93890. amountToRotate.toEulerAnglesToRef(tmpVector);
  93891. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  93892. }
  93893. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93894. // Rotate selected mesh quaternion over fixed axis
  93895. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  93896. }
  93897. else {
  93898. // Rotate selected mesh quaternion over rotated axis
  93899. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  93900. }
  93901. lastDragPosition.copyFrom(event.dragPlanePoint);
  93902. if (snapped) {
  93903. tmpSnapEvent.snapDistance = angle;
  93904. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93905. }
  93906. }
  93907. });
  93908. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93909. if (_this._customMeshSet) {
  93910. return;
  93911. }
  93912. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93913. var material = isHovered ? hoverMaterial : coloredMaterial;
  93914. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93915. m.material = material;
  93916. if (m.color) {
  93917. m.color = material.emissiveColor;
  93918. }
  93919. });
  93920. });
  93921. return _this;
  93922. }
  93923. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  93924. if (this.dragBehavior) {
  93925. this.dragBehavior.enabled = value ? true : false;
  93926. }
  93927. };
  93928. /**
  93929. * Disposes of the gizmo
  93930. */
  93931. PlaneRotationGizmo.prototype.dispose = function () {
  93932. this.onSnapObservable.clear();
  93933. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93934. this.dragBehavior.detach();
  93935. _super.prototype.dispose.call(this);
  93936. };
  93937. return PlaneRotationGizmo;
  93938. }(BABYLON.Gizmo));
  93939. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  93940. })(BABYLON || (BABYLON = {}));
  93941. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  93942. var BABYLON;
  93943. (function (BABYLON) {
  93944. /**
  93945. * Gizmo that enables dragging a mesh along 3 axis
  93946. */
  93947. var PositionGizmo = /** @class */ (function (_super) {
  93948. __extends(PositionGizmo, _super);
  93949. /**
  93950. * Creates a PositionGizmo
  93951. * @param gizmoLayer The utility layer the gizmo will be added to
  93952. */
  93953. function PositionGizmo(gizmoLayer) {
  93954. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93955. var _this = _super.call(this, gizmoLayer) || this;
  93956. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93957. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93958. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93959. _this.attachedMesh = null;
  93960. return _this;
  93961. }
  93962. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  93963. set: function (mesh) {
  93964. if (this.xGizmo) {
  93965. this.xGizmo.attachedMesh = mesh;
  93966. this.yGizmo.attachedMesh = mesh;
  93967. this.zGizmo.attachedMesh = mesh;
  93968. }
  93969. },
  93970. enumerable: true,
  93971. configurable: true
  93972. });
  93973. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  93974. get: function () {
  93975. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93976. },
  93977. set: function (value) {
  93978. if (this.xGizmo) {
  93979. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93980. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93981. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93982. }
  93983. },
  93984. enumerable: true,
  93985. configurable: true
  93986. });
  93987. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  93988. get: function () {
  93989. return this.xGizmo.snapDistance;
  93990. },
  93991. /**
  93992. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93993. */
  93994. set: function (value) {
  93995. if (this.xGizmo) {
  93996. this.xGizmo.snapDistance = value;
  93997. this.yGizmo.snapDistance = value;
  93998. this.zGizmo.snapDistance = value;
  93999. }
  94000. },
  94001. enumerable: true,
  94002. configurable: true
  94003. });
  94004. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  94005. get: function () {
  94006. return this.xGizmo.scaleRatio;
  94007. },
  94008. /**
  94009. * Ratio for the scale of the gizmo (Default: 1)
  94010. */
  94011. set: function (value) {
  94012. if (this.xGizmo) {
  94013. this.xGizmo.scaleRatio = value;
  94014. this.yGizmo.scaleRatio = value;
  94015. this.zGizmo.scaleRatio = value;
  94016. }
  94017. },
  94018. enumerable: true,
  94019. configurable: true
  94020. });
  94021. /**
  94022. * Disposes of the gizmo
  94023. */
  94024. PositionGizmo.prototype.dispose = function () {
  94025. this.xGizmo.dispose();
  94026. this.yGizmo.dispose();
  94027. this.zGizmo.dispose();
  94028. };
  94029. /**
  94030. * CustomMeshes are not supported by this gizmo
  94031. * @param mesh The mesh to replace the default mesh of the gizmo
  94032. */
  94033. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  94034. 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)");
  94035. };
  94036. return PositionGizmo;
  94037. }(BABYLON.Gizmo));
  94038. BABYLON.PositionGizmo = PositionGizmo;
  94039. })(BABYLON || (BABYLON = {}));
  94040. //# sourceMappingURL=babylon.positionGizmo.js.map
  94041. var BABYLON;
  94042. (function (BABYLON) {
  94043. /**
  94044. * Gizmo that enables rotating a mesh along 3 axis
  94045. */
  94046. var RotationGizmo = /** @class */ (function (_super) {
  94047. __extends(RotationGizmo, _super);
  94048. /**
  94049. * Creates a RotationGizmo
  94050. * @param gizmoLayer The utility layer the gizmo will be added to
  94051. */
  94052. function RotationGizmo(gizmoLayer) {
  94053. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94054. var _this = _super.call(this, gizmoLayer) || this;
  94055. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94056. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94057. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94058. _this.attachedMesh = null;
  94059. return _this;
  94060. }
  94061. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  94062. set: function (mesh) {
  94063. if (this.xGizmo) {
  94064. this.xGizmo.attachedMesh = mesh;
  94065. this.yGizmo.attachedMesh = mesh;
  94066. this.zGizmo.attachedMesh = mesh;
  94067. }
  94068. },
  94069. enumerable: true,
  94070. configurable: true
  94071. });
  94072. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94073. get: function () {
  94074. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94075. },
  94076. set: function (value) {
  94077. if (this.xGizmo) {
  94078. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94079. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94080. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94081. }
  94082. },
  94083. enumerable: true,
  94084. configurable: true
  94085. });
  94086. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  94087. get: function () {
  94088. return this.xGizmo.snapDistance;
  94089. },
  94090. /**
  94091. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94092. */
  94093. set: function (value) {
  94094. if (this.xGizmo) {
  94095. this.xGizmo.snapDistance = value;
  94096. this.yGizmo.snapDistance = value;
  94097. this.zGizmo.snapDistance = value;
  94098. }
  94099. },
  94100. enumerable: true,
  94101. configurable: true
  94102. });
  94103. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  94104. get: function () {
  94105. return this.xGizmo.scaleRatio;
  94106. },
  94107. /**
  94108. * Ratio for the scale of the gizmo (Default: 1)
  94109. */
  94110. set: function (value) {
  94111. if (this.xGizmo) {
  94112. this.xGizmo.scaleRatio = value;
  94113. this.yGizmo.scaleRatio = value;
  94114. this.zGizmo.scaleRatio = value;
  94115. }
  94116. },
  94117. enumerable: true,
  94118. configurable: true
  94119. });
  94120. /**
  94121. * Disposes of the gizmo
  94122. */
  94123. RotationGizmo.prototype.dispose = function () {
  94124. this.xGizmo.dispose();
  94125. this.yGizmo.dispose();
  94126. this.zGizmo.dispose();
  94127. };
  94128. /**
  94129. * CustomMeshes are not supported by this gizmo
  94130. * @param mesh The mesh to replace the default mesh of the gizmo
  94131. */
  94132. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  94133. 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)");
  94134. };
  94135. return RotationGizmo;
  94136. }(BABYLON.Gizmo));
  94137. BABYLON.RotationGizmo = RotationGizmo;
  94138. })(BABYLON || (BABYLON = {}));
  94139. //# sourceMappingURL=babylon.rotationGizmo.js.map
  94140. var BABYLON;
  94141. (function (BABYLON) {
  94142. /**
  94143. * Gizmo that enables scaling a mesh along 3 axis
  94144. */
  94145. var ScaleGizmo = /** @class */ (function (_super) {
  94146. __extends(ScaleGizmo, _super);
  94147. /**
  94148. * Creates a ScaleGizmo
  94149. * @param gizmoLayer The utility layer the gizmo will be added to
  94150. */
  94151. function ScaleGizmo(gizmoLayer) {
  94152. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94153. var _this = _super.call(this, gizmoLayer) || this;
  94154. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94155. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94156. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94157. // Create uniform scale gizmo
  94158. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  94159. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94160. _this._uniformGizmo.uniformScaling = true;
  94161. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  94162. octahedron.scaling.scaleInPlace(0.007);
  94163. _this._uniformGizmo.setCustomMesh(octahedron, true);
  94164. _this.attachedMesh = null;
  94165. return _this;
  94166. }
  94167. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  94168. set: function (mesh) {
  94169. if (this.xGizmo) {
  94170. this.xGizmo.attachedMesh = mesh;
  94171. this.yGizmo.attachedMesh = mesh;
  94172. this.zGizmo.attachedMesh = mesh;
  94173. this._uniformGizmo.attachedMesh = mesh;
  94174. }
  94175. },
  94176. enumerable: true,
  94177. configurable: true
  94178. });
  94179. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94180. get: function () {
  94181. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94182. },
  94183. set: function (value) {
  94184. if (this.xGizmo) {
  94185. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94186. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94187. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94188. }
  94189. },
  94190. enumerable: true,
  94191. configurable: true
  94192. });
  94193. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  94194. get: function () {
  94195. return this.xGizmo.snapDistance;
  94196. },
  94197. /**
  94198. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94199. */
  94200. set: function (value) {
  94201. if (this.xGizmo) {
  94202. this.xGizmo.snapDistance = value;
  94203. this.yGizmo.snapDistance = value;
  94204. this.zGizmo.snapDistance = value;
  94205. this._uniformGizmo.snapDistance = value;
  94206. }
  94207. },
  94208. enumerable: true,
  94209. configurable: true
  94210. });
  94211. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  94212. get: function () {
  94213. return this.xGizmo.scaleRatio;
  94214. },
  94215. /**
  94216. * Ratio for the scale of the gizmo (Default: 1)
  94217. */
  94218. set: function (value) {
  94219. if (this.xGizmo) {
  94220. this.xGizmo.scaleRatio = value;
  94221. this.yGizmo.scaleRatio = value;
  94222. this.zGizmo.scaleRatio = value;
  94223. this._uniformGizmo.scaleRatio = value;
  94224. }
  94225. },
  94226. enumerable: true,
  94227. configurable: true
  94228. });
  94229. /**
  94230. * Disposes of the gizmo
  94231. */
  94232. ScaleGizmo.prototype.dispose = function () {
  94233. this.xGizmo.dispose();
  94234. this.yGizmo.dispose();
  94235. this.zGizmo.dispose();
  94236. this._uniformGizmo.dispose();
  94237. };
  94238. return ScaleGizmo;
  94239. }(BABYLON.Gizmo));
  94240. BABYLON.ScaleGizmo = ScaleGizmo;
  94241. })(BABYLON || (BABYLON = {}));
  94242. //# sourceMappingURL=babylon.scaleGizmo.js.map
  94243. var BABYLON;
  94244. (function (BABYLON) {
  94245. /**
  94246. * Bounding box gizmo
  94247. */
  94248. var BoundingBoxGizmo = /** @class */ (function (_super) {
  94249. __extends(BoundingBoxGizmo, _super);
  94250. /**
  94251. * Creates an BoundingBoxGizmo
  94252. * @param gizmoLayer The utility layer the gizmo will be added to
  94253. * @param color The color of the gizmo
  94254. */
  94255. function BoundingBoxGizmo(color, gizmoLayer) {
  94256. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94257. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  94258. var _this = _super.call(this, gizmoLayer) || this;
  94259. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  94260. _this._renderObserver = null;
  94261. _this._pointerObserver = null;
  94262. _this._scaleDragSpeed = 0.2;
  94263. _this._tmpQuaternion = new BABYLON.Quaternion();
  94264. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94265. _this._tmpRotationMatrix = new BABYLON.Matrix();
  94266. /**
  94267. * 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)
  94268. */
  94269. _this.ignoreChildren = false;
  94270. /**
  94271. * 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)
  94272. */
  94273. _this.includeChildPredicate = null;
  94274. /**
  94275. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  94276. */
  94277. _this.rotationSphereSize = 0.1;
  94278. /**
  94279. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  94280. */
  94281. _this.scaleBoxSize = 0.1;
  94282. /**
  94283. * 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)
  94284. */
  94285. _this.fixedDragMeshScreenSize = false;
  94286. /**
  94287. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  94288. */
  94289. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  94290. /**
  94291. * Fired when a rotation sphere or scale box is dragged
  94292. */
  94293. _this.onDragStartObservable = new BABYLON.Observable();
  94294. /**
  94295. * Fired when a scale box is dragged
  94296. */
  94297. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  94298. /**
  94299. * Fired when a scale box drag is ended
  94300. */
  94301. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  94302. /**
  94303. * Fired when a rotation sphere is dragged
  94304. */
  94305. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  94306. /**
  94307. * Fired when a rotation sphere drag is ended
  94308. */
  94309. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  94310. /**
  94311. * 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)
  94312. */
  94313. _this.scalePivot = null;
  94314. _this._existingMeshScale = new BABYLON.Vector3();
  94315. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  94316. _this._updateScale = false;
  94317. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  94318. // Create Materials
  94319. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94320. coloredMaterial.disableLighting = true;
  94321. coloredMaterial.emissiveColor = color;
  94322. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94323. hoverColoredMaterial.disableLighting = true;
  94324. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94325. // Build bounding box out of lines
  94326. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94327. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  94328. var lines = [];
  94329. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  94330. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94331. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94332. 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));
  94333. 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));
  94334. 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));
  94335. 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));
  94336. 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));
  94337. 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));
  94338. 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));
  94339. 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));
  94340. 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));
  94341. lines.forEach(function (l) {
  94342. l.color = color;
  94343. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  94344. l.isPickable = false;
  94345. _this._lineBoundingBox.addChild(l);
  94346. });
  94347. _this._rootMesh.addChild(_this._lineBoundingBox);
  94348. // Create rotation spheres
  94349. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94350. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  94351. var _loop_1 = function (i_1) {
  94352. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  94353. sphere.rotationQuaternion = new BABYLON.Quaternion();
  94354. sphere.material = coloredMaterial;
  94355. // Drag behavior
  94356. _dragBehavior = new BABYLON.PointerDragBehavior({});
  94357. _dragBehavior.moveAttached = false;
  94358. _dragBehavior.updateDragPlane = false;
  94359. sphere.addBehavior(_dragBehavior);
  94360. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  94361. var totalTurnAmountOfDrag = 0;
  94362. _dragBehavior.onDragStartObservable.add(function (event) {
  94363. startingTurnDirection.copyFrom(sphere.forward);
  94364. totalTurnAmountOfDrag = 0;
  94365. });
  94366. _dragBehavior.onDragObservable.add(function (event) {
  94367. _this.onRotationSphereDragObservable.notifyObservers({});
  94368. if (_this.attachedMesh) {
  94369. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94370. var worldDragDirection = startingTurnDirection;
  94371. // Project the world right on to the drag plane
  94372. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  94373. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  94374. // project drag delta on to the resulting drag axis and rotate based on that
  94375. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  94376. // Make rotation relative to size of mesh.
  94377. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94378. // Rotate based on axis
  94379. if (!_this.attachedMesh.rotationQuaternion) {
  94380. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94381. }
  94382. if (!_this._anchorMesh.rotationQuaternion) {
  94383. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  94384. }
  94385. // Do not allow the object to turn more than a full circle
  94386. totalTurnAmountOfDrag += projectDist;
  94387. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  94388. if (i_1 >= 8) {
  94389. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  94390. }
  94391. else if (i_1 >= 4) {
  94392. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  94393. }
  94394. else {
  94395. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  94396. }
  94397. // Rotate around center of bounding box
  94398. _this._anchorMesh.addChild(_this.attachedMesh);
  94399. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  94400. _this._anchorMesh.removeChild(_this.attachedMesh);
  94401. }
  94402. _this.updateBoundingBox();
  94403. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94404. }
  94405. });
  94406. // Selection/deselection
  94407. _dragBehavior.onDragStartObservable.add(function () {
  94408. _this.onDragStartObservable.notifyObservers({});
  94409. _this._selectNode(sphere);
  94410. });
  94411. _dragBehavior.onDragEndObservable.add(function () {
  94412. _this.onRotationSphereDragEndObservable.notifyObservers({});
  94413. _this._selectNode(null);
  94414. });
  94415. this_1._rotateSpheresParent.addChild(sphere);
  94416. };
  94417. var this_1 = this, _dragBehavior;
  94418. for (var i_1 = 0; i_1 < 12; i_1++) {
  94419. _loop_1(i_1);
  94420. }
  94421. _this._rootMesh.addChild(_this._rotateSpheresParent);
  94422. // Create scale cubes
  94423. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94424. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  94425. for (var i = 0; i < 2; i++) {
  94426. for (var j = 0; j < 2; j++) {
  94427. var _loop_2 = function () {
  94428. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  94429. box.material = coloredMaterial;
  94430. // Dragging logic
  94431. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  94432. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94433. _dragBehavior.moveAttached = false;
  94434. box.addBehavior(_dragBehavior);
  94435. _dragBehavior.onDragObservable.add(function (event) {
  94436. _this.onScaleBoxDragObservable.notifyObservers({});
  94437. if (_this.attachedMesh) {
  94438. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94439. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94440. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  94441. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  94442. _this.updateBoundingBox();
  94443. if (_this.scalePivot) {
  94444. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  94445. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  94446. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  94447. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  94448. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  94449. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  94450. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  94451. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  94452. }
  94453. else {
  94454. // Scale from the position of the opposite corner
  94455. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  94456. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  94457. }
  94458. _this._anchorMesh.addChild(_this.attachedMesh);
  94459. _this._anchorMesh.scaling.addInPlace(deltaScale);
  94460. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  94461. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  94462. }
  94463. _this._anchorMesh.removeChild(_this.attachedMesh);
  94464. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94465. }
  94466. });
  94467. // Selection/deselection
  94468. _dragBehavior.onDragStartObservable.add(function () {
  94469. _this.onDragStartObservable.notifyObservers({});
  94470. _this._selectNode(box);
  94471. });
  94472. _dragBehavior.onDragEndObservable.add(function () {
  94473. _this.onScaleBoxDragEndObservable.notifyObservers({});
  94474. _this._selectNode(null);
  94475. });
  94476. this_2._scaleBoxesParent.addChild(box);
  94477. };
  94478. var this_2 = this, _dragBehavior;
  94479. for (var k = 0; k < 2; k++) {
  94480. _loop_2();
  94481. }
  94482. }
  94483. }
  94484. _this._rootMesh.addChild(_this._scaleBoxesParent);
  94485. // Hover color change
  94486. var pointerIds = new Array();
  94487. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94488. if (!pointerIds[pointerInfo.event.pointerId]) {
  94489. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  94490. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  94491. pointerIds[pointerInfo.event.pointerId] = mesh;
  94492. mesh.material = hoverColoredMaterial;
  94493. }
  94494. });
  94495. }
  94496. else {
  94497. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  94498. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  94499. delete pointerIds[pointerInfo.event.pointerId];
  94500. }
  94501. }
  94502. });
  94503. // Update bounding box positions
  94504. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  94505. // Only update the bouding box if scaling has changed
  94506. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  94507. _this.updateBoundingBox();
  94508. }
  94509. });
  94510. _this.updateBoundingBox();
  94511. return _this;
  94512. }
  94513. /** @hidden */
  94514. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  94515. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  94516. // Save old pivot and set pivot to 0,0,0
  94517. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  94518. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  94519. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  94520. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  94521. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94522. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94523. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94524. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  94525. }
  94526. }
  94527. BoundingBoxGizmo._PivotCached++;
  94528. };
  94529. /** @hidden */
  94530. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  94531. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  94532. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  94533. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94534. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94535. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94536. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  94537. }
  94538. this._PivotCached--;
  94539. };
  94540. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  94541. if (value) {
  94542. // Reset anchor mesh to match attached mesh's scale
  94543. // This is needed to avoid invalid box/sphere position on first drag
  94544. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  94545. this._anchorMesh.addChild(value);
  94546. this._anchorMesh.removeChild(value);
  94547. BoundingBoxGizmo._RestorePivotPoint(value);
  94548. this.updateBoundingBox();
  94549. }
  94550. };
  94551. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  94552. this._rotateSpheresParent.getChildMeshes()
  94553. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  94554. m.isVisible = (!selectedMesh || m == selectedMesh);
  94555. });
  94556. };
  94557. /**
  94558. * Updates the bounding box information for the Gizmo
  94559. */
  94560. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  94561. if (this.attachedMesh) {
  94562. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  94563. this._update();
  94564. // Rotate based on axis
  94565. if (!this.attachedMesh.rotationQuaternion) {
  94566. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  94567. }
  94568. if (!this._anchorMesh.rotationQuaternion) {
  94569. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  94570. }
  94571. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94572. // Store original position and reset mesh to origin before computing the bounding box
  94573. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94574. this._tmpVector.copyFrom(this.attachedMesh.position);
  94575. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  94576. this.attachedMesh.position.set(0, 0, 0);
  94577. // Update bounding dimensions/positions
  94578. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  94579. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  94580. // Update gizmo to match bounding box scaling and rotation
  94581. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  94582. 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);
  94583. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  94584. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  94585. this._lineBoundingBox.computeWorldMatrix();
  94586. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  94587. // restore position/rotation values
  94588. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  94589. this.attachedMesh.position.copyFrom(this._tmpVector);
  94590. }
  94591. // Update rotation sphere locations
  94592. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  94593. for (var i = 0; i < 3; i++) {
  94594. for (var j = 0; j < 2; j++) {
  94595. for (var k = 0; k < 2; k++) {
  94596. var index = ((i * 4) + (j * 2)) + k;
  94597. if (i == 0) {
  94598. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94599. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94600. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94601. }
  94602. if (i == 1) {
  94603. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  94604. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94605. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94606. }
  94607. if (i == 2) {
  94608. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  94609. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94610. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94611. }
  94612. if (this.fixedDragMeshScreenSize) {
  94613. this._rootMesh.computeWorldMatrix();
  94614. this._rotateSpheresParent.computeWorldMatrix();
  94615. rotateSpheres[index].computeWorldMatrix();
  94616. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94617. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94618. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94619. }
  94620. else {
  94621. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  94622. }
  94623. }
  94624. }
  94625. }
  94626. // Update scale box locations
  94627. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  94628. for (var i = 0; i < 2; i++) {
  94629. for (var j = 0; j < 2; j++) {
  94630. for (var k = 0; k < 2; k++) {
  94631. var index = ((i * 4) + (j * 2)) + k;
  94632. if (scaleBoxes[index]) {
  94633. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94634. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94635. if (this.fixedDragMeshScreenSize) {
  94636. this._rootMesh.computeWorldMatrix();
  94637. this._scaleBoxesParent.computeWorldMatrix();
  94638. scaleBoxes[index].computeWorldMatrix();
  94639. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94640. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94641. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94642. }
  94643. else {
  94644. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  94645. }
  94646. }
  94647. }
  94648. }
  94649. }
  94650. if (this.attachedMesh) {
  94651. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  94652. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  94653. }
  94654. };
  94655. /**
  94656. * Enables rotation on the specified axis and disables rotation on the others
  94657. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  94658. */
  94659. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  94660. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  94661. if (i < 4) {
  94662. m.setEnabled(axis.indexOf("x") != -1);
  94663. }
  94664. else if (i < 8) {
  94665. m.setEnabled(axis.indexOf("y") != -1);
  94666. }
  94667. else {
  94668. m.setEnabled(axis.indexOf("z") != -1);
  94669. }
  94670. });
  94671. };
  94672. /**
  94673. * Disposes of the gizmo
  94674. */
  94675. BoundingBoxGizmo.prototype.dispose = function () {
  94676. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94677. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  94678. this._lineBoundingBox.dispose();
  94679. this._rotateSpheresParent.dispose();
  94680. this._scaleBoxesParent.dispose();
  94681. _super.prototype.dispose.call(this);
  94682. };
  94683. /**
  94684. * 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)
  94685. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  94686. * @returns the bounding box mesh with the passed in mesh as a child
  94687. */
  94688. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  94689. var makeNotPickable = function (root) {
  94690. root.isPickable = false;
  94691. root.getChildMeshes().forEach(function (c) {
  94692. makeNotPickable(c);
  94693. });
  94694. };
  94695. makeNotPickable(mesh);
  94696. // Reset position to get boudning box from origin with no rotation
  94697. if (!mesh.rotationQuaternion) {
  94698. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  94699. }
  94700. var oldPos = mesh.position.clone();
  94701. var oldRot = mesh.rotationQuaternion.clone();
  94702. mesh.rotationQuaternion.set(0, 0, 0, 1);
  94703. mesh.position.set(0, 0, 0);
  94704. // Update bounding dimensions/positions
  94705. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  94706. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  94707. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  94708. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  94709. // Restore original positions
  94710. mesh.addChild(box);
  94711. mesh.rotationQuaternion.copyFrom(oldRot);
  94712. mesh.position.copyFrom(oldPos);
  94713. // Reverse parenting
  94714. mesh.removeChild(box);
  94715. box.addChild(mesh);
  94716. box.visibility = 0;
  94717. return box;
  94718. };
  94719. /**
  94720. * CustomMeshes are not supported by this gizmo
  94721. * @param mesh The mesh to replace the default mesh of the gizmo
  94722. */
  94723. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  94724. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  94725. };
  94726. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  94727. // store/remove pivot point should only be applied during their outermost calls
  94728. BoundingBoxGizmo._PivotCached = 0;
  94729. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  94730. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  94731. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  94732. return BoundingBoxGizmo;
  94733. }(BABYLON.Gizmo));
  94734. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  94735. })(BABYLON || (BABYLON = {}));
  94736. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  94737. var BABYLON;
  94738. (function (BABYLON) {
  94739. /**
  94740. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  94741. */
  94742. var GizmoManager = /** @class */ (function () {
  94743. /**
  94744. * Instatiates a gizmo manager
  94745. * @param scene the scene to overlay the gizmos on top of
  94746. */
  94747. function GizmoManager(scene) {
  94748. var _this = this;
  94749. this.scene = scene;
  94750. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  94751. this._pointerObserver = null;
  94752. this._attachedMesh = null;
  94753. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  94754. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  94755. /**
  94756. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  94757. */
  94758. this.attachableMeshes = null;
  94759. /**
  94760. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  94761. */
  94762. this.usePointerToAttachGizmos = true;
  94763. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  94764. // Instatiate/dispose gizmos based on pointer actions
  94765. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  94766. if (!_this.usePointerToAttachGizmos) {
  94767. return;
  94768. }
  94769. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  94770. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  94771. var node = pointerInfo.pickInfo.pickedMesh;
  94772. if (_this.attachableMeshes == null) {
  94773. // Attach to the most parent node
  94774. while (node && node.parent != null) {
  94775. node = node.parent;
  94776. }
  94777. }
  94778. else {
  94779. // Attach to the parent node that is an attachableMesh
  94780. var found = false;
  94781. _this.attachableMeshes.forEach(function (mesh) {
  94782. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  94783. node = mesh;
  94784. found = true;
  94785. }
  94786. });
  94787. if (!found) {
  94788. node = null;
  94789. }
  94790. }
  94791. if (node instanceof BABYLON.AbstractMesh) {
  94792. _this.attachToMesh(node);
  94793. }
  94794. else {
  94795. _this.attachToMesh(null);
  94796. }
  94797. }
  94798. else {
  94799. _this.attachToMesh(null);
  94800. }
  94801. }
  94802. });
  94803. }
  94804. /**
  94805. * Attaches a set of gizmos to the specified mesh
  94806. * @param mesh The mesh the gizmo's should be attached to
  94807. */
  94808. GizmoManager.prototype.attachToMesh = function (mesh) {
  94809. if (this._attachedMesh) {
  94810. this._attachedMesh.removeBehavior(this._dragBehavior);
  94811. }
  94812. this._attachedMesh = mesh;
  94813. for (var key in this.gizmos) {
  94814. var gizmo = (this.gizmos[key]);
  94815. if (gizmo && this._gizmosEnabled[key]) {
  94816. gizmo.attachedMesh = mesh;
  94817. }
  94818. }
  94819. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  94820. this._attachedMesh.addBehavior(this._dragBehavior);
  94821. }
  94822. };
  94823. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  94824. get: function () {
  94825. return this._gizmosEnabled.positionGizmo;
  94826. },
  94827. /**
  94828. * If the position gizmo is enabled
  94829. */
  94830. set: function (value) {
  94831. if (value) {
  94832. if (!this.gizmos.positionGizmo) {
  94833. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  94834. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94835. }
  94836. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  94837. }
  94838. else if (this.gizmos.positionGizmo) {
  94839. this.gizmos.positionGizmo.attachedMesh = null;
  94840. }
  94841. this._gizmosEnabled.positionGizmo = value;
  94842. },
  94843. enumerable: true,
  94844. configurable: true
  94845. });
  94846. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  94847. get: function () {
  94848. return this._gizmosEnabled.rotationGizmo;
  94849. },
  94850. /**
  94851. * If the rotation gizmo is enabled
  94852. */
  94853. set: function (value) {
  94854. if (value) {
  94855. if (!this.gizmos.rotationGizmo) {
  94856. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  94857. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94858. }
  94859. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  94860. }
  94861. else if (this.gizmos.rotationGizmo) {
  94862. this.gizmos.rotationGizmo.attachedMesh = null;
  94863. }
  94864. this._gizmosEnabled.rotationGizmo = value;
  94865. },
  94866. enumerable: true,
  94867. configurable: true
  94868. });
  94869. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  94870. get: function () {
  94871. return this._gizmosEnabled.scaleGizmo;
  94872. },
  94873. /**
  94874. * If the scale gizmo is enabled
  94875. */
  94876. set: function (value) {
  94877. if (value) {
  94878. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  94879. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  94880. }
  94881. else if (this.gizmos.scaleGizmo) {
  94882. this.gizmos.scaleGizmo.attachedMesh = null;
  94883. }
  94884. this._gizmosEnabled.scaleGizmo = value;
  94885. },
  94886. enumerable: true,
  94887. configurable: true
  94888. });
  94889. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  94890. get: function () {
  94891. return this._gizmosEnabled.boundingBoxGizmo;
  94892. },
  94893. /**
  94894. * If the boundingBox gizmo is enabled
  94895. */
  94896. set: function (value) {
  94897. if (value) {
  94898. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  94899. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  94900. if (this._attachedMesh) {
  94901. this._attachedMesh.removeBehavior(this._dragBehavior);
  94902. this._attachedMesh.addBehavior(this._dragBehavior);
  94903. }
  94904. }
  94905. else if (this.gizmos.boundingBoxGizmo) {
  94906. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  94907. }
  94908. this._gizmosEnabled.boundingBoxGizmo = value;
  94909. },
  94910. enumerable: true,
  94911. configurable: true
  94912. });
  94913. /**
  94914. * Disposes of the gizmo manager
  94915. */
  94916. GizmoManager.prototype.dispose = function () {
  94917. this.scene.onPointerObservable.remove(this._pointerObserver);
  94918. for (var key in this.gizmos) {
  94919. var gizmo = (this.gizmos[key]);
  94920. if (gizmo) {
  94921. gizmo.dispose();
  94922. }
  94923. }
  94924. this._dragBehavior.detach();
  94925. };
  94926. return GizmoManager;
  94927. }());
  94928. BABYLON.GizmoManager = GizmoManager;
  94929. })(BABYLON || (BABYLON = {}));
  94930. //# sourceMappingURL=babylon.gizmoManager.js.map
  94931. var BABYLON;
  94932. (function (BABYLON) {
  94933. /**
  94934. * Defines a target to use with MorphTargetManager
  94935. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  94936. */
  94937. var MorphTarget = /** @class */ (function () {
  94938. /**
  94939. * Creates a new MorphTarget
  94940. * @param name defines the name of the target
  94941. * @param influence defines the influence to use
  94942. */
  94943. function MorphTarget(
  94944. /** defines the name of the target */
  94945. name, influence, scene) {
  94946. if (influence === void 0) { influence = 0; }
  94947. if (scene === void 0) { scene = null; }
  94948. this.name = name;
  94949. /**
  94950. * Gets or sets the list of animations
  94951. */
  94952. this.animations = new Array();
  94953. this._positions = null;
  94954. this._normals = null;
  94955. this._tangents = null;
  94956. /**
  94957. * Observable raised when the influence changes
  94958. */
  94959. this.onInfluenceChanged = new BABYLON.Observable();
  94960. this._animationPropertiesOverride = null;
  94961. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94962. this.influence = influence;
  94963. }
  94964. Object.defineProperty(MorphTarget.prototype, "influence", {
  94965. /**
  94966. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  94967. */
  94968. get: function () {
  94969. return this._influence;
  94970. },
  94971. set: function (influence) {
  94972. if (this._influence === influence) {
  94973. return;
  94974. }
  94975. var previous = this._influence;
  94976. this._influence = influence;
  94977. if (this.onInfluenceChanged.hasObservers) {
  94978. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  94979. }
  94980. },
  94981. enumerable: true,
  94982. configurable: true
  94983. });
  94984. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  94985. /**
  94986. * Gets or sets the animation properties override
  94987. */
  94988. get: function () {
  94989. if (!this._animationPropertiesOverride && this._scene) {
  94990. return this._scene.animationPropertiesOverride;
  94991. }
  94992. return this._animationPropertiesOverride;
  94993. },
  94994. set: function (value) {
  94995. this._animationPropertiesOverride = value;
  94996. },
  94997. enumerable: true,
  94998. configurable: true
  94999. });
  95000. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  95001. /**
  95002. * Gets a boolean defining if the target contains position data
  95003. */
  95004. get: function () {
  95005. return !!this._positions;
  95006. },
  95007. enumerable: true,
  95008. configurable: true
  95009. });
  95010. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  95011. /**
  95012. * Gets a boolean defining if the target contains normal data
  95013. */
  95014. get: function () {
  95015. return !!this._normals;
  95016. },
  95017. enumerable: true,
  95018. configurable: true
  95019. });
  95020. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  95021. /**
  95022. * Gets a boolean defining if the target contains tangent data
  95023. */
  95024. get: function () {
  95025. return !!this._tangents;
  95026. },
  95027. enumerable: true,
  95028. configurable: true
  95029. });
  95030. /**
  95031. * Affects position data to this target
  95032. * @param data defines the position data to use
  95033. */
  95034. MorphTarget.prototype.setPositions = function (data) {
  95035. this._positions = data;
  95036. };
  95037. /**
  95038. * Gets the position data stored in this target
  95039. * @returns a FloatArray containing the position data (or null if not present)
  95040. */
  95041. MorphTarget.prototype.getPositions = function () {
  95042. return this._positions;
  95043. };
  95044. /**
  95045. * Affects normal data to this target
  95046. * @param data defines the normal data to use
  95047. */
  95048. MorphTarget.prototype.setNormals = function (data) {
  95049. this._normals = data;
  95050. };
  95051. /**
  95052. * Gets the normal data stored in this target
  95053. * @returns a FloatArray containing the normal data (or null if not present)
  95054. */
  95055. MorphTarget.prototype.getNormals = function () {
  95056. return this._normals;
  95057. };
  95058. /**
  95059. * Affects tangent data to this target
  95060. * @param data defines the tangent data to use
  95061. */
  95062. MorphTarget.prototype.setTangents = function (data) {
  95063. this._tangents = data;
  95064. };
  95065. /**
  95066. * Gets the tangent data stored in this target
  95067. * @returns a FloatArray containing the tangent data (or null if not present)
  95068. */
  95069. MorphTarget.prototype.getTangents = function () {
  95070. return this._tangents;
  95071. };
  95072. /**
  95073. * Serializes the current target into a Serialization object
  95074. * @returns the serialized object
  95075. */
  95076. MorphTarget.prototype.serialize = function () {
  95077. var serializationObject = {};
  95078. serializationObject.name = this.name;
  95079. serializationObject.influence = this.influence;
  95080. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  95081. if (this.hasNormals) {
  95082. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  95083. }
  95084. if (this.hasTangents) {
  95085. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  95086. }
  95087. // Animations
  95088. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  95089. return serializationObject;
  95090. };
  95091. // Statics
  95092. /**
  95093. * Creates a new target from serialized data
  95094. * @param serializationObject defines the serialized data to use
  95095. * @returns a new MorphTarget
  95096. */
  95097. MorphTarget.Parse = function (serializationObject) {
  95098. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  95099. result.setPositions(serializationObject.positions);
  95100. if (serializationObject.normals) {
  95101. result.setNormals(serializationObject.normals);
  95102. }
  95103. if (serializationObject.tangents) {
  95104. result.setTangents(serializationObject.tangents);
  95105. }
  95106. // Animations
  95107. if (serializationObject.animations) {
  95108. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  95109. var parsedAnimation = serializationObject.animations[animationIndex];
  95110. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  95111. }
  95112. }
  95113. return result;
  95114. };
  95115. /**
  95116. * Creates a MorphTarget from mesh data
  95117. * @param mesh defines the source mesh
  95118. * @param name defines the name to use for the new target
  95119. * @param influence defines the influence to attach to the target
  95120. * @returns a new MorphTarget
  95121. */
  95122. MorphTarget.FromMesh = function (mesh, name, influence) {
  95123. if (!name) {
  95124. name = mesh.name;
  95125. }
  95126. var result = new MorphTarget(name, influence, mesh.getScene());
  95127. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  95128. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95129. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  95130. }
  95131. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  95132. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  95133. }
  95134. return result;
  95135. };
  95136. return MorphTarget;
  95137. }());
  95138. BABYLON.MorphTarget = MorphTarget;
  95139. })(BABYLON || (BABYLON = {}));
  95140. //# sourceMappingURL=babylon.morphTarget.js.map
  95141. var BABYLON;
  95142. (function (BABYLON) {
  95143. /**
  95144. * This class is used to deform meshes using morphing between different targets
  95145. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95146. */
  95147. var MorphTargetManager = /** @class */ (function () {
  95148. /**
  95149. * Creates a new MorphTargetManager
  95150. * @param scene defines the current scene
  95151. */
  95152. function MorphTargetManager(scene) {
  95153. if (scene === void 0) { scene = null; }
  95154. this._targets = new Array();
  95155. this._targetObservable = new Array();
  95156. this._activeTargets = new BABYLON.SmartArray(16);
  95157. this._supportsNormals = false;
  95158. this._supportsTangents = false;
  95159. this._vertexCount = 0;
  95160. this._uniqueId = 0;
  95161. this._tempInfluences = new Array();
  95162. if (!scene) {
  95163. scene = BABYLON.Engine.LastCreatedScene;
  95164. }
  95165. this._scene = scene;
  95166. if (this._scene) {
  95167. this._scene.morphTargetManagers.push(this);
  95168. this._uniqueId = this._scene.getUniqueId();
  95169. }
  95170. }
  95171. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  95172. /**
  95173. * Gets the unique ID of this manager
  95174. */
  95175. get: function () {
  95176. return this._uniqueId;
  95177. },
  95178. enumerable: true,
  95179. configurable: true
  95180. });
  95181. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  95182. /**
  95183. * Gets the number of vertices handled by this manager
  95184. */
  95185. get: function () {
  95186. return this._vertexCount;
  95187. },
  95188. enumerable: true,
  95189. configurable: true
  95190. });
  95191. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  95192. /**
  95193. * Gets a boolean indicating if this manager supports morphing of normals
  95194. */
  95195. get: function () {
  95196. return this._supportsNormals;
  95197. },
  95198. enumerable: true,
  95199. configurable: true
  95200. });
  95201. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  95202. /**
  95203. * Gets a boolean indicating if this manager supports morphing of tangents
  95204. */
  95205. get: function () {
  95206. return this._supportsTangents;
  95207. },
  95208. enumerable: true,
  95209. configurable: true
  95210. });
  95211. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  95212. /**
  95213. * Gets the number of targets stored in this manager
  95214. */
  95215. get: function () {
  95216. return this._targets.length;
  95217. },
  95218. enumerable: true,
  95219. configurable: true
  95220. });
  95221. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  95222. /**
  95223. * Gets the number of influencers (ie. the number of targets with influences > 0)
  95224. */
  95225. get: function () {
  95226. return this._activeTargets.length;
  95227. },
  95228. enumerable: true,
  95229. configurable: true
  95230. });
  95231. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  95232. /**
  95233. * Gets the list of influences (one per target)
  95234. */
  95235. get: function () {
  95236. return this._influences;
  95237. },
  95238. enumerable: true,
  95239. configurable: true
  95240. });
  95241. /**
  95242. * Gets the active target at specified index. An active target is a target with an influence > 0
  95243. * @param index defines the index to check
  95244. * @returns the requested target
  95245. */
  95246. MorphTargetManager.prototype.getActiveTarget = function (index) {
  95247. return this._activeTargets.data[index];
  95248. };
  95249. /**
  95250. * Gets the target at specified index
  95251. * @param index defines the index to check
  95252. * @returns the requested target
  95253. */
  95254. MorphTargetManager.prototype.getTarget = function (index) {
  95255. return this._targets[index];
  95256. };
  95257. /**
  95258. * Add a new target to this manager
  95259. * @param target defines the target to add
  95260. */
  95261. MorphTargetManager.prototype.addTarget = function (target) {
  95262. var _this = this;
  95263. this._targets.push(target);
  95264. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  95265. _this._syncActiveTargets(needUpdate);
  95266. }));
  95267. this._syncActiveTargets(true);
  95268. };
  95269. /**
  95270. * Removes a target from the manager
  95271. * @param target defines the target to remove
  95272. */
  95273. MorphTargetManager.prototype.removeTarget = function (target) {
  95274. var index = this._targets.indexOf(target);
  95275. if (index >= 0) {
  95276. this._targets.splice(index, 1);
  95277. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  95278. this._syncActiveTargets(true);
  95279. }
  95280. };
  95281. /**
  95282. * Serializes the current manager into a Serialization object
  95283. * @returns the serialized object
  95284. */
  95285. MorphTargetManager.prototype.serialize = function () {
  95286. var serializationObject = {};
  95287. serializationObject.id = this.uniqueId;
  95288. serializationObject.targets = [];
  95289. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95290. var target = _a[_i];
  95291. serializationObject.targets.push(target.serialize());
  95292. }
  95293. return serializationObject;
  95294. };
  95295. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  95296. var influenceCount = 0;
  95297. this._activeTargets.reset();
  95298. this._supportsNormals = true;
  95299. this._supportsTangents = true;
  95300. this._vertexCount = 0;
  95301. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95302. var target = _a[_i];
  95303. this._activeTargets.push(target);
  95304. this._tempInfluences[influenceCount++] = target.influence;
  95305. var positions = target.getPositions();
  95306. if (positions) {
  95307. this._supportsNormals = this._supportsNormals && target.hasNormals;
  95308. this._supportsTangents = this._supportsTangents && target.hasTangents;
  95309. var vertexCount = positions.length / 3;
  95310. if (this._vertexCount === 0) {
  95311. this._vertexCount = vertexCount;
  95312. }
  95313. else if (this._vertexCount !== vertexCount) {
  95314. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  95315. return;
  95316. }
  95317. }
  95318. }
  95319. if (!this._influences || this._influences.length !== influenceCount) {
  95320. this._influences = new Float32Array(influenceCount);
  95321. }
  95322. for (var index = 0; index < influenceCount; index++) {
  95323. this._influences[index] = this._tempInfluences[index];
  95324. }
  95325. if (needUpdate) {
  95326. this.synchronize();
  95327. }
  95328. };
  95329. /**
  95330. * Syncrhonize the targets with all the meshes using this morph target manager
  95331. */
  95332. MorphTargetManager.prototype.synchronize = function () {
  95333. if (!this._scene) {
  95334. return;
  95335. }
  95336. // Flag meshes as dirty to resync with the active targets
  95337. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  95338. var mesh = _a[_i];
  95339. if (mesh.morphTargetManager === this) {
  95340. mesh._syncGeometryWithMorphTargetManager();
  95341. }
  95342. }
  95343. };
  95344. // Statics
  95345. /**
  95346. * Creates a new MorphTargetManager from serialized data
  95347. * @param serializationObject defines the serialized data
  95348. * @param scene defines the hosting scene
  95349. * @returns the new MorphTargetManager
  95350. */
  95351. MorphTargetManager.Parse = function (serializationObject, scene) {
  95352. var result = new MorphTargetManager(scene);
  95353. result._uniqueId = serializationObject.id;
  95354. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  95355. var targetData = _a[_i];
  95356. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  95357. }
  95358. return result;
  95359. };
  95360. return MorphTargetManager;
  95361. }());
  95362. BABYLON.MorphTargetManager = MorphTargetManager;
  95363. })(BABYLON || (BABYLON = {}));
  95364. //# sourceMappingURL=babylon.morphTargetManager.js.map
  95365. var BABYLON;
  95366. (function (BABYLON) {
  95367. var Octree = /** @class */ (function () {
  95368. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  95369. if (maxDepth === void 0) { maxDepth = 2; }
  95370. this.maxDepth = maxDepth;
  95371. this.dynamicContent = new Array();
  95372. this._maxBlockCapacity = maxBlockCapacity || 64;
  95373. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  95374. this._creationFunc = creationFunc;
  95375. }
  95376. // Methods
  95377. Octree.prototype.update = function (worldMin, worldMax, entries) {
  95378. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  95379. };
  95380. Octree.prototype.addMesh = function (entry) {
  95381. for (var index = 0; index < this.blocks.length; index++) {
  95382. var block = this.blocks[index];
  95383. block.addEntry(entry);
  95384. }
  95385. };
  95386. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  95387. this._selectionContent.reset();
  95388. for (var index = 0; index < this.blocks.length; index++) {
  95389. var block = this.blocks[index];
  95390. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  95391. }
  95392. if (allowDuplicate) {
  95393. this._selectionContent.concat(this.dynamicContent);
  95394. }
  95395. else {
  95396. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95397. }
  95398. return this._selectionContent;
  95399. };
  95400. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  95401. this._selectionContent.reset();
  95402. for (var index = 0; index < this.blocks.length; index++) {
  95403. var block = this.blocks[index];
  95404. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  95405. }
  95406. if (allowDuplicate) {
  95407. this._selectionContent.concat(this.dynamicContent);
  95408. }
  95409. else {
  95410. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95411. }
  95412. return this._selectionContent;
  95413. };
  95414. Octree.prototype.intersectsRay = function (ray) {
  95415. this._selectionContent.reset();
  95416. for (var index = 0; index < this.blocks.length; index++) {
  95417. var block = this.blocks[index];
  95418. block.intersectsRay(ray, this._selectionContent);
  95419. }
  95420. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95421. return this._selectionContent;
  95422. };
  95423. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  95424. target.blocks = new Array();
  95425. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  95426. // Segmenting space
  95427. for (var x = 0; x < 2; x++) {
  95428. for (var y = 0; y < 2; y++) {
  95429. for (var z = 0; z < 2; z++) {
  95430. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  95431. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  95432. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  95433. block.addEntries(entries);
  95434. target.blocks.push(block);
  95435. }
  95436. }
  95437. }
  95438. };
  95439. Octree.CreationFuncForMeshes = function (entry, block) {
  95440. var boundingInfo = entry.getBoundingInfo();
  95441. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  95442. block.entries.push(entry);
  95443. }
  95444. };
  95445. Octree.CreationFuncForSubMeshes = function (entry, block) {
  95446. var boundingInfo = entry.getBoundingInfo();
  95447. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  95448. block.entries.push(entry);
  95449. }
  95450. };
  95451. return Octree;
  95452. }());
  95453. BABYLON.Octree = Octree;
  95454. })(BABYLON || (BABYLON = {}));
  95455. //# sourceMappingURL=babylon.octree.js.map
  95456. var BABYLON;
  95457. (function (BABYLON) {
  95458. var OctreeBlock = /** @class */ (function () {
  95459. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  95460. this.entries = new Array();
  95461. this._boundingVectors = new Array();
  95462. this._capacity = capacity;
  95463. this._depth = depth;
  95464. this._maxDepth = maxDepth;
  95465. this._creationFunc = creationFunc;
  95466. this._minPoint = minPoint;
  95467. this._maxPoint = maxPoint;
  95468. this._boundingVectors.push(minPoint.clone());
  95469. this._boundingVectors.push(maxPoint.clone());
  95470. this._boundingVectors.push(minPoint.clone());
  95471. this._boundingVectors[2].x = maxPoint.x;
  95472. this._boundingVectors.push(minPoint.clone());
  95473. this._boundingVectors[3].y = maxPoint.y;
  95474. this._boundingVectors.push(minPoint.clone());
  95475. this._boundingVectors[4].z = maxPoint.z;
  95476. this._boundingVectors.push(maxPoint.clone());
  95477. this._boundingVectors[5].z = minPoint.z;
  95478. this._boundingVectors.push(maxPoint.clone());
  95479. this._boundingVectors[6].x = minPoint.x;
  95480. this._boundingVectors.push(maxPoint.clone());
  95481. this._boundingVectors[7].y = minPoint.y;
  95482. }
  95483. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  95484. // Property
  95485. get: function () {
  95486. return this._capacity;
  95487. },
  95488. enumerable: true,
  95489. configurable: true
  95490. });
  95491. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  95492. get: function () {
  95493. return this._minPoint;
  95494. },
  95495. enumerable: true,
  95496. configurable: true
  95497. });
  95498. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  95499. get: function () {
  95500. return this._maxPoint;
  95501. },
  95502. enumerable: true,
  95503. configurable: true
  95504. });
  95505. // Methods
  95506. OctreeBlock.prototype.addEntry = function (entry) {
  95507. if (this.blocks) {
  95508. for (var index = 0; index < this.blocks.length; index++) {
  95509. var block = this.blocks[index];
  95510. block.addEntry(entry);
  95511. }
  95512. return;
  95513. }
  95514. this._creationFunc(entry, this);
  95515. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  95516. this.createInnerBlocks();
  95517. }
  95518. };
  95519. OctreeBlock.prototype.addEntries = function (entries) {
  95520. for (var index = 0; index < entries.length; index++) {
  95521. var mesh = entries[index];
  95522. this.addEntry(mesh);
  95523. }
  95524. };
  95525. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  95526. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  95527. if (this.blocks) {
  95528. for (var index = 0; index < this.blocks.length; index++) {
  95529. var block = this.blocks[index];
  95530. block.select(frustumPlanes, selection, allowDuplicate);
  95531. }
  95532. return;
  95533. }
  95534. if (allowDuplicate) {
  95535. selection.concat(this.entries);
  95536. }
  95537. else {
  95538. selection.concatWithNoDuplicate(this.entries);
  95539. }
  95540. }
  95541. };
  95542. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  95543. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  95544. if (this.blocks) {
  95545. for (var index = 0; index < this.blocks.length; index++) {
  95546. var block = this.blocks[index];
  95547. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  95548. }
  95549. return;
  95550. }
  95551. if (allowDuplicate) {
  95552. selection.concat(this.entries);
  95553. }
  95554. else {
  95555. selection.concatWithNoDuplicate(this.entries);
  95556. }
  95557. }
  95558. };
  95559. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  95560. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  95561. if (this.blocks) {
  95562. for (var index = 0; index < this.blocks.length; index++) {
  95563. var block = this.blocks[index];
  95564. block.intersectsRay(ray, selection);
  95565. }
  95566. return;
  95567. }
  95568. selection.concatWithNoDuplicate(this.entries);
  95569. }
  95570. };
  95571. OctreeBlock.prototype.createInnerBlocks = function () {
  95572. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  95573. };
  95574. return OctreeBlock;
  95575. }());
  95576. BABYLON.OctreeBlock = OctreeBlock;
  95577. })(BABYLON || (BABYLON = {}));
  95578. //# sourceMappingURL=babylon.octreeBlock.js.map
  95579. var BABYLON;
  95580. (function (BABYLON) {
  95581. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  95582. if (maxCapacity === void 0) { maxCapacity = 64; }
  95583. if (maxDepth === void 0) { maxDepth = 2; }
  95584. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  95585. if (!component) {
  95586. component = new OctreeSceneComponent(this);
  95587. this._addComponent(component);
  95588. }
  95589. if (!this._selectionOctree) {
  95590. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  95591. }
  95592. var worldExtends = this.getWorldExtends();
  95593. // Update octree
  95594. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  95595. return this._selectionOctree;
  95596. };
  95597. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  95598. get: function () {
  95599. return this._selectionOctree;
  95600. },
  95601. enumerable: true,
  95602. configurable: true
  95603. });
  95604. /**
  95605. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  95606. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  95607. * @param maxCapacity defines the maximum size of each block (64 by default)
  95608. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  95609. * @returns the new octree
  95610. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  95611. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  95612. */
  95613. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  95614. if (maxCapacity === void 0) { maxCapacity = 64; }
  95615. if (maxDepth === void 0) { maxDepth = 2; }
  95616. var scene = this.getScene();
  95617. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  95618. if (!component) {
  95619. component = new OctreeSceneComponent(scene);
  95620. scene._addComponent(component);
  95621. }
  95622. if (!this._submeshesOctree) {
  95623. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  95624. }
  95625. this.computeWorldMatrix(true);
  95626. var boundingInfo = this.getBoundingInfo();
  95627. // Update octree
  95628. var bbox = boundingInfo.boundingBox;
  95629. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  95630. return this._submeshesOctree;
  95631. };
  95632. /**
  95633. * Defines the octree scene component responsible to manage any octrees
  95634. * in a given scene.
  95635. */
  95636. var OctreeSceneComponent = /** @class */ (function () {
  95637. /**
  95638. * Creates a new instance of the component for the given scene
  95639. * @param scene Defines the scene to register the component in
  95640. */
  95641. function OctreeSceneComponent(scene) {
  95642. /**
  95643. * The component name helpfull to identify the component in the list of scene components.
  95644. */
  95645. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  95646. /**
  95647. * Indicates if the meshes have been checked to make sure they are isEnabled()
  95648. */
  95649. this.checksIsEnabled = true;
  95650. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  95651. this.scene = scene;
  95652. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  95653. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  95654. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  95655. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  95656. }
  95657. /**
  95658. * Registers the component in a given scene
  95659. */
  95660. OctreeSceneComponent.prototype.register = function () {
  95661. var _this = this;
  95662. this.scene.onMeshRemovedObservable.add(function (mesh) {
  95663. var sceneOctree = _this.scene.selectionOctree;
  95664. if (sceneOctree !== undefined && sceneOctree !== null) {
  95665. var index = sceneOctree.dynamicContent.indexOf(mesh);
  95666. if (index !== -1) {
  95667. sceneOctree.dynamicContent.splice(index, 1);
  95668. }
  95669. }
  95670. });
  95671. this.scene.onMeshImportedObservable.add(function (mesh) {
  95672. var sceneOctree = _this.scene.selectionOctree;
  95673. if (sceneOctree !== undefined && sceneOctree !== null) {
  95674. sceneOctree.addMesh(mesh);
  95675. }
  95676. });
  95677. };
  95678. /**
  95679. * Return the list of active meshes
  95680. * @returns the list of active meshes
  95681. */
  95682. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  95683. if (this.scene._selectionOctree) {
  95684. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  95685. return selection;
  95686. }
  95687. return this.scene._getDefaultMeshCandidates();
  95688. };
  95689. /**
  95690. * Return the list of active sub meshes
  95691. * @param mesh The mesh to get the candidates sub meshes from
  95692. * @returns the list of active sub meshes
  95693. */
  95694. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  95695. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  95696. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  95697. return intersections;
  95698. }
  95699. return this.scene._getDefaultSubMeshCandidates(mesh);
  95700. };
  95701. /**
  95702. * Return the list of sub meshes intersecting with a given local ray
  95703. * @param mesh defines the mesh to find the submesh for
  95704. * @param localRay defines the ray in local space
  95705. * @returns the list of intersecting sub meshes
  95706. */
  95707. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  95708. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  95709. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  95710. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  95711. return intersections;
  95712. }
  95713. return this.scene._getDefaultSubMeshCandidates(mesh);
  95714. };
  95715. /**
  95716. * Return the list of sub meshes colliding with a collider
  95717. * @param mesh defines the mesh to find the submesh for
  95718. * @param collider defines the collider to evaluate the collision against
  95719. * @returns the list of colliding sub meshes
  95720. */
  95721. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  95722. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  95723. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  95724. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  95725. return intersections;
  95726. }
  95727. return this.scene._getDefaultSubMeshCandidates(mesh);
  95728. };
  95729. /**
  95730. * Rebuilds the elements related to this component in case of
  95731. * context lost for instance.
  95732. */
  95733. OctreeSceneComponent.prototype.rebuild = function () {
  95734. // Nothing to do here.
  95735. };
  95736. /**
  95737. * Disposes the component and the associated ressources.
  95738. */
  95739. OctreeSceneComponent.prototype.dispose = function () {
  95740. // Nothing to do here.
  95741. };
  95742. return OctreeSceneComponent;
  95743. }());
  95744. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  95745. })(BABYLON || (BABYLON = {}));
  95746. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  95747. var BABYLON;
  95748. (function (BABYLON) {
  95749. /**
  95750. * Postprocess used to generate anaglyphic rendering
  95751. */
  95752. var AnaglyphPostProcess = /** @class */ (function (_super) {
  95753. __extends(AnaglyphPostProcess, _super);
  95754. /**
  95755. * Creates a new AnaglyphPostProcess
  95756. * @param name defines postprocess name
  95757. * @param options defines creation options or target ratio scale
  95758. * @param rigCameras defines cameras using this postprocess
  95759. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  95760. * @param engine defines hosting engine
  95761. * @param reusable defines if the postprocess will be reused multiple times per frame
  95762. */
  95763. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  95764. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  95765. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95766. _this.onApplyObservable.add(function (effect) {
  95767. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  95768. });
  95769. return _this;
  95770. }
  95771. return AnaglyphPostProcess;
  95772. }(BABYLON.PostProcess));
  95773. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  95774. })(BABYLON || (BABYLON = {}));
  95775. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  95776. var BABYLON;
  95777. (function (BABYLON) {
  95778. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  95779. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95780. });
  95781. /**
  95782. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  95783. */
  95784. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  95785. __extends(AnaglyphArcRotateCamera, _super);
  95786. /**
  95787. * Creates a new AnaglyphArcRotateCamera
  95788. * @param name defines camera name
  95789. * @param alpha defines alpha angle (in radians)
  95790. * @param beta defines beta angle (in radians)
  95791. * @param radius defines radius
  95792. * @param target defines camera target
  95793. * @param interaxialDistance defines distance between each color axis
  95794. * @param scene defines the hosting scene
  95795. */
  95796. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  95797. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95798. _this.interaxialDistance = interaxialDistance;
  95799. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95800. return _this;
  95801. }
  95802. /**
  95803. * Gets camera class name
  95804. * @returns AnaglyphArcRotateCamera
  95805. */
  95806. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  95807. return "AnaglyphArcRotateCamera";
  95808. };
  95809. return AnaglyphArcRotateCamera;
  95810. }(BABYLON.ArcRotateCamera));
  95811. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  95812. })(BABYLON || (BABYLON = {}));
  95813. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  95814. var BABYLON;
  95815. (function (BABYLON) {
  95816. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  95817. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95818. });
  95819. /**
  95820. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  95821. */
  95822. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  95823. __extends(AnaglyphFreeCamera, _super);
  95824. /**
  95825. * Creates a new AnaglyphFreeCamera
  95826. * @param name defines camera name
  95827. * @param position defines initial position
  95828. * @param interaxialDistance defines distance between each color axis
  95829. * @param scene defines the hosting scene
  95830. */
  95831. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  95832. var _this = _super.call(this, name, position, scene) || this;
  95833. _this.interaxialDistance = interaxialDistance;
  95834. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95835. return _this;
  95836. }
  95837. /**
  95838. * Gets camera class name
  95839. * @returns AnaglyphFreeCamera
  95840. */
  95841. AnaglyphFreeCamera.prototype.getClassName = function () {
  95842. return "AnaglyphFreeCamera";
  95843. };
  95844. return AnaglyphFreeCamera;
  95845. }(BABYLON.FreeCamera));
  95846. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  95847. })(BABYLON || (BABYLON = {}));
  95848. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  95849. var BABYLON;
  95850. (function (BABYLON) {
  95851. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  95852. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95853. });
  95854. /**
  95855. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  95856. */
  95857. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  95858. __extends(AnaglyphGamepadCamera, _super);
  95859. /**
  95860. * Creates a new AnaglyphGamepadCamera
  95861. * @param name defines camera name
  95862. * @param position defines initial position
  95863. * @param interaxialDistance defines distance between each color axis
  95864. * @param scene defines the hosting scene
  95865. */
  95866. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  95867. var _this = _super.call(this, name, position, scene) || this;
  95868. _this.interaxialDistance = interaxialDistance;
  95869. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95870. return _this;
  95871. }
  95872. /**
  95873. * Gets camera class name
  95874. * @returns AnaglyphGamepadCamera
  95875. */
  95876. AnaglyphGamepadCamera.prototype.getClassName = function () {
  95877. return "AnaglyphGamepadCamera";
  95878. };
  95879. return AnaglyphGamepadCamera;
  95880. }(BABYLON.GamepadCamera));
  95881. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  95882. })(BABYLON || (BABYLON = {}));
  95883. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  95884. var BABYLON;
  95885. (function (BABYLON) {
  95886. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  95887. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95888. });
  95889. /**
  95890. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  95891. */
  95892. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  95893. __extends(AnaglyphUniversalCamera, _super);
  95894. /**
  95895. * Creates a new AnaglyphUniversalCamera
  95896. * @param name defines camera name
  95897. * @param position defines initial position
  95898. * @param interaxialDistance defines distance between each color axis
  95899. * @param scene defines the hosting scene
  95900. */
  95901. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  95902. var _this = _super.call(this, name, position, scene) || this;
  95903. _this.interaxialDistance = interaxialDistance;
  95904. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95905. return _this;
  95906. }
  95907. /**
  95908. * Gets camera class name
  95909. * @returns AnaglyphUniversalCamera
  95910. */
  95911. AnaglyphUniversalCamera.prototype.getClassName = function () {
  95912. return "AnaglyphUniversalCamera";
  95913. };
  95914. return AnaglyphUniversalCamera;
  95915. }(BABYLON.UniversalCamera));
  95916. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  95917. })(BABYLON || (BABYLON = {}));
  95918. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  95919. var BABYLON;
  95920. (function (BABYLON) {
  95921. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  95922. __extends(StereoscopicInterlacePostProcess, _super);
  95923. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  95924. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  95925. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95926. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95927. _this.onSizeChangedObservable.add(function () {
  95928. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95929. });
  95930. _this.onApplyObservable.add(function (effect) {
  95931. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  95932. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  95933. });
  95934. return _this;
  95935. }
  95936. return StereoscopicInterlacePostProcess;
  95937. }(BABYLON.PostProcess));
  95938. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  95939. })(BABYLON || (BABYLON = {}));
  95940. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  95941. var BABYLON;
  95942. (function (BABYLON) {
  95943. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  95944. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95945. });
  95946. /**
  95947. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  95948. */
  95949. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  95950. __extends(StereoscopicArcRotateCamera, _super);
  95951. /**
  95952. * Creates a new StereoscopicArcRotateCamera
  95953. * @param name defines camera name
  95954. * @param alpha defines alpha angle (in radians)
  95955. * @param beta defines beta angle (in radians)
  95956. * @param radius defines radius
  95957. * @param target defines camera target
  95958. * @param interaxialDistance defines distance between each color axis
  95959. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95960. * @param scene defines the hosting scene
  95961. */
  95962. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  95963. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95964. _this.interaxialDistance = interaxialDistance;
  95965. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95966. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95967. return _this;
  95968. }
  95969. /**
  95970. * Gets camera class name
  95971. * @returns StereoscopicArcRotateCamera
  95972. */
  95973. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  95974. return "StereoscopicArcRotateCamera";
  95975. };
  95976. return StereoscopicArcRotateCamera;
  95977. }(BABYLON.ArcRotateCamera));
  95978. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  95979. })(BABYLON || (BABYLON = {}));
  95980. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  95981. var BABYLON;
  95982. (function (BABYLON) {
  95983. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  95984. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95985. });
  95986. /**
  95987. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  95988. */
  95989. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  95990. __extends(StereoscopicFreeCamera, _super);
  95991. /**
  95992. * Creates a new StereoscopicFreeCamera
  95993. * @param name defines camera name
  95994. * @param position defines initial position
  95995. * @param interaxialDistance defines distance between each color axis
  95996. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95997. * @param scene defines the hosting scene
  95998. */
  95999. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96000. var _this = _super.call(this, name, position, scene) || this;
  96001. _this.interaxialDistance = interaxialDistance;
  96002. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96003. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96004. return _this;
  96005. }
  96006. /**
  96007. * Gets camera class name
  96008. * @returns StereoscopicFreeCamera
  96009. */
  96010. StereoscopicFreeCamera.prototype.getClassName = function () {
  96011. return "StereoscopicFreeCamera";
  96012. };
  96013. return StereoscopicFreeCamera;
  96014. }(BABYLON.FreeCamera));
  96015. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  96016. })(BABYLON || (BABYLON = {}));
  96017. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  96018. var BABYLON;
  96019. (function (BABYLON) {
  96020. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  96021. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96022. });
  96023. /**
  96024. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  96025. */
  96026. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  96027. __extends(StereoscopicGamepadCamera, _super);
  96028. /**
  96029. * Creates a new StereoscopicGamepadCamera
  96030. * @param name defines camera name
  96031. * @param position defines initial position
  96032. * @param interaxialDistance defines distance between each color axis
  96033. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96034. * @param scene defines the hosting scene
  96035. */
  96036. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96037. var _this = _super.call(this, name, position, scene) || this;
  96038. _this.interaxialDistance = interaxialDistance;
  96039. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96040. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96041. return _this;
  96042. }
  96043. /**
  96044. * Gets camera class name
  96045. * @returns StereoscopicGamepadCamera
  96046. */
  96047. StereoscopicGamepadCamera.prototype.getClassName = function () {
  96048. return "StereoscopicGamepadCamera";
  96049. };
  96050. return StereoscopicGamepadCamera;
  96051. }(BABYLON.GamepadCamera));
  96052. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  96053. })(BABYLON || (BABYLON = {}));
  96054. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  96055. var BABYLON;
  96056. (function (BABYLON) {
  96057. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96058. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96059. });
  96060. /**
  96061. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  96062. */
  96063. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  96064. __extends(StereoscopicUniversalCamera, _super);
  96065. /**
  96066. * Creates a new StereoscopicUniversalCamera
  96067. * @param name defines camera name
  96068. * @param position defines initial position
  96069. * @param interaxialDistance defines distance between each color axis
  96070. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96071. * @param scene defines the hosting scene
  96072. */
  96073. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96074. var _this = _super.call(this, name, position, scene) || this;
  96075. _this.interaxialDistance = interaxialDistance;
  96076. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96077. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96078. return _this;
  96079. }
  96080. /**
  96081. * Gets camera class name
  96082. * @returns StereoscopicUniversalCamera
  96083. */
  96084. StereoscopicUniversalCamera.prototype.getClassName = function () {
  96085. return "StereoscopicUniversalCamera";
  96086. };
  96087. return StereoscopicUniversalCamera;
  96088. }(BABYLON.UniversalCamera));
  96089. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  96090. })(BABYLON || (BABYLON = {}));
  96091. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  96092. var BABYLON;
  96093. (function (BABYLON) {
  96094. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  96095. __extends(VRDistortionCorrectionPostProcess, _super);
  96096. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  96097. var _this = _super.call(this, name, "vrDistortionCorrection", [
  96098. 'LensCenter',
  96099. 'Scale',
  96100. 'ScaleIn',
  96101. 'HmdWarpParam'
  96102. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  96103. _this._isRightEye = isRightEye;
  96104. _this._distortionFactors = vrMetrics.distortionK;
  96105. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  96106. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  96107. _this.adaptScaleToCurrentViewport = true;
  96108. _this.onSizeChangedObservable.add(function () {
  96109. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  96110. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  96111. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  96112. });
  96113. _this.onApplyObservable.add(function (effect) {
  96114. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  96115. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  96116. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  96117. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  96118. });
  96119. return _this;
  96120. }
  96121. return VRDistortionCorrectionPostProcess;
  96122. }(BABYLON.PostProcess));
  96123. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  96124. })(BABYLON || (BABYLON = {}));
  96125. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  96126. var BABYLON;
  96127. (function (BABYLON) {
  96128. /**
  96129. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  96130. * Screen rotation is taken into account.
  96131. */
  96132. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  96133. function FreeCameraDeviceOrientationInput() {
  96134. var _this = this;
  96135. this._screenOrientationAngle = 0;
  96136. this._screenQuaternion = new BABYLON.Quaternion();
  96137. this._alpha = 0;
  96138. this._beta = 0;
  96139. this._gamma = 0;
  96140. this._orientationChanged = function () {
  96141. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  96142. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  96143. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  96144. };
  96145. this._deviceOrientation = function (evt) {
  96146. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  96147. _this._beta = evt.beta !== null ? evt.beta : 0;
  96148. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  96149. };
  96150. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  96151. this._orientationChanged();
  96152. }
  96153. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  96154. get: function () {
  96155. return this._camera;
  96156. },
  96157. set: function (camera) {
  96158. this._camera = camera;
  96159. if (this._camera != null && !this._camera.rotationQuaternion) {
  96160. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  96161. }
  96162. },
  96163. enumerable: true,
  96164. configurable: true
  96165. });
  96166. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96167. window.addEventListener("orientationchange", this._orientationChanged);
  96168. window.addEventListener("deviceorientation", this._deviceOrientation);
  96169. //In certain cases, the attach control is called AFTER orientation was changed,
  96170. //So this is needed.
  96171. this._orientationChanged();
  96172. };
  96173. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  96174. window.removeEventListener("orientationchange", this._orientationChanged);
  96175. window.removeEventListener("deviceorientation", this._deviceOrientation);
  96176. };
  96177. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  96178. //if no device orientation provided, don't update the rotation.
  96179. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  96180. if (!this._alpha)
  96181. return;
  96182. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  96183. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  96184. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  96185. //Mirror on XY Plane
  96186. this._camera.rotationQuaternion.z *= -1;
  96187. this._camera.rotationQuaternion.w *= -1;
  96188. };
  96189. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  96190. return "FreeCameraDeviceOrientationInput";
  96191. };
  96192. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  96193. return "deviceOrientation";
  96194. };
  96195. return FreeCameraDeviceOrientationInput;
  96196. }());
  96197. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  96198. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  96199. })(BABYLON || (BABYLON = {}));
  96200. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  96201. var BABYLON;
  96202. (function (BABYLON) {
  96203. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  96204. function ArcRotateCameraVRDeviceOrientationInput() {
  96205. this.alphaCorrection = 1;
  96206. this.betaCorrection = 1;
  96207. this.gammaCorrection = 1;
  96208. this._alpha = 0;
  96209. this._gamma = 0;
  96210. this._dirty = false;
  96211. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  96212. }
  96213. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96214. this.camera.attachControl(element, noPreventDefault);
  96215. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  96216. };
  96217. /** @hidden */
  96218. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  96219. if (evt.alpha !== null) {
  96220. this._alpha = +evt.alpha | 0;
  96221. }
  96222. if (evt.gamma !== null) {
  96223. this._gamma = +evt.gamma | 0;
  96224. }
  96225. this._dirty = true;
  96226. };
  96227. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  96228. if (this._dirty) {
  96229. this._dirty = false;
  96230. if (this._gamma < 0) {
  96231. this._gamma = 180 + this._gamma;
  96232. }
  96233. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  96234. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  96235. }
  96236. };
  96237. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  96238. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  96239. };
  96240. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  96241. return "ArcRotateCameraVRDeviceOrientationInput";
  96242. };
  96243. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  96244. return "VRDeviceOrientation";
  96245. };
  96246. return ArcRotateCameraVRDeviceOrientationInput;
  96247. }());
  96248. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  96249. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  96250. })(BABYLON || (BABYLON = {}));
  96251. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  96252. var BABYLON;
  96253. (function (BABYLON) {
  96254. var VRCameraMetrics = /** @class */ (function () {
  96255. function VRCameraMetrics() {
  96256. this.compensateDistortion = true;
  96257. }
  96258. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  96259. get: function () {
  96260. return this.hResolution / (2 * this.vResolution);
  96261. },
  96262. enumerable: true,
  96263. configurable: true
  96264. });
  96265. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  96266. get: function () {
  96267. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  96268. },
  96269. enumerable: true,
  96270. configurable: true
  96271. });
  96272. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  96273. get: function () {
  96274. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96275. var h = (4 * meters) / this.hScreenSize;
  96276. return BABYLON.Matrix.Translation(h, 0, 0);
  96277. },
  96278. enumerable: true,
  96279. configurable: true
  96280. });
  96281. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  96282. get: function () {
  96283. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96284. var h = (4 * meters) / this.hScreenSize;
  96285. return BABYLON.Matrix.Translation(-h, 0, 0);
  96286. },
  96287. enumerable: true,
  96288. configurable: true
  96289. });
  96290. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  96291. get: function () {
  96292. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  96293. },
  96294. enumerable: true,
  96295. configurable: true
  96296. });
  96297. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  96298. get: function () {
  96299. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  96300. },
  96301. enumerable: true,
  96302. configurable: true
  96303. });
  96304. VRCameraMetrics.GetDefault = function () {
  96305. var result = new VRCameraMetrics();
  96306. result.hResolution = 1280;
  96307. result.vResolution = 800;
  96308. result.hScreenSize = 0.149759993;
  96309. result.vScreenSize = 0.0935999975;
  96310. result.vScreenCenter = 0.0467999987;
  96311. result.eyeToScreenDistance = 0.0410000011;
  96312. result.lensSeparationDistance = 0.0635000020;
  96313. result.interpupillaryDistance = 0.0640000030;
  96314. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  96315. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  96316. result.postProcessScaleFactor = 1.714605507808412;
  96317. result.lensCenterOffset = 0.151976421;
  96318. return result;
  96319. };
  96320. return VRCameraMetrics;
  96321. }());
  96322. BABYLON.VRCameraMetrics = VRCameraMetrics;
  96323. })(BABYLON || (BABYLON = {}));
  96324. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  96325. var BABYLON;
  96326. (function (BABYLON) {
  96327. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  96328. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96329. });
  96330. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  96331. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96332. });
  96333. /**
  96334. * This represents a WebVR camera.
  96335. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  96336. * @example http://doc.babylonjs.com/how_to/webvr_camera
  96337. */
  96338. var WebVRFreeCamera = /** @class */ (function (_super) {
  96339. __extends(WebVRFreeCamera, _super);
  96340. /**
  96341. * Instantiates a WebVRFreeCamera.
  96342. * @param name The name of the WebVRFreeCamera
  96343. * @param position The starting anchor position for the camera
  96344. * @param scene The scene the camera belongs to
  96345. * @param webVROptions a set of customizable options for the webVRCamera
  96346. */
  96347. function WebVRFreeCamera(name, position, scene, webVROptions) {
  96348. if (webVROptions === void 0) { webVROptions = {}; }
  96349. var _this = _super.call(this, name, position, scene) || this;
  96350. _this.webVROptions = webVROptions;
  96351. /**
  96352. * @hidden
  96353. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  96354. */
  96355. _this._vrDevice = null;
  96356. /**
  96357. * The rawPose of the vrDevice.
  96358. */
  96359. _this.rawPose = null;
  96360. _this._specsVersion = "1.1";
  96361. _this._attached = false;
  96362. _this._descendants = [];
  96363. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  96364. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  96365. /** @hidden */
  96366. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  96367. _this._standingMatrix = null;
  96368. /**
  96369. * Represents device position in babylon space.
  96370. */
  96371. _this.devicePosition = BABYLON.Vector3.Zero();
  96372. /**
  96373. * Represents device rotation in babylon space.
  96374. */
  96375. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  96376. /**
  96377. * The scale of the device to be used when translating from device space to babylon space.
  96378. */
  96379. _this.deviceScaleFactor = 1;
  96380. _this._deviceToWorld = BABYLON.Matrix.Identity();
  96381. _this._worldToDevice = BABYLON.Matrix.Identity();
  96382. /**
  96383. * References to the webVR controllers for the vrDevice.
  96384. */
  96385. _this.controllers = [];
  96386. /**
  96387. * Emits an event when a controller is attached.
  96388. */
  96389. _this.onControllersAttachedObservable = new BABYLON.Observable();
  96390. /**
  96391. * Emits an event when a controller's mesh has been loaded;
  96392. */
  96393. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  96394. /**
  96395. * Emits an event when the HMD's pose has been updated.
  96396. */
  96397. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  96398. _this._poseSet = false;
  96399. /**
  96400. * If the rig cameras be used as parent instead of this camera.
  96401. */
  96402. _this.rigParenting = true;
  96403. _this._defaultHeight = undefined;
  96404. _this._htmlElementAttached = null;
  96405. _this._detachIfAttached = function () {
  96406. var vrDisplay = _this.getEngine().getVRDevice();
  96407. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  96408. _this.detachControl(_this._htmlElementAttached);
  96409. }
  96410. };
  96411. _this._workingVector = BABYLON.Vector3.Zero();
  96412. _this._oneVector = BABYLON.Vector3.One();
  96413. _this._workingMatrix = BABYLON.Matrix.Identity();
  96414. _this._tmpMatrix = new BABYLON.Matrix();
  96415. _this._cache.position = BABYLON.Vector3.Zero();
  96416. if (webVROptions.defaultHeight) {
  96417. _this._defaultHeight = webVROptions.defaultHeight;
  96418. _this.position.y = _this._defaultHeight;
  96419. }
  96420. _this.minZ = 0.1;
  96421. //legacy support - the compensation boolean was removed.
  96422. if (arguments.length === 5) {
  96423. _this.webVROptions = arguments[4];
  96424. }
  96425. // default webVR options
  96426. if (_this.webVROptions.trackPosition == undefined) {
  96427. _this.webVROptions.trackPosition = true;
  96428. }
  96429. if (_this.webVROptions.controllerMeshes == undefined) {
  96430. _this.webVROptions.controllerMeshes = true;
  96431. }
  96432. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  96433. _this.webVROptions.defaultLightingOnControllers = true;
  96434. }
  96435. _this.rotationQuaternion = new BABYLON.Quaternion();
  96436. if (_this.webVROptions && _this.webVROptions.positionScale) {
  96437. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  96438. }
  96439. //enable VR
  96440. var engine = _this.getEngine();
  96441. _this._onVREnabled = function (success) { if (success) {
  96442. _this.initControllers();
  96443. } };
  96444. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  96445. engine.initWebVR().add(function (event) {
  96446. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  96447. return;
  96448. }
  96449. _this._vrDevice = event.vrDisplay;
  96450. //reset the rig parameters.
  96451. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  96452. if (_this._attached) {
  96453. _this.getEngine().enableVR();
  96454. }
  96455. });
  96456. if (typeof (VRFrameData) !== "undefined")
  96457. _this._frameData = new VRFrameData();
  96458. /**
  96459. * The idea behind the following lines:
  96460. * objects that have the camera as parent should actually have the rig cameras as a parent.
  96461. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  96462. * the second will not show it correctly.
  96463. *
  96464. * To solve this - each object that has the camera as parent will be added to a protected array.
  96465. * When the rig camera renders, it will take this array and set all of those to be its children.
  96466. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  96467. * Amazing!
  96468. */
  96469. scene.onBeforeCameraRenderObservable.add(function (camera) {
  96470. if (camera.parent === _this && _this.rigParenting) {
  96471. _this._descendants = _this.getDescendants(true, function (n) {
  96472. // don't take the cameras or the controllers!
  96473. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  96474. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  96475. return !isController && !isRigCamera;
  96476. });
  96477. _this._descendants.forEach(function (node) {
  96478. node.parent = camera;
  96479. });
  96480. }
  96481. });
  96482. scene.onAfterCameraRenderObservable.add(function (camera) {
  96483. if (camera.parent === _this && _this.rigParenting) {
  96484. _this._descendants.forEach(function (node) {
  96485. node.parent = _this;
  96486. });
  96487. }
  96488. });
  96489. return _this;
  96490. }
  96491. /**
  96492. * Gets the device distance from the ground in meters.
  96493. * @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.
  96494. */
  96495. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  96496. if (this._standingMatrix) {
  96497. // Add standing matrix offset to get real offset from ground in room
  96498. this._standingMatrix.getTranslationToRef(this._workingVector);
  96499. return this._deviceRoomPosition.y + this._workingVector.y;
  96500. }
  96501. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  96502. return this._defaultHeight || 0;
  96503. };
  96504. /**
  96505. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  96506. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  96507. */
  96508. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  96509. var _this = this;
  96510. if (callback === void 0) { callback = function (bool) { }; }
  96511. // Use standing matrix if available
  96512. this.getEngine().initWebVRAsync().then(function (result) {
  96513. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  96514. callback(false);
  96515. }
  96516. else {
  96517. _this._standingMatrix = new BABYLON.Matrix();
  96518. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  96519. if (!_this.getScene().useRightHandedSystem) {
  96520. [2, 6, 8, 9, 14].forEach(function (num) {
  96521. if (_this._standingMatrix) {
  96522. _this._standingMatrix.m[num] *= -1;
  96523. }
  96524. });
  96525. }
  96526. callback(true);
  96527. }
  96528. });
  96529. };
  96530. /**
  96531. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  96532. * @returns A promise with a boolean set to if the standing matrix is supported.
  96533. */
  96534. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  96535. var _this = this;
  96536. return new Promise(function (res, rej) {
  96537. _this.useStandingMatrix(function (supported) {
  96538. res(supported);
  96539. });
  96540. });
  96541. };
  96542. /**
  96543. * Disposes the camera
  96544. */
  96545. WebVRFreeCamera.prototype.dispose = function () {
  96546. this._detachIfAttached();
  96547. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  96548. _super.prototype.dispose.call(this);
  96549. };
  96550. /**
  96551. * Gets a vrController by name.
  96552. * @param name The name of the controller to retreive
  96553. * @returns the controller matching the name specified or null if not found
  96554. */
  96555. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  96556. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  96557. var gp = _a[_i];
  96558. if (gp.hand === name) {
  96559. return gp;
  96560. }
  96561. }
  96562. return null;
  96563. };
  96564. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  96565. /**
  96566. * The controller corrisponding to the users left hand.
  96567. */
  96568. get: function () {
  96569. if (!this._leftController) {
  96570. this._leftController = this.getControllerByName("left");
  96571. }
  96572. return this._leftController;
  96573. },
  96574. enumerable: true,
  96575. configurable: true
  96576. });
  96577. ;
  96578. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  96579. /**
  96580. * The controller corrisponding to the users right hand.
  96581. */
  96582. get: function () {
  96583. if (!this._rightController) {
  96584. this._rightController = this.getControllerByName("right");
  96585. }
  96586. return this._rightController;
  96587. },
  96588. enumerable: true,
  96589. configurable: true
  96590. });
  96591. ;
  96592. /**
  96593. * Casts a ray forward from the vrCamera's gaze.
  96594. * @param length Length of the ray (default: 100)
  96595. * @returns the ray corrisponding to the gaze
  96596. */
  96597. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  96598. if (length === void 0) { length = 100; }
  96599. if (this.leftCamera) {
  96600. // Use left eye to avoid computation to compute center on every call
  96601. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  96602. }
  96603. else {
  96604. return _super.prototype.getForwardRay.call(this, length);
  96605. }
  96606. };
  96607. /**
  96608. * @hidden
  96609. * Updates the camera based on device's frame data
  96610. */
  96611. WebVRFreeCamera.prototype._checkInputs = function () {
  96612. if (this._vrDevice && this._vrDevice.isPresenting) {
  96613. this._vrDevice.getFrameData(this._frameData);
  96614. this.updateFromDevice(this._frameData.pose);
  96615. }
  96616. _super.prototype._checkInputs.call(this);
  96617. };
  96618. /**
  96619. * Updates the poseControlled values based on the input device pose.
  96620. * @param poseData Pose coming from the device
  96621. */
  96622. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  96623. if (poseData && poseData.orientation) {
  96624. this.rawPose = poseData;
  96625. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  96626. if (this.getScene().useRightHandedSystem) {
  96627. this._deviceRoomRotationQuaternion.z *= -1;
  96628. this._deviceRoomRotationQuaternion.w *= -1;
  96629. }
  96630. if (this.webVROptions.trackPosition && this.rawPose.position) {
  96631. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  96632. if (this.getScene().useRightHandedSystem) {
  96633. this._deviceRoomPosition.z *= -1;
  96634. }
  96635. }
  96636. this._poseSet = true;
  96637. }
  96638. };
  96639. /**
  96640. * WebVR's attach control will start broadcasting frames to the device.
  96641. * Note that in certain browsers (chrome for example) this function must be called
  96642. * within a user-interaction callback. Example:
  96643. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  96644. *
  96645. * @param element html element to attach the vrDevice to
  96646. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  96647. */
  96648. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  96649. _super.prototype.attachControl.call(this, element, noPreventDefault);
  96650. this._attached = true;
  96651. this._htmlElementAttached = element;
  96652. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  96653. if (this._vrDevice) {
  96654. this.getEngine().enableVR();
  96655. }
  96656. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96657. };
  96658. /**
  96659. * Detaches the camera from the html element and disables VR
  96660. *
  96661. * @param element html element to detach from
  96662. */
  96663. WebVRFreeCamera.prototype.detachControl = function (element) {
  96664. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  96665. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  96666. _super.prototype.detachControl.call(this, element);
  96667. this._attached = false;
  96668. this.getEngine().disableVR();
  96669. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96670. };
  96671. /**
  96672. * @returns the name of this class
  96673. */
  96674. WebVRFreeCamera.prototype.getClassName = function () {
  96675. return "WebVRFreeCamera";
  96676. };
  96677. /**
  96678. * Calls resetPose on the vrDisplay
  96679. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  96680. */
  96681. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  96682. //uses the vrDisplay's "resetPose()".
  96683. //pitch and roll won't be affected.
  96684. this._vrDevice.resetPose();
  96685. };
  96686. /**
  96687. * @hidden
  96688. * Updates the rig cameras (left and right eye)
  96689. */
  96690. WebVRFreeCamera.prototype._updateRigCameras = function () {
  96691. var camLeft = this._rigCameras[0];
  96692. var camRight = this._rigCameras[1];
  96693. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96694. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96695. camLeft.position.copyFrom(this._deviceRoomPosition);
  96696. camRight.position.copyFrom(this._deviceRoomPosition);
  96697. };
  96698. // Remove translation from 6dof headset if trackposition is set to false
  96699. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  96700. if (isViewMatrix === void 0) { isViewMatrix = false; }
  96701. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  96702. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  96703. if (!isViewMatrix) {
  96704. this._tmpMatrix.invert();
  96705. }
  96706. this._tmpMatrix.multiplyToRef(matrix, matrix);
  96707. }
  96708. };
  96709. /**
  96710. * @hidden
  96711. * Updates the cached values of the camera
  96712. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  96713. */
  96714. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  96715. var _this = this;
  96716. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  96717. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  96718. if (!this.updateCacheCalled) {
  96719. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  96720. this.updateCacheCalled = true;
  96721. this.update();
  96722. }
  96723. // Set working vector to the device position in room space rotated by the new rotation
  96724. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  96725. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  96726. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  96727. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  96728. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  96729. // Add translation from anchor position
  96730. this._deviceToWorld.getTranslationToRef(this._workingVector);
  96731. this._workingVector.addInPlace(this.position);
  96732. this._workingVector.subtractInPlace(this._cache.position);
  96733. this._deviceToWorld.setTranslation(this._workingVector);
  96734. // Set an inverted matrix to be used when updating the camera
  96735. this._deviceToWorld.invertToRef(this._worldToDevice);
  96736. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  96737. this.controllers.forEach(function (controller) {
  96738. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  96739. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  96740. controller.update();
  96741. });
  96742. }
  96743. if (!ignoreParentClass) {
  96744. _super.prototype._updateCache.call(this);
  96745. }
  96746. this.updateCacheCalled = false;
  96747. };
  96748. /**
  96749. * Updates the current device position and rotation in the babylon world
  96750. */
  96751. WebVRFreeCamera.prototype.update = function () {
  96752. // Get current device position in babylon world
  96753. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  96754. // Get current device rotation in babylon world
  96755. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  96756. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  96757. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  96758. if (this._poseSet) {
  96759. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  96760. }
  96761. _super.prototype.update.call(this);
  96762. };
  96763. /**
  96764. * @hidden
  96765. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  96766. * @returns an identity matrix
  96767. */
  96768. WebVRFreeCamera.prototype._getViewMatrix = function () {
  96769. return BABYLON.Matrix.Identity();
  96770. };
  96771. /**
  96772. * This function is called by the two RIG cameras.
  96773. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  96774. */
  96775. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  96776. var _this = this;
  96777. // Update the parent camera prior to using a child camera to avoid desynchronization
  96778. var parentCamera = this._cameraRigParams["parentCamera"];
  96779. parentCamera._updateCache();
  96780. //WebVR 1.1
  96781. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  96782. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  96783. if (!this.getScene().useRightHandedSystem) {
  96784. [2, 6, 8, 9, 14].forEach(function (num) {
  96785. _this._webvrViewMatrix.m[num] *= -1;
  96786. });
  96787. }
  96788. // update the camera rotation matrix
  96789. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  96790. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  96791. // Computing target and final matrix
  96792. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  96793. // should the view matrix be updated with scale and position offset?
  96794. if (parentCamera.deviceScaleFactor !== 1) {
  96795. this._webvrViewMatrix.invert();
  96796. // scale the position, if set
  96797. if (parentCamera.deviceScaleFactor) {
  96798. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  96799. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  96800. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  96801. }
  96802. this._webvrViewMatrix.invert();
  96803. }
  96804. // Remove translation from 6dof headset if trackposition is set to false
  96805. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  96806. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  96807. // Compute global position
  96808. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  96809. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  96810. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  96811. this._workingMatrix.getTranslationToRef(this._globalPosition);
  96812. this._markSyncedWithParent();
  96813. return this._webvrViewMatrix;
  96814. };
  96815. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  96816. var _this = this;
  96817. var parentCamera = this.parent;
  96818. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  96819. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  96820. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  96821. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  96822. //babylon compatible matrix
  96823. if (!this.getScene().useRightHandedSystem) {
  96824. [8, 9, 10, 11].forEach(function (num) {
  96825. _this._projectionMatrix.m[num] *= -1;
  96826. });
  96827. }
  96828. return this._projectionMatrix;
  96829. };
  96830. /**
  96831. * Initializes the controllers and their meshes
  96832. */
  96833. WebVRFreeCamera.prototype.initControllers = function () {
  96834. var _this = this;
  96835. this.controllers = [];
  96836. var manager = this.getScene().gamepadManager;
  96837. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  96838. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96839. var webVrController = gamepad;
  96840. if (webVrController.defaultModel) {
  96841. webVrController.defaultModel.setEnabled(false);
  96842. }
  96843. if (webVrController.hand === "right") {
  96844. _this._rightController = null;
  96845. }
  96846. if (webVrController.hand === "left") {
  96847. _this._leftController = null;
  96848. }
  96849. var controllerIndex = _this.controllers.indexOf(webVrController);
  96850. if (controllerIndex !== -1) {
  96851. _this.controllers.splice(controllerIndex, 1);
  96852. }
  96853. }
  96854. });
  96855. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  96856. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96857. var webVrController_1 = gamepad;
  96858. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  96859. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  96860. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  96861. if (_this.webVROptions.controllerMeshes) {
  96862. if (webVrController_1.defaultModel) {
  96863. webVrController_1.defaultModel.setEnabled(true);
  96864. }
  96865. else {
  96866. // Load the meshes
  96867. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  96868. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  96869. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  96870. if (_this.webVROptions.defaultLightingOnControllers) {
  96871. if (!_this._lightOnControllers) {
  96872. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  96873. }
  96874. var activateLightOnSubMeshes_1 = function (mesh, light) {
  96875. var children = mesh.getChildren();
  96876. if (children && children.length !== 0) {
  96877. children.forEach(function (mesh) {
  96878. light.includedOnlyMeshes.push(mesh);
  96879. activateLightOnSubMeshes_1(mesh, light);
  96880. });
  96881. }
  96882. };
  96883. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  96884. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  96885. }
  96886. });
  96887. }
  96888. }
  96889. webVrController_1.attachToPoseControlledCamera(_this);
  96890. // since this is async - sanity check. Is the controller already stored?
  96891. if (_this.controllers.indexOf(webVrController_1) === -1) {
  96892. //add to the controllers array
  96893. _this.controllers.push(webVrController_1);
  96894. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  96895. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  96896. // So we're overriding setting left & right manually to be sure
  96897. var firstViveWandDetected = false;
  96898. for (var i = 0; i < _this.controllers.length; i++) {
  96899. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96900. if (!firstViveWandDetected) {
  96901. firstViveWandDetected = true;
  96902. _this.controllers[i].hand = "left";
  96903. }
  96904. else {
  96905. _this.controllers[i].hand = "right";
  96906. }
  96907. }
  96908. }
  96909. //did we find enough controllers? Great! let the developer know.
  96910. if (_this.controllers.length >= 2) {
  96911. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  96912. }
  96913. }
  96914. }
  96915. });
  96916. };
  96917. return WebVRFreeCamera;
  96918. }(BABYLON.FreeCamera));
  96919. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  96920. })(BABYLON || (BABYLON = {}));
  96921. //# sourceMappingURL=babylon.webVRCamera.js.map
  96922. var BABYLON;
  96923. (function (BABYLON) {
  96924. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  96925. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  96926. });
  96927. // We're mainly based on the logic defined into the FreeCamera code
  96928. /**
  96929. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  96930. * being tilted forward or back and left or right.
  96931. */
  96932. var DeviceOrientationCamera = /** @class */ (function (_super) {
  96933. __extends(DeviceOrientationCamera, _super);
  96934. /**
  96935. * Creates a new device orientation camera
  96936. * @param name The name of the camera
  96937. * @param position The start position camera
  96938. * @param scene The scene the camera belongs to
  96939. */
  96940. function DeviceOrientationCamera(name, position, scene) {
  96941. var _this = _super.call(this, name, position, scene) || this;
  96942. _this._quaternionCache = new BABYLON.Quaternion();
  96943. _this.inputs.addDeviceOrientation();
  96944. return _this;
  96945. }
  96946. /**
  96947. * Gets the current instance class name ("DeviceOrientationCamera").
  96948. * This helps avoiding instanceof at run time.
  96949. * @returns the class name
  96950. */
  96951. DeviceOrientationCamera.prototype.getClassName = function () {
  96952. return "DeviceOrientationCamera";
  96953. };
  96954. /**
  96955. * @hidden
  96956. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  96957. */
  96958. DeviceOrientationCamera.prototype._checkInputs = function () {
  96959. _super.prototype._checkInputs.call(this);
  96960. this._quaternionCache.copyFrom(this.rotationQuaternion);
  96961. if (this._initialQuaternion) {
  96962. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  96963. }
  96964. };
  96965. /**
  96966. * Reset the camera to its default orientation on the specified axis only.
  96967. * @param axis The axis to reset
  96968. */
  96969. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  96970. var _this = this;
  96971. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  96972. //can only work if this camera has a rotation quaternion already.
  96973. if (!this.rotationQuaternion)
  96974. return;
  96975. if (!this._initialQuaternion) {
  96976. this._initialQuaternion = new BABYLON.Quaternion();
  96977. }
  96978. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  96979. ['x', 'y', 'z'].forEach(function (axisName) {
  96980. if (!axis[axisName]) {
  96981. _this._initialQuaternion[axisName] = 0;
  96982. }
  96983. else {
  96984. _this._initialQuaternion[axisName] *= -1;
  96985. }
  96986. });
  96987. this._initialQuaternion.normalize();
  96988. //force rotation update
  96989. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  96990. };
  96991. return DeviceOrientationCamera;
  96992. }(BABYLON.FreeCamera));
  96993. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  96994. })(BABYLON || (BABYLON = {}));
  96995. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  96996. var BABYLON;
  96997. (function (BABYLON) {
  96998. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  96999. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97000. });
  97001. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  97002. __extends(VRDeviceOrientationFreeCamera, _super);
  97003. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97004. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97005. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97006. var _this = _super.call(this, name, position, scene) || this;
  97007. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97008. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97009. return _this;
  97010. }
  97011. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  97012. return "VRDeviceOrientationFreeCamera";
  97013. };
  97014. return VRDeviceOrientationFreeCamera;
  97015. }(BABYLON.DeviceOrientationCamera));
  97016. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  97017. })(BABYLON || (BABYLON = {}));
  97018. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  97019. var BABYLON;
  97020. (function (BABYLON) {
  97021. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97022. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  97023. });
  97024. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  97025. __extends(VRDeviceOrientationArcRotateCamera, _super);
  97026. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  97027. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97028. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97029. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97030. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97031. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97032. _this.inputs.addVRDeviceOrientation();
  97033. return _this;
  97034. }
  97035. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  97036. return "VRDeviceOrientationArcRotateCamera";
  97037. };
  97038. return VRDeviceOrientationArcRotateCamera;
  97039. }(BABYLON.ArcRotateCamera));
  97040. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  97041. })(BABYLON || (BABYLON = {}));
  97042. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  97043. var BABYLON;
  97044. (function (BABYLON) {
  97045. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  97046. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  97047. });
  97048. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  97049. __extends(VRDeviceOrientationGamepadCamera, _super);
  97050. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97051. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97052. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97053. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  97054. _this.inputs.addGamepad();
  97055. return _this;
  97056. }
  97057. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  97058. return "VRDeviceOrientationGamepadCamera";
  97059. };
  97060. return VRDeviceOrientationGamepadCamera;
  97061. }(BABYLON.VRDeviceOrientationFreeCamera));
  97062. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  97063. })(BABYLON || (BABYLON = {}));
  97064. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  97065. var BABYLON;
  97066. (function (BABYLON) {
  97067. var VRExperienceHelperGazer = /** @class */ (function () {
  97068. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  97069. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  97070. this.scene = scene;
  97071. /** @hidden */
  97072. this._pointerDownOnMeshAsked = false;
  97073. /** @hidden */
  97074. this._isActionableMesh = false;
  97075. /** @hidden */
  97076. this._teleportationRequestInitiated = false;
  97077. /** @hidden */
  97078. this._teleportationBackRequestInitiated = false;
  97079. /** @hidden */
  97080. this._rotationRightAsked = false;
  97081. /** @hidden */
  97082. this._rotationLeftAsked = false;
  97083. /** @hidden */
  97084. this._dpadPressed = true;
  97085. /** @hidden */
  97086. this._activePointer = false;
  97087. this._id = VRExperienceHelperGazer._idCounter++;
  97088. // Gaze tracker
  97089. if (!gazeTrackerToClone) {
  97090. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  97091. this._gazeTracker.bakeCurrentTransformIntoVertices();
  97092. this._gazeTracker.isPickable = false;
  97093. this._gazeTracker.isVisible = false;
  97094. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  97095. targetMat.specularColor = BABYLON.Color3.Black();
  97096. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97097. targetMat.backFaceCulling = false;
  97098. this._gazeTracker.material = targetMat;
  97099. }
  97100. else {
  97101. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  97102. }
  97103. }
  97104. /** @hidden */
  97105. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  97106. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  97107. };
  97108. /** @hidden */
  97109. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  97110. this._pointerDownOnMeshAsked = true;
  97111. if (this._currentHit) {
  97112. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  97113. }
  97114. };
  97115. /** @hidden */
  97116. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  97117. if (this._currentHit) {
  97118. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  97119. }
  97120. this._pointerDownOnMeshAsked = false;
  97121. };
  97122. /** @hidden */
  97123. VRExperienceHelperGazer.prototype._activatePointer = function () {
  97124. this._activePointer = true;
  97125. };
  97126. /** @hidden */
  97127. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  97128. this._activePointer = false;
  97129. };
  97130. /** @hidden */
  97131. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  97132. if (distance === void 0) { distance = 100; }
  97133. };
  97134. VRExperienceHelperGazer.prototype.dispose = function () {
  97135. this._interactionsEnabled = false;
  97136. this._teleportationEnabled = false;
  97137. if (this._gazeTracker) {
  97138. this._gazeTracker.dispose();
  97139. }
  97140. };
  97141. VRExperienceHelperGazer._idCounter = 0;
  97142. return VRExperienceHelperGazer;
  97143. }());
  97144. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  97145. __extends(VRExperienceHelperControllerGazer, _super);
  97146. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  97147. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  97148. _this.webVRController = webVRController;
  97149. // Laser pointer
  97150. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  97151. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  97152. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97153. laserPointerMaterial.alpha = 0.6;
  97154. _this._laserPointer.material = laserPointerMaterial;
  97155. _this._laserPointer.rotation.x = Math.PI / 2;
  97156. _this._laserPointer.position.z = -0.5;
  97157. _this._laserPointer.isVisible = false;
  97158. _this._laserPointer.isPickable = false;
  97159. if (!webVRController.mesh) {
  97160. // Create an empty mesh that is used prior to loading the high quality model
  97161. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  97162. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  97163. preloadPointerPose.rotation.x = -0.7;
  97164. preloadMesh.addChild(preloadPointerPose);
  97165. webVRController.attachToMesh(preloadMesh);
  97166. }
  97167. _this._setLaserPointerParent(webVRController.mesh);
  97168. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  97169. _this._setLaserPointerParent(mesh);
  97170. });
  97171. return _this;
  97172. }
  97173. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  97174. return this.webVRController.getForwardRay(length);
  97175. };
  97176. /** @hidden */
  97177. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  97178. _super.prototype._activatePointer.call(this);
  97179. this._laserPointer.isVisible = true;
  97180. };
  97181. /** @hidden */
  97182. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  97183. _super.prototype._deactivatePointer.call(this);
  97184. this._laserPointer.isVisible = false;
  97185. };
  97186. /** @hidden */
  97187. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  97188. this._laserPointer.material.emissiveColor = color;
  97189. };
  97190. /** @hidden */
  97191. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  97192. var makeNotPick = function (root) {
  97193. root.isPickable = false;
  97194. root.getChildMeshes().forEach(function (c) {
  97195. makeNotPick(c);
  97196. });
  97197. };
  97198. makeNotPick(mesh);
  97199. var childMeshes = mesh.getChildMeshes();
  97200. this.webVRController._pointingPoseNode = null;
  97201. for (var i = 0; i < childMeshes.length; i++) {
  97202. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  97203. mesh = childMeshes[i];
  97204. this.webVRController._pointingPoseNode = mesh;
  97205. break;
  97206. }
  97207. }
  97208. this._laserPointer.parent = mesh;
  97209. };
  97210. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  97211. if (distance === void 0) { distance = 100; }
  97212. this._laserPointer.scaling.y = distance;
  97213. this._laserPointer.position.z = -distance / 2;
  97214. };
  97215. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  97216. _super.prototype.dispose.call(this);
  97217. this._laserPointer.dispose();
  97218. if (this._meshAttachedObserver) {
  97219. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  97220. }
  97221. };
  97222. return VRExperienceHelperControllerGazer;
  97223. }(VRExperienceHelperGazer));
  97224. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  97225. __extends(VRExperienceHelperCameraGazer, _super);
  97226. function VRExperienceHelperCameraGazer(getCamera, scene) {
  97227. var _this = _super.call(this, scene) || this;
  97228. _this.getCamera = getCamera;
  97229. return _this;
  97230. }
  97231. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  97232. var camera = this.getCamera();
  97233. if (camera) {
  97234. return camera.getForwardRay(length);
  97235. }
  97236. else {
  97237. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  97238. }
  97239. };
  97240. return VRExperienceHelperCameraGazer;
  97241. }(VRExperienceHelperGazer));
  97242. /**
  97243. * Helps to quickly add VR support to an existing scene.
  97244. * See http://doc.babylonjs.com/how_to/webvr_helper
  97245. */
  97246. var VRExperienceHelper = /** @class */ (function () {
  97247. /**
  97248. * Instantiates a VRExperienceHelper.
  97249. * Helps to quickly add VR support to an existing scene.
  97250. * @param scene The scene the VRExperienceHelper belongs to.
  97251. * @param webVROptions Options to modify the vr experience helper's behavior.
  97252. */
  97253. function VRExperienceHelper(scene,
  97254. /** Options to modify the vr experience helper's behavior. */
  97255. webVROptions) {
  97256. if (webVROptions === void 0) { webVROptions = {}; }
  97257. var _this = this;
  97258. this.webVROptions = webVROptions;
  97259. // Can the system support WebVR, even if a headset isn't plugged in?
  97260. this._webVRsupported = false;
  97261. // If WebVR is supported, is a headset plugged in and are we ready to present?
  97262. this._webVRready = false;
  97263. // Are we waiting for the requestPresent callback to complete?
  97264. this._webVRrequesting = false;
  97265. // Are we presenting to the headset right now? (this is the vrDevice state)
  97266. this._webVRpresenting = false;
  97267. // Are we presenting in the fullscreen fallback?
  97268. this._fullscreenVRpresenting = false;
  97269. /**
  97270. * Observable raised when entering VR.
  97271. */
  97272. this.onEnteringVRObservable = new BABYLON.Observable();
  97273. /**
  97274. * Observable raised when exiting VR.
  97275. */
  97276. this.onExitingVRObservable = new BABYLON.Observable();
  97277. /**
  97278. * Observable raised when controller mesh is loaded.
  97279. */
  97280. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  97281. this._useCustomVRButton = false;
  97282. this._teleportationRequested = false;
  97283. this._teleportActive = false;
  97284. this._floorMeshesCollection = [];
  97285. this._rotationAllowed = true;
  97286. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  97287. this._isDefaultTeleportationTarget = true;
  97288. this._teleportationFillColor = "#444444";
  97289. this._teleportationBorderColor = "#FFFFFF";
  97290. this._rotationAngle = 0;
  97291. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  97292. this._padSensibilityUp = 0.65;
  97293. this._padSensibilityDown = 0.35;
  97294. this._leftController = null;
  97295. this._rightController = null;
  97296. /**
  97297. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  97298. */
  97299. this.onNewMeshSelected = new BABYLON.Observable();
  97300. /**
  97301. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  97302. */
  97303. this.onNewMeshPicked = new BABYLON.Observable();
  97304. /**
  97305. * Observable raised before camera teleportation
  97306. */
  97307. this.onBeforeCameraTeleport = new BABYLON.Observable();
  97308. /**
  97309. * Observable raised after camera teleportation
  97310. */
  97311. this.onAfterCameraTeleport = new BABYLON.Observable();
  97312. /**
  97313. * Observable raised when current selected mesh gets unselected
  97314. */
  97315. this.onSelectedMeshUnselected = new BABYLON.Observable();
  97316. /**
  97317. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  97318. */
  97319. this.teleportationEnabled = true;
  97320. this._teleportationInitialized = false;
  97321. this._interactionsEnabled = false;
  97322. this._interactionsRequested = false;
  97323. this._displayGaze = true;
  97324. this._displayLaserPointer = true;
  97325. /**
  97326. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  97327. */
  97328. this.updateGazeTrackerScale = true;
  97329. this._onResize = function () {
  97330. _this.moveButtonToBottomRight();
  97331. if (_this._fullscreenVRpresenting && _this._webVRready) {
  97332. _this.exitVR();
  97333. }
  97334. };
  97335. this._onFullscreenChange = function () {
  97336. if (document.fullscreen !== undefined) {
  97337. _this._fullscreenVRpresenting = document.fullscreen;
  97338. }
  97339. else if (document.mozFullScreen !== undefined) {
  97340. _this._fullscreenVRpresenting = document.mozFullScreen;
  97341. }
  97342. else if (document.webkitIsFullScreen !== undefined) {
  97343. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  97344. }
  97345. else if (document.msIsFullScreen !== undefined) {
  97346. _this._fullscreenVRpresenting = document.msIsFullScreen;
  97347. }
  97348. else if (document.msFullscreenElement !== undefined) {
  97349. _this._fullscreenVRpresenting = document.msFullscreenElement;
  97350. }
  97351. if (!_this._fullscreenVRpresenting && _this._canvas) {
  97352. _this.exitVR();
  97353. if (!_this._useCustomVRButton) {
  97354. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  97355. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  97356. }
  97357. }
  97358. };
  97359. this.beforeRender = function () {
  97360. if (_this._leftController && _this._leftController._activePointer) {
  97361. _this._castRayAndSelectObject(_this._leftController);
  97362. }
  97363. if (_this._rightController && _this._rightController._activePointer) {
  97364. _this._castRayAndSelectObject(_this._rightController);
  97365. }
  97366. if (_this._noControllerIsActive) {
  97367. _this._castRayAndSelectObject(_this._cameraGazer);
  97368. }
  97369. else {
  97370. _this._cameraGazer._gazeTracker.isVisible = false;
  97371. }
  97372. };
  97373. this._onNewGamepadConnected = function (gamepad) {
  97374. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  97375. if (gamepad.leftStick) {
  97376. gamepad.onleftstickchanged(function (stickValues) {
  97377. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  97378. // Listening to classic/xbox gamepad only if no VR controller is active
  97379. if ((!_this._leftController && !_this._rightController) ||
  97380. ((_this._leftController && !_this._leftController._activePointer) &&
  97381. (_this._rightController && !_this._rightController._activePointer))) {
  97382. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  97383. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  97384. }
  97385. }
  97386. });
  97387. }
  97388. if (gamepad.rightStick) {
  97389. gamepad.onrightstickchanged(function (stickValues) {
  97390. if (_this._teleportationInitialized) {
  97391. _this._checkRotate(stickValues, _this._cameraGazer);
  97392. }
  97393. });
  97394. }
  97395. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  97396. gamepad.onbuttondown(function (buttonPressed) {
  97397. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97398. _this._cameraGazer._selectionPointerDown();
  97399. }
  97400. });
  97401. gamepad.onbuttonup(function (buttonPressed) {
  97402. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97403. _this._cameraGazer._selectionPointerUp();
  97404. }
  97405. });
  97406. }
  97407. }
  97408. else {
  97409. var webVRController = gamepad;
  97410. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  97411. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  97412. _this._rightController = controller;
  97413. }
  97414. else {
  97415. _this._leftController = controller;
  97416. }
  97417. _this._tryEnableInteractionOnController(controller);
  97418. }
  97419. };
  97420. // 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
  97421. this._tryEnableInteractionOnController = function (controller) {
  97422. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  97423. _this._enableInteractionOnController(controller);
  97424. }
  97425. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  97426. _this._enableTeleportationOnController(controller);
  97427. }
  97428. };
  97429. this._onNewGamepadDisconnected = function (gamepad) {
  97430. if (gamepad instanceof BABYLON.WebVRController) {
  97431. if (gamepad.hand === "left" && _this._leftController != null) {
  97432. _this._leftController.dispose();
  97433. _this._leftController = null;
  97434. }
  97435. if (gamepad.hand === "right" && _this._rightController != null) {
  97436. _this._rightController.dispose();
  97437. _this._rightController = null;
  97438. }
  97439. }
  97440. };
  97441. this._workingVector = BABYLON.Vector3.Zero();
  97442. this._workingQuaternion = BABYLON.Quaternion.Identity();
  97443. this._workingMatrix = BABYLON.Matrix.Identity();
  97444. this._scene = scene;
  97445. this._canvas = scene.getEngine().getRenderingCanvas();
  97446. // Parse options
  97447. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  97448. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  97449. }
  97450. if (webVROptions.createDeviceOrientationCamera === undefined) {
  97451. webVROptions.createDeviceOrientationCamera = true;
  97452. }
  97453. if (webVROptions.laserToggle === undefined) {
  97454. webVROptions.laserToggle = true;
  97455. }
  97456. if (webVROptions.defaultHeight === undefined) {
  97457. webVROptions.defaultHeight = 1.7;
  97458. }
  97459. if (webVROptions.useCustomVRButton) {
  97460. this._useCustomVRButton = true;
  97461. if (webVROptions.customVRButton) {
  97462. this._btnVR = webVROptions.customVRButton;
  97463. }
  97464. }
  97465. if (webVROptions.rayLength) {
  97466. this._rayLength = webVROptions.rayLength;
  97467. }
  97468. this._defaultHeight = webVROptions.defaultHeight;
  97469. if (webVROptions.positionScale) {
  97470. this._rayLength *= webVROptions.positionScale;
  97471. this._defaultHeight *= webVROptions.positionScale;
  97472. }
  97473. this._hasEnteredVR = false;
  97474. // Set position
  97475. if (this._scene.activeCamera) {
  97476. this._position = this._scene.activeCamera.position.clone();
  97477. }
  97478. else {
  97479. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  97480. }
  97481. // Set non-vr camera
  97482. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  97483. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  97484. // Copy data from existing camera
  97485. if (this._scene.activeCamera) {
  97486. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  97487. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  97488. // Set rotation from previous camera
  97489. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  97490. var targetCamera = this._scene.activeCamera;
  97491. if (targetCamera.rotationQuaternion) {
  97492. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  97493. }
  97494. else {
  97495. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  97496. }
  97497. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  97498. }
  97499. }
  97500. this._scene.activeCamera = this._deviceOrientationCamera;
  97501. if (this._canvas) {
  97502. this._scene.activeCamera.attachControl(this._canvas);
  97503. }
  97504. }
  97505. else {
  97506. this._existingCamera = this._scene.activeCamera;
  97507. }
  97508. // Create VR cameras
  97509. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  97510. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  97511. }
  97512. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  97513. this._webVRCamera.useStandingMatrix();
  97514. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  97515. // Create default button
  97516. if (!this._useCustomVRButton) {
  97517. this._btnVR = document.createElement("BUTTON");
  97518. this._btnVR.className = "babylonVRicon";
  97519. this._btnVR.id = "babylonVRiconbtn";
  97520. this._btnVR.title = "Click to switch to VR";
  97521. 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) }";
  97522. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  97523. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  97524. // css += ".babylonVRicon.vrdisplaysupported { }";
  97525. // css += ".babylonVRicon.vrdisplayready { }";
  97526. // css += ".babylonVRicon.vrdisplayrequesting { }";
  97527. var style = document.createElement('style');
  97528. style.appendChild(document.createTextNode(css));
  97529. document.getElementsByTagName('head')[0].appendChild(style);
  97530. this.moveButtonToBottomRight();
  97531. }
  97532. // VR button click event
  97533. if (this._btnVR) {
  97534. this._btnVR.addEventListener("click", function () {
  97535. if (!_this.isInVRMode) {
  97536. _this.enterVR();
  97537. }
  97538. else {
  97539. _this.exitVR();
  97540. }
  97541. });
  97542. }
  97543. // Window events
  97544. window.addEventListener("resize", this._onResize);
  97545. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  97546. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  97547. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  97548. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  97549. document.onmsfullscreenchange = this._onFullscreenChange;
  97550. // Display vr button when headset is connected
  97551. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  97552. this.displayVRButton();
  97553. }
  97554. else {
  97555. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  97556. if (e.vrDisplay) {
  97557. _this.displayVRButton();
  97558. }
  97559. });
  97560. }
  97561. // Exiting VR mode using 'ESC' key on desktop
  97562. this._onKeyDown = function (event) {
  97563. if (event.keyCode === 27 && _this.isInVRMode) {
  97564. _this.exitVR();
  97565. }
  97566. };
  97567. document.addEventListener("keydown", this._onKeyDown);
  97568. // Exiting VR mode double tapping the touch screen
  97569. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  97570. if (_this.isInVRMode) {
  97571. _this.exitVR();
  97572. if (_this._fullscreenVRpresenting) {
  97573. _this._scene.getEngine().switchFullscreen(true);
  97574. }
  97575. }
  97576. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  97577. // Listen for WebVR display changes
  97578. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  97579. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  97580. this._onVRRequestPresentStart = function () {
  97581. _this._webVRrequesting = true;
  97582. _this.updateButtonVisibility();
  97583. };
  97584. this._onVRRequestPresentComplete = function (success) {
  97585. _this._webVRrequesting = false;
  97586. _this.updateButtonVisibility();
  97587. };
  97588. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  97589. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  97590. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  97591. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97592. scene.onDisposeObservable.add(function () {
  97593. _this.dispose();
  97594. });
  97595. // Gamepad connection events
  97596. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  97597. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  97598. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  97599. this.updateButtonVisibility();
  97600. //create easing functions
  97601. this._circleEase = new BABYLON.CircleEase();
  97602. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  97603. if (this.webVROptions.floorMeshes) {
  97604. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  97605. }
  97606. }
  97607. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  97608. /** Return this.onEnteringVRObservable
  97609. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  97610. */
  97611. get: function () {
  97612. return this.onEnteringVRObservable;
  97613. },
  97614. enumerable: true,
  97615. configurable: true
  97616. });
  97617. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  97618. /** Return this.onExitingVRObservable
  97619. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  97620. */
  97621. get: function () {
  97622. return this.onExitingVRObservable;
  97623. },
  97624. enumerable: true,
  97625. configurable: true
  97626. });
  97627. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  97628. /** Return this.onControllerMeshLoadedObservable
  97629. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  97630. */
  97631. get: function () {
  97632. return this.onControllerMeshLoadedObservable;
  97633. },
  97634. enumerable: true,
  97635. configurable: true
  97636. });
  97637. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  97638. /**
  97639. * The mesh used to display where the user is going to teleport.
  97640. */
  97641. get: function () {
  97642. return this._teleportationTarget;
  97643. },
  97644. /**
  97645. * Sets the mesh to be used to display where the user is going to teleport.
  97646. */
  97647. set: function (value) {
  97648. if (value) {
  97649. value.name = "teleportationTarget";
  97650. this._isDefaultTeleportationTarget = false;
  97651. this._teleportationTarget = value;
  97652. }
  97653. },
  97654. enumerable: true,
  97655. configurable: true
  97656. });
  97657. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  97658. /**
  97659. * 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
  97660. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  97661. * See http://doc.babylonjs.com/resources/baking_transformations
  97662. */
  97663. get: function () {
  97664. return this._cameraGazer._gazeTracker;
  97665. },
  97666. set: function (value) {
  97667. if (value) {
  97668. // Dispose of existing meshes
  97669. if (this._cameraGazer._gazeTracker) {
  97670. this._cameraGazer._gazeTracker.dispose();
  97671. }
  97672. if (this._leftController && this._leftController._gazeTracker) {
  97673. this._leftController._gazeTracker.dispose();
  97674. }
  97675. if (this._rightController && this._rightController._gazeTracker) {
  97676. this._rightController._gazeTracker.dispose();
  97677. }
  97678. // Set and create gaze trackers on head and controllers
  97679. this._cameraGazer._gazeTracker = value;
  97680. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  97681. this._cameraGazer._gazeTracker.isPickable = false;
  97682. this._cameraGazer._gazeTracker.isVisible = false;
  97683. this._cameraGazer._gazeTracker.name = "gazeTracker";
  97684. if (this._leftController) {
  97685. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97686. }
  97687. if (this._rightController) {
  97688. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97689. }
  97690. }
  97691. },
  97692. enumerable: true,
  97693. configurable: true
  97694. });
  97695. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  97696. /**
  97697. * The gaze tracking mesh corresponding to the left controller
  97698. */
  97699. get: function () {
  97700. if (this._leftController) {
  97701. return this._leftController._gazeTracker;
  97702. }
  97703. return null;
  97704. },
  97705. enumerable: true,
  97706. configurable: true
  97707. });
  97708. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  97709. /**
  97710. * The gaze tracking mesh corresponding to the right controller
  97711. */
  97712. get: function () {
  97713. if (this._rightController) {
  97714. return this._rightController._gazeTracker;
  97715. }
  97716. return null;
  97717. },
  97718. enumerable: true,
  97719. configurable: true
  97720. });
  97721. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  97722. /**
  97723. * If the ray of the gaze should be displayed.
  97724. */
  97725. get: function () {
  97726. return this._displayGaze;
  97727. },
  97728. /**
  97729. * Sets if the ray of the gaze should be displayed.
  97730. */
  97731. set: function (value) {
  97732. this._displayGaze = value;
  97733. if (!value) {
  97734. this._cameraGazer._gazeTracker.isVisible = false;
  97735. if (this._leftController) {
  97736. this._leftController._gazeTracker.isVisible = false;
  97737. }
  97738. if (this._rightController) {
  97739. this._rightController._gazeTracker.isVisible = false;
  97740. }
  97741. }
  97742. },
  97743. enumerable: true,
  97744. configurable: true
  97745. });
  97746. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  97747. /**
  97748. * If the ray of the LaserPointer should be displayed.
  97749. */
  97750. get: function () {
  97751. return this._displayLaserPointer;
  97752. },
  97753. /**
  97754. * Sets if the ray of the LaserPointer should be displayed.
  97755. */
  97756. set: function (value) {
  97757. this._displayLaserPointer = value;
  97758. if (!value) {
  97759. if (this._rightController) {
  97760. this._rightController._deactivatePointer();
  97761. this._rightController._gazeTracker.isVisible = false;
  97762. }
  97763. if (this._leftController) {
  97764. this._leftController._deactivatePointer();
  97765. this._leftController._gazeTracker.isVisible = false;
  97766. }
  97767. }
  97768. else {
  97769. if (this._rightController) {
  97770. this._rightController._activatePointer();
  97771. }
  97772. if (this._leftController) {
  97773. this._leftController._activatePointer();
  97774. }
  97775. }
  97776. },
  97777. enumerable: true,
  97778. configurable: true
  97779. });
  97780. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  97781. /**
  97782. * The deviceOrientationCamera used as the camera when not in VR.
  97783. */
  97784. get: function () {
  97785. return this._deviceOrientationCamera;
  97786. },
  97787. enumerable: true,
  97788. configurable: true
  97789. });
  97790. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  97791. /**
  97792. * Based on the current WebVR support, returns the current VR camera used.
  97793. */
  97794. get: function () {
  97795. if (this._webVRready) {
  97796. return this._webVRCamera;
  97797. }
  97798. else {
  97799. return this._scene.activeCamera;
  97800. }
  97801. },
  97802. enumerable: true,
  97803. configurable: true
  97804. });
  97805. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  97806. /**
  97807. * The webVRCamera which is used when in VR.
  97808. */
  97809. get: function () {
  97810. return this._webVRCamera;
  97811. },
  97812. enumerable: true,
  97813. configurable: true
  97814. });
  97815. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  97816. /**
  97817. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  97818. */
  97819. get: function () {
  97820. return this._vrDeviceOrientationCamera;
  97821. },
  97822. enumerable: true,
  97823. configurable: true
  97824. });
  97825. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  97826. get: function () {
  97827. var result = this._cameraGazer._teleportationRequestInitiated
  97828. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  97829. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  97830. return result;
  97831. },
  97832. enumerable: true,
  97833. configurable: true
  97834. });
  97835. // Raised when one of the controller has loaded successfully its associated default mesh
  97836. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  97837. if (this._leftController && this._leftController.webVRController == webVRController) {
  97838. if (webVRController.mesh) {
  97839. this._leftController._setLaserPointerParent(webVRController.mesh);
  97840. }
  97841. }
  97842. if (this._rightController && this._rightController.webVRController == webVRController) {
  97843. if (webVRController.mesh) {
  97844. this._rightController._setLaserPointerParent(webVRController.mesh);
  97845. }
  97846. }
  97847. try {
  97848. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  97849. }
  97850. catch (err) {
  97851. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  97852. }
  97853. };
  97854. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  97855. /**
  97856. * Gets a value indicating if we are currently in VR mode.
  97857. */
  97858. get: function () {
  97859. return this._webVRpresenting || this._fullscreenVRpresenting;
  97860. },
  97861. enumerable: true,
  97862. configurable: true
  97863. });
  97864. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  97865. var vrDisplay = this._scene.getEngine().getVRDevice();
  97866. if (vrDisplay) {
  97867. var wasPresenting = this._webVRpresenting;
  97868. this._webVRpresenting = vrDisplay.isPresenting;
  97869. if (wasPresenting && !this._webVRpresenting)
  97870. this.exitVR();
  97871. }
  97872. else {
  97873. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  97874. }
  97875. this.updateButtonVisibility();
  97876. };
  97877. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  97878. this._webVRsupported = eventArgs.vrSupported;
  97879. this._webVRready = !!eventArgs.vrDisplay;
  97880. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  97881. this.updateButtonVisibility();
  97882. };
  97883. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  97884. if (this._canvas && !this._useCustomVRButton) {
  97885. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  97886. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  97887. }
  97888. };
  97889. VRExperienceHelper.prototype.displayVRButton = function () {
  97890. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  97891. document.body.appendChild(this._btnVR);
  97892. this._btnVRDisplayed = true;
  97893. }
  97894. };
  97895. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  97896. if (!this._btnVR || this._useCustomVRButton) {
  97897. return;
  97898. }
  97899. this._btnVR.className = "babylonVRicon";
  97900. if (this.isInVRMode) {
  97901. this._btnVR.className += " vrdisplaypresenting";
  97902. }
  97903. else {
  97904. if (this._webVRready)
  97905. this._btnVR.className += " vrdisplayready";
  97906. if (this._webVRsupported)
  97907. this._btnVR.className += " vrdisplaysupported";
  97908. if (this._webVRrequesting)
  97909. this._btnVR.className += " vrdisplayrequesting";
  97910. }
  97911. };
  97912. /**
  97913. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  97914. * Otherwise, will use the fullscreen API.
  97915. */
  97916. VRExperienceHelper.prototype.enterVR = function () {
  97917. if (this.onEnteringVRObservable) {
  97918. try {
  97919. this.onEnteringVRObservable.notifyObservers(this);
  97920. }
  97921. catch (err) {
  97922. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  97923. }
  97924. }
  97925. if (this._scene.activeCamera) {
  97926. this._position = this._scene.activeCamera.position.clone();
  97927. // make sure that we return to the last active camera
  97928. this._existingCamera = this._scene.activeCamera;
  97929. }
  97930. if (this._webVRrequesting)
  97931. return;
  97932. // If WebVR is supported and a headset is connected
  97933. if (this._webVRready) {
  97934. if (!this._webVRpresenting) {
  97935. this._webVRCamera.position = this._position;
  97936. this._scene.activeCamera = this._webVRCamera;
  97937. }
  97938. }
  97939. else if (this._vrDeviceOrientationCamera) {
  97940. this._vrDeviceOrientationCamera.position = this._position;
  97941. if (this._scene.activeCamera) {
  97942. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  97943. }
  97944. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  97945. this._scene.getEngine().switchFullscreen(true);
  97946. this.updateButtonVisibility();
  97947. }
  97948. if (this._scene.activeCamera && this._canvas) {
  97949. this._scene.activeCamera.attachControl(this._canvas);
  97950. }
  97951. if (this._interactionsEnabled) {
  97952. this._scene.registerBeforeRender(this.beforeRender);
  97953. }
  97954. this._hasEnteredVR = true;
  97955. };
  97956. /**
  97957. * Attempt to exit VR, or fullscreen.
  97958. */
  97959. VRExperienceHelper.prototype.exitVR = function () {
  97960. if (this._hasEnteredVR) {
  97961. if (this.onExitingVRObservable) {
  97962. try {
  97963. this.onExitingVRObservable.notifyObservers(this);
  97964. }
  97965. catch (err) {
  97966. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  97967. }
  97968. }
  97969. if (this._webVRpresenting) {
  97970. this._scene.getEngine().disableVR();
  97971. }
  97972. if (this._scene.activeCamera) {
  97973. this._position = this._scene.activeCamera.position.clone();
  97974. }
  97975. if (this._deviceOrientationCamera) {
  97976. this._deviceOrientationCamera.position = this._position;
  97977. this._scene.activeCamera = this._deviceOrientationCamera;
  97978. if (this._canvas) {
  97979. this._scene.activeCamera.attachControl(this._canvas);
  97980. }
  97981. }
  97982. else if (this._existingCamera) {
  97983. this._existingCamera.position = this._position;
  97984. this._scene.activeCamera = this._existingCamera;
  97985. }
  97986. this.updateButtonVisibility();
  97987. if (this._interactionsEnabled) {
  97988. this._scene.unregisterBeforeRender(this.beforeRender);
  97989. this._cameraGazer._gazeTracker.isVisible = false;
  97990. if (this._leftController) {
  97991. this._leftController._gazeTracker.isVisible = false;
  97992. }
  97993. if (this._rightController) {
  97994. this._rightController._gazeTracker.isVisible = false;
  97995. }
  97996. }
  97997. // resize to update width and height when exiting vr exits fullscreen
  97998. this._scene.getEngine().resize();
  97999. this._hasEnteredVR = false;
  98000. }
  98001. };
  98002. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  98003. /**
  98004. * The position of the vr experience helper.
  98005. */
  98006. get: function () {
  98007. return this._position;
  98008. },
  98009. /**
  98010. * Sets the position of the vr experience helper.
  98011. */
  98012. set: function (value) {
  98013. this._position = value;
  98014. if (this._scene.activeCamera) {
  98015. this._scene.activeCamera.position = value;
  98016. }
  98017. },
  98018. enumerable: true,
  98019. configurable: true
  98020. });
  98021. /**
  98022. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  98023. */
  98024. VRExperienceHelper.prototype.enableInteractions = function () {
  98025. var _this = this;
  98026. if (!this._interactionsEnabled) {
  98027. this._interactionsRequested = true;
  98028. if (this._leftController) {
  98029. this._enableInteractionOnController(this._leftController);
  98030. }
  98031. if (this._rightController) {
  98032. this._enableInteractionOnController(this._rightController);
  98033. }
  98034. this.raySelectionPredicate = function (mesh) {
  98035. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  98036. };
  98037. this.meshSelectionPredicate = function (mesh) {
  98038. return true;
  98039. };
  98040. this._raySelectionPredicate = function (mesh) {
  98041. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  98042. && mesh.name.indexOf("teleportationTarget") === -1
  98043. && mesh.name.indexOf("torusTeleportation") === -1)) {
  98044. return _this.raySelectionPredicate(mesh);
  98045. }
  98046. return false;
  98047. };
  98048. this._interactionsEnabled = true;
  98049. }
  98050. };
  98051. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  98052. get: function () {
  98053. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  98054. },
  98055. enumerable: true,
  98056. configurable: true
  98057. });
  98058. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  98059. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  98060. if (this._floorMeshesCollection[i].id === mesh.id) {
  98061. return true;
  98062. }
  98063. }
  98064. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  98065. return true;
  98066. }
  98067. return false;
  98068. };
  98069. /**
  98070. * Adds a floor mesh to be used for teleportation.
  98071. * @param floorMesh the mesh to be used for teleportation.
  98072. */
  98073. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  98074. if (!this._floorMeshesCollection) {
  98075. return;
  98076. }
  98077. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  98078. return;
  98079. }
  98080. this._floorMeshesCollection.push(floorMesh);
  98081. };
  98082. /**
  98083. * Removes a floor mesh from being used for teleportation.
  98084. * @param floorMesh the mesh to be removed.
  98085. */
  98086. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  98087. if (!this._floorMeshesCollection) {
  98088. return;
  98089. }
  98090. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  98091. if (meshIndex !== -1) {
  98092. this._floorMeshesCollection.splice(meshIndex, 1);
  98093. }
  98094. };
  98095. /**
  98096. * Enables interactions and teleportation using the VR controllers and gaze.
  98097. * @param vrTeleportationOptions options to modify teleportation behavior.
  98098. */
  98099. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  98100. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  98101. if (!this._teleportationInitialized) {
  98102. this._teleportationRequested = true;
  98103. this.enableInteractions();
  98104. if (vrTeleportationOptions.floorMeshName) {
  98105. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  98106. }
  98107. if (vrTeleportationOptions.floorMeshes) {
  98108. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  98109. }
  98110. if (this._leftController != null) {
  98111. this._enableTeleportationOnController(this._leftController);
  98112. }
  98113. if (this._rightController != null) {
  98114. this._enableTeleportationOnController(this._rightController);
  98115. }
  98116. // Creates an image processing post process for the vignette not relying
  98117. // on the main scene configuration for image processing to reduce setup and spaces
  98118. // (gamma/linear) conflicts.
  98119. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  98120. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  98121. imageProcessingConfiguration.vignetteEnabled = true;
  98122. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  98123. this._webVRCamera.detachPostProcess(this._postProcessMove);
  98124. this._teleportationInitialized = true;
  98125. if (this._isDefaultTeleportationTarget) {
  98126. this._createTeleportationCircles();
  98127. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  98128. }
  98129. }
  98130. };
  98131. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  98132. var _this = this;
  98133. var controllerMesh = controller.webVRController.mesh;
  98134. if (controllerMesh) {
  98135. controller._interactionsEnabled = true;
  98136. controller._activatePointer();
  98137. if (this.webVROptions.laserToggle) {
  98138. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  98139. // Enabling / disabling laserPointer
  98140. if (_this._displayLaserPointer && stateObject.value === 1) {
  98141. if (controller._activePointer) {
  98142. controller._deactivatePointer();
  98143. }
  98144. else {
  98145. controller._activatePointer();
  98146. }
  98147. if (_this.displayGaze) {
  98148. controller._gazeTracker.isVisible = controller._activePointer;
  98149. }
  98150. }
  98151. });
  98152. }
  98153. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  98154. var gazer = controller;
  98155. if (_this._noControllerIsActive) {
  98156. gazer = _this._cameraGazer;
  98157. }
  98158. if (!gazer._pointerDownOnMeshAsked) {
  98159. if (stateObject.value > _this._padSensibilityUp) {
  98160. gazer._selectionPointerDown();
  98161. }
  98162. }
  98163. else if (stateObject.value < _this._padSensibilityDown) {
  98164. gazer._selectionPointerUp();
  98165. }
  98166. });
  98167. }
  98168. };
  98169. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  98170. // Dont teleport if another gaze already requested teleportation
  98171. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  98172. return;
  98173. }
  98174. if (!gazer._teleportationRequestInitiated) {
  98175. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  98176. gazer._activatePointer();
  98177. gazer._teleportationRequestInitiated = true;
  98178. }
  98179. }
  98180. else {
  98181. // Listening to the proper controller values changes to confirm teleportation
  98182. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  98183. if (this._teleportActive) {
  98184. this.teleportCamera(this._haloCenter);
  98185. }
  98186. gazer._teleportationRequestInitiated = false;
  98187. }
  98188. }
  98189. };
  98190. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  98191. // Only rotate when user is not currently selecting a teleportation location
  98192. if (gazer._teleportationRequestInitiated) {
  98193. return;
  98194. }
  98195. if (!gazer._rotationLeftAsked) {
  98196. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  98197. gazer._rotationLeftAsked = true;
  98198. if (this._rotationAllowed) {
  98199. this._rotateCamera(false);
  98200. }
  98201. }
  98202. }
  98203. else {
  98204. if (stateObject.x > -this._padSensibilityDown) {
  98205. gazer._rotationLeftAsked = false;
  98206. }
  98207. }
  98208. if (!gazer._rotationRightAsked) {
  98209. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  98210. gazer._rotationRightAsked = true;
  98211. if (this._rotationAllowed) {
  98212. this._rotateCamera(true);
  98213. }
  98214. }
  98215. }
  98216. else {
  98217. if (stateObject.x < this._padSensibilityDown) {
  98218. gazer._rotationRightAsked = false;
  98219. }
  98220. }
  98221. };
  98222. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  98223. // Only teleport backwards when user is not currently selecting a teleportation location
  98224. if (gazer._teleportationRequestInitiated) {
  98225. return;
  98226. }
  98227. // Teleport backwards
  98228. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  98229. if (!gazer._teleportationBackRequestInitiated) {
  98230. if (!this.currentVRCamera) {
  98231. return;
  98232. }
  98233. // Get rotation and position of the current camera
  98234. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  98235. var position = this.currentVRCamera.position;
  98236. // If the camera has device position, use that instead
  98237. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  98238. rotation = this.currentVRCamera.deviceRotationQuaternion;
  98239. position = this.currentVRCamera.devicePosition;
  98240. }
  98241. // Get matrix with only the y rotation of the device rotation
  98242. rotation.toEulerAnglesToRef(this._workingVector);
  98243. this._workingVector.z = 0;
  98244. this._workingVector.x = 0;
  98245. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  98246. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  98247. // Rotate backwards ray by device rotation to cast at the ground behind the user
  98248. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  98249. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  98250. var ray = new BABYLON.Ray(position, this._workingVector);
  98251. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98252. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  98253. this.teleportCamera(hit.pickedPoint);
  98254. }
  98255. gazer._teleportationBackRequestInitiated = true;
  98256. }
  98257. }
  98258. else {
  98259. gazer._teleportationBackRequestInitiated = false;
  98260. }
  98261. };
  98262. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  98263. var _this = this;
  98264. var controllerMesh = controller.webVRController.mesh;
  98265. if (controllerMesh) {
  98266. if (!controller._interactionsEnabled) {
  98267. this._enableInteractionOnController(controller);
  98268. }
  98269. controller._interactionsEnabled = true;
  98270. controller._teleportationEnabled = true;
  98271. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  98272. controller._dpadPressed = false;
  98273. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  98274. controller._dpadPressed = stateObject.pressed;
  98275. if (!controller._dpadPressed) {
  98276. controller._rotationLeftAsked = false;
  98277. controller._rotationRightAsked = false;
  98278. controller._teleportationBackRequestInitiated = false;
  98279. }
  98280. });
  98281. }
  98282. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  98283. if (_this.teleportationEnabled) {
  98284. _this._checkTeleportBackwards(stateObject, controller);
  98285. _this._checkTeleportWithRay(stateObject, controller);
  98286. }
  98287. _this._checkRotate(stateObject, controller);
  98288. });
  98289. }
  98290. };
  98291. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  98292. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  98293. this._teleportationTarget.isPickable = false;
  98294. var length = 512;
  98295. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  98296. dynamicTexture.hasAlpha = true;
  98297. var context = dynamicTexture.getContext();
  98298. var centerX = length / 2;
  98299. var centerY = length / 2;
  98300. var radius = 200;
  98301. context.beginPath();
  98302. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  98303. context.fillStyle = this._teleportationFillColor;
  98304. context.fill();
  98305. context.lineWidth = 10;
  98306. context.strokeStyle = this._teleportationBorderColor;
  98307. context.stroke();
  98308. context.closePath();
  98309. dynamicTexture.update();
  98310. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  98311. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  98312. this._teleportationTarget.material = teleportationCircleMaterial;
  98313. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  98314. torus.isPickable = false;
  98315. torus.parent = this._teleportationTarget;
  98316. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  98317. var keys = [];
  98318. keys.push({
  98319. frame: 0,
  98320. value: 0
  98321. });
  98322. keys.push({
  98323. frame: 30,
  98324. value: 0.4
  98325. });
  98326. keys.push({
  98327. frame: 60,
  98328. value: 0
  98329. });
  98330. animationInnerCircle.setKeys(keys);
  98331. var easingFunction = new BABYLON.SineEase();
  98332. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98333. animationInnerCircle.setEasingFunction(easingFunction);
  98334. torus.animations = [];
  98335. torus.animations.push(animationInnerCircle);
  98336. this._scene.beginAnimation(torus, 0, 60, true);
  98337. this._hideTeleportationTarget();
  98338. };
  98339. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  98340. this._teleportActive = true;
  98341. if (this._teleportationInitialized) {
  98342. this._teleportationTarget.isVisible = true;
  98343. if (this._isDefaultTeleportationTarget) {
  98344. this._teleportationTarget.getChildren()[0].isVisible = true;
  98345. }
  98346. }
  98347. };
  98348. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  98349. this._teleportActive = false;
  98350. if (this._teleportationInitialized) {
  98351. this._teleportationTarget.isVisible = false;
  98352. if (this._isDefaultTeleportationTarget) {
  98353. this._teleportationTarget.getChildren()[0].isVisible = false;
  98354. }
  98355. }
  98356. };
  98357. VRExperienceHelper.prototype._rotateCamera = function (right) {
  98358. var _this = this;
  98359. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98360. return;
  98361. }
  98362. if (right) {
  98363. this._rotationAngle++;
  98364. }
  98365. else {
  98366. this._rotationAngle--;
  98367. }
  98368. this.currentVRCamera.animations = [];
  98369. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  98370. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98371. var animationRotationKeys = [];
  98372. animationRotationKeys.push({
  98373. frame: 0,
  98374. value: this.currentVRCamera.rotationQuaternion
  98375. });
  98376. animationRotationKeys.push({
  98377. frame: 6,
  98378. value: target
  98379. });
  98380. animationRotation.setKeys(animationRotationKeys);
  98381. animationRotation.setEasingFunction(this._circleEase);
  98382. this.currentVRCamera.animations.push(animationRotation);
  98383. this._postProcessMove.animations = [];
  98384. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98385. var vignetteWeightKeys = [];
  98386. vignetteWeightKeys.push({
  98387. frame: 0,
  98388. value: 0
  98389. });
  98390. vignetteWeightKeys.push({
  98391. frame: 3,
  98392. value: 4
  98393. });
  98394. vignetteWeightKeys.push({
  98395. frame: 6,
  98396. value: 0
  98397. });
  98398. animationPP.setKeys(vignetteWeightKeys);
  98399. animationPP.setEasingFunction(this._circleEase);
  98400. this._postProcessMove.animations.push(animationPP);
  98401. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98402. var vignetteStretchKeys = [];
  98403. vignetteStretchKeys.push({
  98404. frame: 0,
  98405. value: 0
  98406. });
  98407. vignetteStretchKeys.push({
  98408. frame: 3,
  98409. value: 10
  98410. });
  98411. vignetteStretchKeys.push({
  98412. frame: 6,
  98413. value: 0
  98414. });
  98415. animationPP2.setKeys(vignetteStretchKeys);
  98416. animationPP2.setEasingFunction(this._circleEase);
  98417. this._postProcessMove.animations.push(animationPP2);
  98418. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98419. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98420. this._postProcessMove.samples = 4;
  98421. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98422. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  98423. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98424. });
  98425. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  98426. };
  98427. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  98428. if (hit.pickedPoint) {
  98429. if (gazer._teleportationRequestInitiated) {
  98430. this._displayTeleportationTarget();
  98431. this._haloCenter.copyFrom(hit.pickedPoint);
  98432. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  98433. }
  98434. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  98435. if (pickNormal) {
  98436. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  98437. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  98438. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  98439. }
  98440. this._teleportationTarget.position.y += 0.1;
  98441. }
  98442. };
  98443. /**
  98444. * Teleports the users feet to the desired location
  98445. * @param location The location where the user's feet should be placed
  98446. */
  98447. VRExperienceHelper.prototype.teleportCamera = function (location) {
  98448. var _this = this;
  98449. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98450. return;
  98451. }
  98452. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  98453. // offset of the headset from the anchor.
  98454. if (this.webVRCamera.leftCamera) {
  98455. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  98456. this._workingVector.subtractInPlace(this.webVRCamera.position);
  98457. location.subtractToRef(this._workingVector, this._workingVector);
  98458. }
  98459. else {
  98460. this._workingVector.copyFrom(location);
  98461. }
  98462. // Add height to account for user's height offset
  98463. if (this.isInVRMode) {
  98464. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  98465. }
  98466. else {
  98467. this._workingVector.y += this._defaultHeight;
  98468. }
  98469. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  98470. // Create animation from the camera's position to the new location
  98471. this.currentVRCamera.animations = [];
  98472. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98473. var animationCameraTeleportationKeys = [{
  98474. frame: 0,
  98475. value: this.currentVRCamera.position
  98476. },
  98477. {
  98478. frame: 11,
  98479. value: this._workingVector
  98480. }
  98481. ];
  98482. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  98483. animationCameraTeleportation.setEasingFunction(this._circleEase);
  98484. this.currentVRCamera.animations.push(animationCameraTeleportation);
  98485. this._postProcessMove.animations = [];
  98486. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98487. var vignetteWeightKeys = [];
  98488. vignetteWeightKeys.push({
  98489. frame: 0,
  98490. value: 0
  98491. });
  98492. vignetteWeightKeys.push({
  98493. frame: 5,
  98494. value: 8
  98495. });
  98496. vignetteWeightKeys.push({
  98497. frame: 11,
  98498. value: 0
  98499. });
  98500. animationPP.setKeys(vignetteWeightKeys);
  98501. this._postProcessMove.animations.push(animationPP);
  98502. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98503. var vignetteStretchKeys = [];
  98504. vignetteStretchKeys.push({
  98505. frame: 0,
  98506. value: 0
  98507. });
  98508. vignetteStretchKeys.push({
  98509. frame: 5,
  98510. value: 10
  98511. });
  98512. vignetteStretchKeys.push({
  98513. frame: 11,
  98514. value: 0
  98515. });
  98516. animationPP2.setKeys(vignetteStretchKeys);
  98517. this._postProcessMove.animations.push(animationPP2);
  98518. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98519. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98520. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98521. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  98522. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98523. });
  98524. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  98525. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  98526. });
  98527. this._hideTeleportationTarget();
  98528. };
  98529. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  98530. if (normal) {
  98531. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  98532. if (angle < Math.PI / 2) {
  98533. normal.scaleInPlace(-1);
  98534. }
  98535. }
  98536. return normal;
  98537. };
  98538. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  98539. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98540. return;
  98541. }
  98542. var ray = gazer._getForwardRay(this._rayLength);
  98543. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98544. if (hit) {
  98545. // Populate the contrllers mesh that can be used for drag/drop
  98546. if (gazer._laserPointer) {
  98547. hit.originMesh = gazer._laserPointer.parent;
  98548. }
  98549. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  98550. }
  98551. gazer._currentHit = hit;
  98552. // Moving the gazeTracker on the mesh face targetted
  98553. if (hit && hit.pickedPoint) {
  98554. if (this._displayGaze) {
  98555. var multiplier = 1;
  98556. gazer._gazeTracker.isVisible = true;
  98557. if (gazer._isActionableMesh) {
  98558. multiplier = 3;
  98559. }
  98560. if (this.updateGazeTrackerScale) {
  98561. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  98562. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  98563. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  98564. }
  98565. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  98566. // To avoid z-fighting
  98567. var deltaFighting = 0.002;
  98568. if (pickNormal) {
  98569. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  98570. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  98571. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  98572. }
  98573. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  98574. if (gazer._gazeTracker.position.x < 0) {
  98575. gazer._gazeTracker.position.x += deltaFighting;
  98576. }
  98577. else {
  98578. gazer._gazeTracker.position.x -= deltaFighting;
  98579. }
  98580. if (gazer._gazeTracker.position.y < 0) {
  98581. gazer._gazeTracker.position.y += deltaFighting;
  98582. }
  98583. else {
  98584. gazer._gazeTracker.position.y -= deltaFighting;
  98585. }
  98586. if (gazer._gazeTracker.position.z < 0) {
  98587. gazer._gazeTracker.position.z += deltaFighting;
  98588. }
  98589. else {
  98590. gazer._gazeTracker.position.z -= deltaFighting;
  98591. }
  98592. }
  98593. // Changing the size of the laser pointer based on the distance from the targetted point
  98594. gazer._updatePointerDistance(hit.distance);
  98595. }
  98596. else {
  98597. gazer._updatePointerDistance();
  98598. gazer._gazeTracker.isVisible = false;
  98599. }
  98600. if (hit && hit.pickedMesh) {
  98601. // The object selected is the floor, we're in a teleportation scenario
  98602. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  98603. // Moving the teleportation area to this targetted point
  98604. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  98605. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  98606. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98607. }
  98608. gazer._currentMeshSelected = null;
  98609. if (gazer._teleportationRequestInitiated) {
  98610. this._moveTeleportationSelectorTo(hit, gazer, ray);
  98611. }
  98612. return;
  98613. }
  98614. // If not, we're in a selection scenario
  98615. //this._teleportationAllowed = false;
  98616. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  98617. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  98618. this.onNewMeshPicked.notifyObservers(hit);
  98619. gazer._currentMeshSelected = hit.pickedMesh;
  98620. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  98621. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  98622. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  98623. gazer._isActionableMesh = true;
  98624. }
  98625. else {
  98626. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98627. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98628. gazer._isActionableMesh = false;
  98629. }
  98630. try {
  98631. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  98632. }
  98633. catch (err) {
  98634. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  98635. }
  98636. }
  98637. else {
  98638. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98639. gazer._currentMeshSelected = null;
  98640. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98641. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98642. }
  98643. }
  98644. }
  98645. else {
  98646. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98647. gazer._currentMeshSelected = null;
  98648. //this._teleportationAllowed = false;
  98649. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98650. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98651. }
  98652. };
  98653. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  98654. if (mesh) {
  98655. this.onSelectedMeshUnselected.notifyObservers(mesh);
  98656. }
  98657. };
  98658. /**
  98659. * Sets the color of the laser ray from the vr controllers.
  98660. * @param color new color for the ray.
  98661. */
  98662. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  98663. if (this._leftController) {
  98664. this._leftController._setLaserPointerColor(color);
  98665. }
  98666. if (this._rightController) {
  98667. this._rightController._setLaserPointerColor(color);
  98668. }
  98669. };
  98670. /**
  98671. * Sets the color of the ray from the vr headsets gaze.
  98672. * @param color new color for the ray.
  98673. */
  98674. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  98675. if (!this._cameraGazer._gazeTracker.material) {
  98676. return;
  98677. }
  98678. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  98679. if (this._leftController) {
  98680. this._leftController._gazeTracker.material.emissiveColor = color;
  98681. }
  98682. if (this._rightController) {
  98683. this._rightController._gazeTracker.material.emissiveColor = color;
  98684. }
  98685. };
  98686. /**
  98687. * Exits VR and disposes of the vr experience helper
  98688. */
  98689. VRExperienceHelper.prototype.dispose = function () {
  98690. if (this.isInVRMode) {
  98691. this.exitVR();
  98692. }
  98693. if (this._postProcessMove) {
  98694. this._postProcessMove.dispose();
  98695. }
  98696. if (this._webVRCamera) {
  98697. this._webVRCamera.dispose();
  98698. }
  98699. if (this._vrDeviceOrientationCamera) {
  98700. this._vrDeviceOrientationCamera.dispose();
  98701. }
  98702. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  98703. document.body.removeChild(this._btnVR);
  98704. }
  98705. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  98706. this._deviceOrientationCamera.dispose();
  98707. }
  98708. if (this._cameraGazer) {
  98709. this._cameraGazer.dispose();
  98710. }
  98711. if (this._leftController) {
  98712. this._leftController.dispose();
  98713. }
  98714. if (this._rightController) {
  98715. this._rightController.dispose();
  98716. }
  98717. if (this._teleportationTarget) {
  98718. this._teleportationTarget.dispose();
  98719. }
  98720. this._floorMeshesCollection = [];
  98721. document.removeEventListener("keydown", this._onKeyDown);
  98722. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98723. window.removeEventListener("resize", this._onResize);
  98724. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  98725. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  98726. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  98727. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  98728. document.onmsfullscreenchange = null;
  98729. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  98730. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  98731. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  98732. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98733. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  98734. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  98735. this._scene.unregisterBeforeRender(this.beforeRender);
  98736. };
  98737. /**
  98738. * Gets the name of the VRExperienceHelper class
  98739. * @returns "VRExperienceHelper"
  98740. */
  98741. VRExperienceHelper.prototype.getClassName = function () {
  98742. return "VRExperienceHelper";
  98743. };
  98744. return VRExperienceHelper;
  98745. }());
  98746. BABYLON.VRExperienceHelper = VRExperienceHelper;
  98747. })(BABYLON || (BABYLON = {}));
  98748. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  98749. // Mainly based on these 2 articles :
  98750. // 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
  98751. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  98752. var BABYLON;
  98753. (function (BABYLON) {
  98754. /**
  98755. * Defines the potential axis of a Joystick
  98756. */
  98757. var JoystickAxis;
  98758. (function (JoystickAxis) {
  98759. /** X axis */
  98760. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  98761. /** Y axis */
  98762. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  98763. /** Z axis */
  98764. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  98765. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  98766. /**
  98767. * Class used to define virtual joystick (used in touch mode)
  98768. */
  98769. var VirtualJoystick = /** @class */ (function () {
  98770. /**
  98771. * Creates a new virtual joystick
  98772. * @param leftJoystick defines that the joystick is for left hand (false by default)
  98773. */
  98774. function VirtualJoystick(leftJoystick) {
  98775. var _this = this;
  98776. if (leftJoystick) {
  98777. this._leftJoystick = true;
  98778. }
  98779. else {
  98780. this._leftJoystick = false;
  98781. }
  98782. VirtualJoystick._globalJoystickIndex++;
  98783. // By default left & right arrow keys are moving the X
  98784. // and up & down keys are moving the Y
  98785. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  98786. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  98787. this.reverseLeftRight = false;
  98788. this.reverseUpDown = false;
  98789. // collections of pointers
  98790. this._touches = new BABYLON.StringDictionary();
  98791. this.deltaPosition = BABYLON.Vector3.Zero();
  98792. this._joystickSensibility = 25;
  98793. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98794. this._onResize = function (evt) {
  98795. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98796. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98797. if (VirtualJoystick.vjCanvas) {
  98798. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  98799. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  98800. }
  98801. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  98802. };
  98803. // injecting a canvas element on top of the canvas 3D game
  98804. if (!VirtualJoystick.vjCanvas) {
  98805. window.addEventListener("resize", this._onResize, false);
  98806. VirtualJoystick.vjCanvas = document.createElement("canvas");
  98807. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98808. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98809. VirtualJoystick.vjCanvas.width = window.innerWidth;
  98810. VirtualJoystick.vjCanvas.height = window.innerHeight;
  98811. VirtualJoystick.vjCanvas.style.width = "100%";
  98812. VirtualJoystick.vjCanvas.style.height = "100%";
  98813. VirtualJoystick.vjCanvas.style.position = "absolute";
  98814. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  98815. VirtualJoystick.vjCanvas.style.top = "0px";
  98816. VirtualJoystick.vjCanvas.style.left = "0px";
  98817. VirtualJoystick.vjCanvas.style.zIndex = "5";
  98818. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  98819. // Support for jQuery PEP polyfill
  98820. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  98821. var context = VirtualJoystick.vjCanvas.getContext('2d');
  98822. if (!context) {
  98823. throw new Error("Unable to create canvas for virtual joystick");
  98824. }
  98825. VirtualJoystick.vjCanvasContext = context;
  98826. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  98827. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  98828. document.body.appendChild(VirtualJoystick.vjCanvas);
  98829. }
  98830. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  98831. this.pressed = false;
  98832. // default joystick color
  98833. this._joystickColor = "cyan";
  98834. this._joystickPointerID = -1;
  98835. // current joystick position
  98836. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  98837. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  98838. // origin joystick position
  98839. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  98840. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  98841. this._onPointerDownHandlerRef = function (evt) {
  98842. _this._onPointerDown(evt);
  98843. };
  98844. this._onPointerMoveHandlerRef = function (evt) {
  98845. _this._onPointerMove(evt);
  98846. };
  98847. this._onPointerUpHandlerRef = function (evt) {
  98848. _this._onPointerUp(evt);
  98849. };
  98850. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  98851. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  98852. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  98853. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  98854. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  98855. evt.preventDefault(); // Disables system menu
  98856. }, false);
  98857. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  98858. }
  98859. /**
  98860. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  98861. * @param newJoystickSensibility defines the new sensibility
  98862. */
  98863. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  98864. this._joystickSensibility = newJoystickSensibility;
  98865. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98866. };
  98867. VirtualJoystick.prototype._onPointerDown = function (e) {
  98868. var positionOnScreenCondition;
  98869. e.preventDefault();
  98870. if (this._leftJoystick === true) {
  98871. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  98872. }
  98873. else {
  98874. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  98875. }
  98876. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  98877. // First contact will be dedicated to the virtual joystick
  98878. this._joystickPointerID = e.pointerId;
  98879. this._joystickPointerStartPos.x = e.clientX;
  98880. this._joystickPointerStartPos.y = e.clientY;
  98881. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  98882. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  98883. this._deltaJoystickVector.x = 0;
  98884. this._deltaJoystickVector.y = 0;
  98885. this.pressed = true;
  98886. this._touches.add(e.pointerId.toString(), e);
  98887. }
  98888. else {
  98889. // You can only trigger the action buttons with a joystick declared
  98890. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  98891. this._action();
  98892. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  98893. }
  98894. }
  98895. };
  98896. VirtualJoystick.prototype._onPointerMove = function (e) {
  98897. // If the current pointer is the one associated to the joystick (first touch contact)
  98898. if (this._joystickPointerID == e.pointerId) {
  98899. this._joystickPointerPos.x = e.clientX;
  98900. this._joystickPointerPos.y = e.clientY;
  98901. this._deltaJoystickVector = this._joystickPointerPos.clone();
  98902. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  98903. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  98904. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  98905. switch (this._axisTargetedByLeftAndRight) {
  98906. case JoystickAxis.X:
  98907. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  98908. break;
  98909. case JoystickAxis.Y:
  98910. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  98911. break;
  98912. case JoystickAxis.Z:
  98913. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  98914. break;
  98915. }
  98916. var directionUpDown = this.reverseUpDown ? 1 : -1;
  98917. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  98918. switch (this._axisTargetedByUpAndDown) {
  98919. case JoystickAxis.X:
  98920. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  98921. break;
  98922. case JoystickAxis.Y:
  98923. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  98924. break;
  98925. case JoystickAxis.Z:
  98926. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  98927. break;
  98928. }
  98929. }
  98930. else {
  98931. var data = this._touches.get(e.pointerId.toString());
  98932. if (data) {
  98933. data.x = e.clientX;
  98934. data.y = e.clientY;
  98935. }
  98936. }
  98937. };
  98938. VirtualJoystick.prototype._onPointerUp = function (e) {
  98939. if (this._joystickPointerID == e.pointerId) {
  98940. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  98941. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  98942. this._joystickPointerID = -1;
  98943. this.pressed = false;
  98944. }
  98945. else {
  98946. var touch = this._touches.get(e.pointerId.toString());
  98947. if (touch) {
  98948. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  98949. }
  98950. }
  98951. this._deltaJoystickVector.x = 0;
  98952. this._deltaJoystickVector.y = 0;
  98953. this._touches.remove(e.pointerId.toString());
  98954. };
  98955. /**
  98956. * Change the color of the virtual joystick
  98957. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  98958. */
  98959. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  98960. this._joystickColor = newColor;
  98961. };
  98962. /**
  98963. * Defines a callback to call when the joystick is touched
  98964. * @param action defines the callback
  98965. */
  98966. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  98967. this._action = action;
  98968. };
  98969. /**
  98970. * Defines which axis you'd like to control for left & right
  98971. * @param axis defines the axis to use
  98972. */
  98973. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  98974. switch (axis) {
  98975. case JoystickAxis.X:
  98976. case JoystickAxis.Y:
  98977. case JoystickAxis.Z:
  98978. this._axisTargetedByLeftAndRight = axis;
  98979. break;
  98980. default:
  98981. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  98982. break;
  98983. }
  98984. };
  98985. /**
  98986. * Defines which axis you'd like to control for up & down
  98987. * @param axis defines the axis to use
  98988. */
  98989. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  98990. switch (axis) {
  98991. case JoystickAxis.X:
  98992. case JoystickAxis.Y:
  98993. case JoystickAxis.Z:
  98994. this._axisTargetedByUpAndDown = axis;
  98995. break;
  98996. default:
  98997. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  98998. break;
  98999. }
  99000. };
  99001. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  99002. var _this = this;
  99003. if (this.pressed) {
  99004. this._touches.forEach(function (key, touch) {
  99005. if (touch.pointerId === _this._joystickPointerID) {
  99006. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  99007. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  99008. VirtualJoystick.vjCanvasContext.beginPath();
  99009. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99010. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99011. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  99012. VirtualJoystick.vjCanvasContext.stroke();
  99013. VirtualJoystick.vjCanvasContext.closePath();
  99014. VirtualJoystick.vjCanvasContext.beginPath();
  99015. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99016. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99017. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  99018. VirtualJoystick.vjCanvasContext.stroke();
  99019. VirtualJoystick.vjCanvasContext.closePath();
  99020. VirtualJoystick.vjCanvasContext.beginPath();
  99021. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99022. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  99023. VirtualJoystick.vjCanvasContext.stroke();
  99024. VirtualJoystick.vjCanvasContext.closePath();
  99025. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  99026. }
  99027. else {
  99028. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99029. VirtualJoystick.vjCanvasContext.beginPath();
  99030. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  99031. VirtualJoystick.vjCanvasContext.beginPath();
  99032. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  99033. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99034. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  99035. VirtualJoystick.vjCanvasContext.stroke();
  99036. VirtualJoystick.vjCanvasContext.closePath();
  99037. touch.prevX = touch.x;
  99038. touch.prevY = touch.y;
  99039. }
  99040. ;
  99041. });
  99042. }
  99043. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99044. };
  99045. /**
  99046. * Release internal HTML canvas
  99047. */
  99048. VirtualJoystick.prototype.releaseCanvas = function () {
  99049. if (VirtualJoystick.vjCanvas) {
  99050. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  99051. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  99052. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  99053. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  99054. window.removeEventListener("resize", this._onResize);
  99055. document.body.removeChild(VirtualJoystick.vjCanvas);
  99056. VirtualJoystick.vjCanvas = null;
  99057. }
  99058. };
  99059. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  99060. VirtualJoystick._globalJoystickIndex = 0;
  99061. return VirtualJoystick;
  99062. }());
  99063. BABYLON.VirtualJoystick = VirtualJoystick;
  99064. })(BABYLON || (BABYLON = {}));
  99065. //# sourceMappingURL=babylon.virtualJoystick.js.map
  99066. var BABYLON;
  99067. (function (BABYLON) {
  99068. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  99069. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  99070. });
  99071. // We're mainly based on the logic defined into the FreeCamera code
  99072. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  99073. __extends(VirtualJoysticksCamera, _super);
  99074. function VirtualJoysticksCamera(name, position, scene) {
  99075. var _this = _super.call(this, name, position, scene) || this;
  99076. _this.inputs.addVirtualJoystick();
  99077. return _this;
  99078. }
  99079. VirtualJoysticksCamera.prototype.getClassName = function () {
  99080. return "VirtualJoysticksCamera";
  99081. };
  99082. return VirtualJoysticksCamera;
  99083. }(BABYLON.FreeCamera));
  99084. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  99085. })(BABYLON || (BABYLON = {}));
  99086. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  99087. var BABYLON;
  99088. (function (BABYLON) {
  99089. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  99090. function FreeCameraVirtualJoystickInput() {
  99091. }
  99092. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  99093. return this._leftjoystick;
  99094. };
  99095. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  99096. return this._rightjoystick;
  99097. };
  99098. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  99099. if (this._leftjoystick) {
  99100. var camera = this.camera;
  99101. var speed = camera._computeLocalCameraSpeed() * 50;
  99102. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  99103. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  99104. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  99105. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  99106. if (!this._leftjoystick.pressed) {
  99107. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  99108. }
  99109. if (!this._rightjoystick.pressed) {
  99110. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  99111. }
  99112. }
  99113. };
  99114. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  99115. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  99116. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  99117. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  99118. this._leftjoystick.setJoystickSensibility(0.15);
  99119. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  99120. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  99121. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  99122. this._rightjoystick.reverseUpDown = true;
  99123. this._rightjoystick.setJoystickSensibility(0.05);
  99124. this._rightjoystick.setJoystickColor("yellow");
  99125. };
  99126. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  99127. this._leftjoystick.releaseCanvas();
  99128. this._rightjoystick.releaseCanvas();
  99129. };
  99130. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  99131. return "FreeCameraVirtualJoystickInput";
  99132. };
  99133. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  99134. return "virtualJoystick";
  99135. };
  99136. return FreeCameraVirtualJoystickInput;
  99137. }());
  99138. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  99139. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  99140. })(BABYLON || (BABYLON = {}));
  99141. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  99142. var BABYLON;
  99143. (function (BABYLON) {
  99144. var SimplificationSettings = /** @class */ (function () {
  99145. function SimplificationSettings(quality, distance, optimizeMesh) {
  99146. this.quality = quality;
  99147. this.distance = distance;
  99148. this.optimizeMesh = optimizeMesh;
  99149. }
  99150. return SimplificationSettings;
  99151. }());
  99152. BABYLON.SimplificationSettings = SimplificationSettings;
  99153. var SimplificationQueue = /** @class */ (function () {
  99154. function SimplificationQueue() {
  99155. this.running = false;
  99156. this._simplificationArray = [];
  99157. }
  99158. SimplificationQueue.prototype.addTask = function (task) {
  99159. this._simplificationArray.push(task);
  99160. };
  99161. SimplificationQueue.prototype.executeNext = function () {
  99162. var task = this._simplificationArray.pop();
  99163. if (task) {
  99164. this.running = true;
  99165. this.runSimplification(task);
  99166. }
  99167. else {
  99168. this.running = false;
  99169. }
  99170. };
  99171. SimplificationQueue.prototype.runSimplification = function (task) {
  99172. var _this = this;
  99173. if (task.parallelProcessing) {
  99174. //parallel simplifier
  99175. task.settings.forEach(function (setting) {
  99176. var simplifier = _this.getSimplifier(task);
  99177. simplifier.simplify(setting, function (newMesh) {
  99178. task.mesh.addLODLevel(setting.distance, newMesh);
  99179. newMesh.isVisible = true;
  99180. //check if it is the last
  99181. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  99182. //all done, run the success callback.
  99183. task.successCallback();
  99184. }
  99185. _this.executeNext();
  99186. });
  99187. });
  99188. }
  99189. else {
  99190. //single simplifier.
  99191. var simplifier = this.getSimplifier(task);
  99192. var runDecimation = function (setting, callback) {
  99193. simplifier.simplify(setting, function (newMesh) {
  99194. task.mesh.addLODLevel(setting.distance, newMesh);
  99195. newMesh.isVisible = true;
  99196. //run the next quality level
  99197. callback();
  99198. });
  99199. };
  99200. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  99201. runDecimation(task.settings[loop.index], function () {
  99202. loop.executeNext();
  99203. });
  99204. }, function () {
  99205. //execution ended, run the success callback.
  99206. if (task.successCallback) {
  99207. task.successCallback();
  99208. }
  99209. _this.executeNext();
  99210. });
  99211. }
  99212. };
  99213. SimplificationQueue.prototype.getSimplifier = function (task) {
  99214. switch (task.simplificationType) {
  99215. case SimplificationType.QUADRATIC:
  99216. default:
  99217. return new QuadraticErrorSimplification(task.mesh);
  99218. }
  99219. };
  99220. return SimplificationQueue;
  99221. }());
  99222. BABYLON.SimplificationQueue = SimplificationQueue;
  99223. /**
  99224. * The implemented types of simplification
  99225. * At the moment only Quadratic Error Decimation is implemented
  99226. */
  99227. var SimplificationType;
  99228. (function (SimplificationType) {
  99229. /** Quadratic error decimation */
  99230. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  99231. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  99232. var DecimationTriangle = /** @class */ (function () {
  99233. function DecimationTriangle(vertices) {
  99234. this.vertices = vertices;
  99235. this.error = new Array(4);
  99236. this.deleted = false;
  99237. this.isDirty = false;
  99238. this.deletePending = false;
  99239. this.borderFactor = 0;
  99240. }
  99241. return DecimationTriangle;
  99242. }());
  99243. BABYLON.DecimationTriangle = DecimationTriangle;
  99244. var DecimationVertex = /** @class */ (function () {
  99245. function DecimationVertex(position, id) {
  99246. this.position = position;
  99247. this.id = id;
  99248. this.isBorder = true;
  99249. this.q = new QuadraticMatrix();
  99250. this.triangleCount = 0;
  99251. this.triangleStart = 0;
  99252. this.originalOffsets = [];
  99253. }
  99254. DecimationVertex.prototype.updatePosition = function (newPosition) {
  99255. this.position.copyFrom(newPosition);
  99256. };
  99257. return DecimationVertex;
  99258. }());
  99259. BABYLON.DecimationVertex = DecimationVertex;
  99260. var QuadraticMatrix = /** @class */ (function () {
  99261. function QuadraticMatrix(data) {
  99262. this.data = new Array(10);
  99263. for (var i = 0; i < 10; ++i) {
  99264. if (data && data[i]) {
  99265. this.data[i] = data[i];
  99266. }
  99267. else {
  99268. this.data[i] = 0;
  99269. }
  99270. }
  99271. }
  99272. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  99273. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  99274. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  99275. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  99276. return det;
  99277. };
  99278. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  99279. for (var i = 0; i < 10; ++i) {
  99280. this.data[i] += matrix.data[i];
  99281. }
  99282. };
  99283. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  99284. for (var i = 0; i < 10; ++i) {
  99285. this.data[i] += data[i];
  99286. }
  99287. };
  99288. QuadraticMatrix.prototype.add = function (matrix) {
  99289. var m = new QuadraticMatrix();
  99290. for (var i = 0; i < 10; ++i) {
  99291. m.data[i] = this.data[i] + matrix.data[i];
  99292. }
  99293. return m;
  99294. };
  99295. QuadraticMatrix.FromData = function (a, b, c, d) {
  99296. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  99297. };
  99298. //returning an array to avoid garbage collection
  99299. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  99300. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  99301. };
  99302. return QuadraticMatrix;
  99303. }());
  99304. BABYLON.QuadraticMatrix = QuadraticMatrix;
  99305. var Reference = /** @class */ (function () {
  99306. function Reference(vertexId, triangleId) {
  99307. this.vertexId = vertexId;
  99308. this.triangleId = triangleId;
  99309. }
  99310. return Reference;
  99311. }());
  99312. BABYLON.Reference = Reference;
  99313. /**
  99314. * An implementation of the Quadratic Error simplification algorithm.
  99315. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  99316. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  99317. * @author RaananW
  99318. */
  99319. var QuadraticErrorSimplification = /** @class */ (function () {
  99320. function QuadraticErrorSimplification(_mesh) {
  99321. this._mesh = _mesh;
  99322. this.syncIterations = 5000;
  99323. this.aggressiveness = 7;
  99324. this.decimationIterations = 100;
  99325. this.boundingBoxEpsilon = BABYLON.Epsilon;
  99326. }
  99327. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  99328. var _this = this;
  99329. this.initDecimatedMesh();
  99330. //iterating through the submeshes array, one after the other.
  99331. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  99332. _this.initWithMesh(loop.index, function () {
  99333. _this.runDecimation(settings, loop.index, function () {
  99334. loop.executeNext();
  99335. });
  99336. }, settings.optimizeMesh);
  99337. }, function () {
  99338. setTimeout(function () {
  99339. successCallback(_this._reconstructedMesh);
  99340. }, 0);
  99341. });
  99342. };
  99343. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  99344. var _this = this;
  99345. var targetCount = ~~(this.triangles.length * settings.quality);
  99346. var deletedTriangles = 0;
  99347. var triangleCount = this.triangles.length;
  99348. var iterationFunction = function (iteration, callback) {
  99349. setTimeout(function () {
  99350. if (iteration % 5 === 0) {
  99351. _this.updateMesh(iteration === 0);
  99352. }
  99353. for (var i = 0; i < _this.triangles.length; ++i) {
  99354. _this.triangles[i].isDirty = false;
  99355. }
  99356. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  99357. var trianglesIterator = function (i) {
  99358. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  99359. var t = _this.triangles[tIdx];
  99360. if (!t)
  99361. return;
  99362. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  99363. return;
  99364. }
  99365. for (var j = 0; j < 3; ++j) {
  99366. if (t.error[j] < threshold) {
  99367. var deleted0 = [];
  99368. var deleted1 = [];
  99369. var v0 = t.vertices[j];
  99370. var v1 = t.vertices[(j + 1) % 3];
  99371. if (v0.isBorder || v1.isBorder)
  99372. continue;
  99373. var p = BABYLON.Vector3.Zero();
  99374. var n = BABYLON.Vector3.Zero();
  99375. var uv = BABYLON.Vector2.Zero();
  99376. var color = new BABYLON.Color4(0, 0, 0, 1);
  99377. _this.calculateError(v0, v1, p, n, uv, color);
  99378. var delTr = new Array();
  99379. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  99380. continue;
  99381. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  99382. continue;
  99383. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  99384. continue;
  99385. var uniqueArray = new Array();
  99386. delTr.forEach(function (deletedT) {
  99387. if (uniqueArray.indexOf(deletedT) === -1) {
  99388. deletedT.deletePending = true;
  99389. uniqueArray.push(deletedT);
  99390. }
  99391. });
  99392. if (uniqueArray.length % 2 !== 0) {
  99393. continue;
  99394. }
  99395. v0.q = v1.q.add(v0.q);
  99396. v0.updatePosition(p);
  99397. var tStart = _this.references.length;
  99398. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  99399. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  99400. var tCount = _this.references.length - tStart;
  99401. if (tCount <= v0.triangleCount) {
  99402. if (tCount) {
  99403. for (var c = 0; c < tCount; c++) {
  99404. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  99405. }
  99406. }
  99407. }
  99408. else {
  99409. v0.triangleStart = tStart;
  99410. }
  99411. v0.triangleCount = tCount;
  99412. break;
  99413. }
  99414. }
  99415. };
  99416. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  99417. }, 0);
  99418. };
  99419. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  99420. if (triangleCount - deletedTriangles <= targetCount)
  99421. loop.breakLoop();
  99422. else {
  99423. iterationFunction(loop.index, function () {
  99424. loop.executeNext();
  99425. });
  99426. }
  99427. }, function () {
  99428. setTimeout(function () {
  99429. //reconstruct this part of the mesh
  99430. _this.reconstructMesh(submeshIndex);
  99431. successCallback();
  99432. }, 0);
  99433. });
  99434. };
  99435. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  99436. var _this = this;
  99437. this.vertices = [];
  99438. this.triangles = [];
  99439. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99440. var indices = this._mesh.getIndices();
  99441. var submesh = this._mesh.subMeshes[submeshIndex];
  99442. var findInVertices = function (positionToSearch) {
  99443. if (optimizeMesh) {
  99444. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  99445. if (_this.vertices[ii].position.equals(positionToSearch)) {
  99446. return _this.vertices[ii];
  99447. }
  99448. }
  99449. }
  99450. return null;
  99451. };
  99452. var vertexReferences = [];
  99453. var vertexInit = function (i) {
  99454. if (!positionData) {
  99455. return;
  99456. }
  99457. var offset = i + submesh.verticesStart;
  99458. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  99459. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  99460. vertex.originalOffsets.push(offset);
  99461. if (vertex.id === _this.vertices.length) {
  99462. _this.vertices.push(vertex);
  99463. }
  99464. vertexReferences.push(vertex.id);
  99465. };
  99466. //var totalVertices = mesh.getTotalVertices();
  99467. var totalVertices = submesh.verticesCount;
  99468. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  99469. var indicesInit = function (i) {
  99470. if (!indices) {
  99471. return;
  99472. }
  99473. var offset = (submesh.indexStart / 3) + i;
  99474. var pos = (offset * 3);
  99475. var i0 = indices[pos + 0];
  99476. var i1 = indices[pos + 1];
  99477. var i2 = indices[pos + 2];
  99478. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  99479. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  99480. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  99481. var triangle = new DecimationTriangle([v0, v1, v2]);
  99482. triangle.originalOffset = pos;
  99483. _this.triangles.push(triangle);
  99484. };
  99485. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  99486. _this.init(callback);
  99487. });
  99488. });
  99489. };
  99490. QuadraticErrorSimplification.prototype.init = function (callback) {
  99491. var _this = this;
  99492. var triangleInit1 = function (i) {
  99493. var t = _this.triangles[i];
  99494. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  99495. for (var j = 0; j < 3; j++) {
  99496. 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))));
  99497. }
  99498. };
  99499. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  99500. var triangleInit2 = function (i) {
  99501. var t = _this.triangles[i];
  99502. for (var j = 0; j < 3; ++j) {
  99503. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  99504. }
  99505. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  99506. };
  99507. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  99508. callback();
  99509. });
  99510. });
  99511. };
  99512. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  99513. var newTriangles = [];
  99514. var i;
  99515. for (i = 0; i < this.vertices.length; ++i) {
  99516. this.vertices[i].triangleCount = 0;
  99517. }
  99518. var t;
  99519. var j;
  99520. for (i = 0; i < this.triangles.length; ++i) {
  99521. if (!this.triangles[i].deleted) {
  99522. t = this.triangles[i];
  99523. for (j = 0; j < 3; ++j) {
  99524. t.vertices[j].triangleCount = 1;
  99525. }
  99526. newTriangles.push(t);
  99527. }
  99528. }
  99529. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  99530. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  99531. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  99532. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  99533. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  99534. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  99535. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  99536. var vertexCount = 0;
  99537. for (i = 0; i < this.vertices.length; ++i) {
  99538. var vertex = this.vertices[i];
  99539. vertex.id = vertexCount;
  99540. if (vertex.triangleCount) {
  99541. vertex.originalOffsets.forEach(function (originalOffset) {
  99542. if (!normalData) {
  99543. return;
  99544. }
  99545. newPositionData.push(vertex.position.x);
  99546. newPositionData.push(vertex.position.y);
  99547. newPositionData.push(vertex.position.z);
  99548. newNormalData.push(normalData[originalOffset * 3]);
  99549. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  99550. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  99551. if (uvs && uvs.length) {
  99552. newUVsData.push(uvs[(originalOffset * 2)]);
  99553. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  99554. }
  99555. else if (colorsData && colorsData.length) {
  99556. newColorsData.push(colorsData[(originalOffset * 4)]);
  99557. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  99558. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  99559. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  99560. }
  99561. ++vertexCount;
  99562. });
  99563. }
  99564. }
  99565. var startingIndex = this._reconstructedMesh.getTotalIndices();
  99566. var startingVertex = this._reconstructedMesh.getTotalVertices();
  99567. var submeshesArray = this._reconstructedMesh.subMeshes;
  99568. this._reconstructedMesh.subMeshes = [];
  99569. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  99570. var originalIndices = this._mesh.getIndices();
  99571. for (i = 0; i < newTriangles.length; ++i) {
  99572. t = newTriangles[i]; //now get the new referencing point for each vertex
  99573. [0, 1, 2].forEach(function (idx) {
  99574. var id = originalIndices[t.originalOffset + idx];
  99575. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  99576. if (offset < 0)
  99577. offset = 0;
  99578. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  99579. });
  99580. }
  99581. //overwriting the old vertex buffers and indices.
  99582. this._reconstructedMesh.setIndices(newIndicesArray);
  99583. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  99584. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  99585. if (newUVsData.length > 0)
  99586. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  99587. if (newColorsData.length > 0)
  99588. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  99589. //create submesh
  99590. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  99591. if (submeshIndex > 0) {
  99592. this._reconstructedMesh.subMeshes = [];
  99593. submeshesArray.forEach(function (submesh) {
  99594. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  99595. });
  99596. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  99597. }
  99598. };
  99599. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  99600. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  99601. this._reconstructedMesh.material = this._mesh.material;
  99602. this._reconstructedMesh.parent = this._mesh.parent;
  99603. this._reconstructedMesh.isVisible = false;
  99604. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  99605. };
  99606. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  99607. for (var i = 0; i < vertex1.triangleCount; ++i) {
  99608. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  99609. if (t.deleted)
  99610. continue;
  99611. var s = this.references[vertex1.triangleStart + i].vertexId;
  99612. var v1 = t.vertices[(s + 1) % 3];
  99613. var v2 = t.vertices[(s + 2) % 3];
  99614. if ((v1 === vertex2 || v2 === vertex2)) {
  99615. deletedArray[i] = true;
  99616. delTr.push(t);
  99617. continue;
  99618. }
  99619. var d1 = v1.position.subtract(point);
  99620. d1 = d1.normalize();
  99621. var d2 = v2.position.subtract(point);
  99622. d2 = d2.normalize();
  99623. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  99624. return true;
  99625. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  99626. deletedArray[i] = false;
  99627. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  99628. return true;
  99629. }
  99630. return false;
  99631. };
  99632. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  99633. var newDeleted = deletedTriangles;
  99634. for (var i = 0; i < vertex.triangleCount; ++i) {
  99635. var ref = this.references[vertex.triangleStart + i];
  99636. var t = this.triangles[ref.triangleId];
  99637. if (t.deleted)
  99638. continue;
  99639. if (deletedArray[i] && t.deletePending) {
  99640. t.deleted = true;
  99641. newDeleted++;
  99642. continue;
  99643. }
  99644. t.vertices[ref.vertexId] = origVertex;
  99645. t.isDirty = true;
  99646. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  99647. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  99648. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  99649. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  99650. this.references.push(ref);
  99651. }
  99652. return newDeleted;
  99653. };
  99654. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  99655. for (var i = 0; i < this.vertices.length; ++i) {
  99656. var vCount = [];
  99657. var vId = [];
  99658. var v = this.vertices[i];
  99659. var j;
  99660. for (j = 0; j < v.triangleCount; ++j) {
  99661. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  99662. for (var ii = 0; ii < 3; ii++) {
  99663. var ofs = 0;
  99664. var vv = triangle.vertices[ii];
  99665. while (ofs < vCount.length) {
  99666. if (vId[ofs] === vv.id)
  99667. break;
  99668. ++ofs;
  99669. }
  99670. if (ofs === vCount.length) {
  99671. vCount.push(1);
  99672. vId.push(vv.id);
  99673. }
  99674. else {
  99675. vCount[ofs]++;
  99676. }
  99677. }
  99678. }
  99679. for (j = 0; j < vCount.length; ++j) {
  99680. if (vCount[j] === 1) {
  99681. this.vertices[vId[j]].isBorder = true;
  99682. }
  99683. else {
  99684. this.vertices[vId[j]].isBorder = false;
  99685. }
  99686. }
  99687. }
  99688. };
  99689. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  99690. if (identifyBorders === void 0) { identifyBorders = false; }
  99691. var i;
  99692. if (!identifyBorders) {
  99693. var newTrianglesVector = [];
  99694. for (i = 0; i < this.triangles.length; ++i) {
  99695. if (!this.triangles[i].deleted) {
  99696. newTrianglesVector.push(this.triangles[i]);
  99697. }
  99698. }
  99699. this.triangles = newTrianglesVector;
  99700. }
  99701. for (i = 0; i < this.vertices.length; ++i) {
  99702. this.vertices[i].triangleCount = 0;
  99703. this.vertices[i].triangleStart = 0;
  99704. }
  99705. var t;
  99706. var j;
  99707. var v;
  99708. for (i = 0; i < this.triangles.length; ++i) {
  99709. t = this.triangles[i];
  99710. for (j = 0; j < 3; ++j) {
  99711. v = t.vertices[j];
  99712. v.triangleCount++;
  99713. }
  99714. }
  99715. var tStart = 0;
  99716. for (i = 0; i < this.vertices.length; ++i) {
  99717. this.vertices[i].triangleStart = tStart;
  99718. tStart += this.vertices[i].triangleCount;
  99719. this.vertices[i].triangleCount = 0;
  99720. }
  99721. var newReferences = new Array(this.triangles.length * 3);
  99722. for (i = 0; i < this.triangles.length; ++i) {
  99723. t = this.triangles[i];
  99724. for (j = 0; j < 3; ++j) {
  99725. v = t.vertices[j];
  99726. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  99727. v.triangleCount++;
  99728. }
  99729. }
  99730. this.references = newReferences;
  99731. if (identifyBorders) {
  99732. this.identifyBorder();
  99733. }
  99734. };
  99735. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  99736. var x = point.x;
  99737. var y = point.y;
  99738. var z = point.z;
  99739. 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
  99740. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  99741. };
  99742. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  99743. var q = vertex1.q.add(vertex2.q);
  99744. var border = vertex1.isBorder && vertex2.isBorder;
  99745. var error = 0;
  99746. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  99747. if (qDet !== 0 && !border) {
  99748. if (!pointResult) {
  99749. pointResult = BABYLON.Vector3.Zero();
  99750. }
  99751. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  99752. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  99753. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  99754. error = this.vertexError(q, pointResult);
  99755. }
  99756. else {
  99757. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  99758. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  99759. var error1 = this.vertexError(q, vertex1.position);
  99760. var error2 = this.vertexError(q, vertex2.position);
  99761. var error3 = this.vertexError(q, p3);
  99762. error = Math.min(error1, error2, error3);
  99763. if (error === error1) {
  99764. if (pointResult) {
  99765. pointResult.copyFrom(vertex1.position);
  99766. }
  99767. }
  99768. else if (error === error2) {
  99769. if (pointResult) {
  99770. pointResult.copyFrom(vertex2.position);
  99771. }
  99772. }
  99773. else {
  99774. if (pointResult) {
  99775. pointResult.copyFrom(p3);
  99776. }
  99777. }
  99778. }
  99779. return error;
  99780. };
  99781. return QuadraticErrorSimplification;
  99782. }());
  99783. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  99784. })(BABYLON || (BABYLON = {}));
  99785. //# sourceMappingURL=babylon.meshSimplification.js.map
  99786. var BABYLON;
  99787. (function (BABYLON) {
  99788. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  99789. get: function () {
  99790. if (!this._simplificationQueue) {
  99791. this._simplificationQueue = new BABYLON.SimplificationQueue();
  99792. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  99793. if (!component) {
  99794. component = new SimplicationQueueSceneComponent(this);
  99795. this._addComponent(component);
  99796. }
  99797. }
  99798. return this._simplificationQueue;
  99799. },
  99800. set: function (value) {
  99801. this._simplificationQueue = value;
  99802. },
  99803. enumerable: true,
  99804. configurable: true
  99805. });
  99806. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  99807. if (parallelProcessing === void 0) { parallelProcessing = true; }
  99808. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  99809. this.getScene().simplificationQueue.addTask({
  99810. settings: settings,
  99811. parallelProcessing: parallelProcessing,
  99812. mesh: this,
  99813. simplificationType: simplificationType,
  99814. successCallback: successCallback
  99815. });
  99816. return this;
  99817. };
  99818. /**
  99819. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  99820. * created in a scene
  99821. */
  99822. var SimplicationQueueSceneComponent = /** @class */ (function () {
  99823. /**
  99824. * Creates a new instance of the component for the given scene
  99825. * @param scene Defines the scene to register the component in
  99826. */
  99827. function SimplicationQueueSceneComponent(scene) {
  99828. /**
  99829. * The component name helpfull to identify the component in the list of scene components.
  99830. */
  99831. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  99832. this.scene = scene;
  99833. }
  99834. /**
  99835. * Registers the component in a given scene
  99836. */
  99837. SimplicationQueueSceneComponent.prototype.register = function () {
  99838. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  99839. };
  99840. /**
  99841. * Rebuilds the elements related to this component in case of
  99842. * context lost for instance.
  99843. */
  99844. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  99845. // Nothing to do for this component
  99846. };
  99847. /**
  99848. * Disposes the component and the associated ressources
  99849. */
  99850. SimplicationQueueSceneComponent.prototype.dispose = function () {
  99851. // Nothing to do for this component
  99852. };
  99853. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  99854. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  99855. this.scene._simplificationQueue.executeNext();
  99856. }
  99857. };
  99858. return SimplicationQueueSceneComponent;
  99859. }());
  99860. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  99861. })(BABYLON || (BABYLON = {}));
  99862. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  99863. var BABYLON;
  99864. (function (BABYLON) {
  99865. var MeshLODLevel = /** @class */ (function () {
  99866. function MeshLODLevel(distance, mesh) {
  99867. this.distance = distance;
  99868. this.mesh = mesh;
  99869. }
  99870. return MeshLODLevel;
  99871. }());
  99872. BABYLON.MeshLODLevel = MeshLODLevel;
  99873. })(BABYLON || (BABYLON = {}));
  99874. //# sourceMappingURL=babylon.meshLODLevel.js.map
  99875. var BABYLON;
  99876. (function (BABYLON) {
  99877. /**
  99878. * Defines the root class used to create scene optimization to use with SceneOptimizer
  99879. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99880. */
  99881. var SceneOptimization = /** @class */ (function () {
  99882. /**
  99883. * Creates the SceneOptimization object
  99884. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99885. * @param desc defines the description associated with the optimization
  99886. */
  99887. function SceneOptimization(
  99888. /**
  99889. * Defines the priority of this optimization (0 by default which means first in the list)
  99890. */
  99891. priority) {
  99892. if (priority === void 0) { priority = 0; }
  99893. this.priority = priority;
  99894. }
  99895. /**
  99896. * Gets a string describing the action executed by the current optimization
  99897. * @returns description string
  99898. */
  99899. SceneOptimization.prototype.getDescription = function () {
  99900. return "";
  99901. };
  99902. /**
  99903. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99904. * @param scene defines the current scene where to apply this optimization
  99905. * @param optimizer defines the current optimizer
  99906. * @returns true if everything that can be done was applied
  99907. */
  99908. SceneOptimization.prototype.apply = function (scene, optimizer) {
  99909. return true;
  99910. };
  99911. ;
  99912. return SceneOptimization;
  99913. }());
  99914. BABYLON.SceneOptimization = SceneOptimization;
  99915. /**
  99916. * Defines an optimization used to reduce the size of render target textures
  99917. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99918. */
  99919. var TextureOptimization = /** @class */ (function (_super) {
  99920. __extends(TextureOptimization, _super);
  99921. /**
  99922. * Creates the TextureOptimization object
  99923. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99924. * @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
  99925. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99926. */
  99927. function TextureOptimization(
  99928. /**
  99929. * Defines the priority of this optimization (0 by default which means first in the list)
  99930. */
  99931. priority,
  99932. /**
  99933. * 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
  99934. */
  99935. maximumSize,
  99936. /**
  99937. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99938. */
  99939. step) {
  99940. if (priority === void 0) { priority = 0; }
  99941. if (maximumSize === void 0) { maximumSize = 1024; }
  99942. if (step === void 0) { step = 0.5; }
  99943. var _this = _super.call(this, priority) || this;
  99944. _this.priority = priority;
  99945. _this.maximumSize = maximumSize;
  99946. _this.step = step;
  99947. return _this;
  99948. }
  99949. /**
  99950. * Gets a string describing the action executed by the current optimization
  99951. * @returns description string
  99952. */
  99953. TextureOptimization.prototype.getDescription = function () {
  99954. return "Reducing render target texture size to " + this.maximumSize;
  99955. };
  99956. /**
  99957. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99958. * @param scene defines the current scene where to apply this optimization
  99959. * @param optimizer defines the current optimizer
  99960. * @returns true if everything that can be done was applied
  99961. */
  99962. TextureOptimization.prototype.apply = function (scene, optimizer) {
  99963. var allDone = true;
  99964. for (var index = 0; index < scene.textures.length; index++) {
  99965. var texture = scene.textures[index];
  99966. if (!texture.canRescale || texture.getContext) {
  99967. continue;
  99968. }
  99969. var currentSize = texture.getSize();
  99970. var maxDimension = Math.max(currentSize.width, currentSize.height);
  99971. if (maxDimension > this.maximumSize) {
  99972. texture.scale(this.step);
  99973. allDone = false;
  99974. }
  99975. }
  99976. return allDone;
  99977. };
  99978. return TextureOptimization;
  99979. }(SceneOptimization));
  99980. BABYLON.TextureOptimization = TextureOptimization;
  99981. /**
  99982. * Defines an optimization used to increase or decrease the rendering resolution
  99983. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99984. */
  99985. var HardwareScalingOptimization = /** @class */ (function (_super) {
  99986. __extends(HardwareScalingOptimization, _super);
  99987. /**
  99988. * Creates the HardwareScalingOptimization object
  99989. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99990. * @param maximumScale defines the maximum scale to use (2 by default)
  99991. * @param step defines the step to use between two passes (0.5 by default)
  99992. */
  99993. function HardwareScalingOptimization(
  99994. /**
  99995. * Defines the priority of this optimization (0 by default which means first in the list)
  99996. */
  99997. priority,
  99998. /**
  99999. * Defines the maximum scale to use (2 by default)
  100000. */
  100001. maximumScale,
  100002. /**
  100003. * Defines the step to use between two passes (0.5 by default)
  100004. */
  100005. step) {
  100006. if (priority === void 0) { priority = 0; }
  100007. if (maximumScale === void 0) { maximumScale = 2; }
  100008. if (step === void 0) { step = 0.25; }
  100009. var _this = _super.call(this, priority) || this;
  100010. _this.priority = priority;
  100011. _this.maximumScale = maximumScale;
  100012. _this.step = step;
  100013. _this._currentScale = -1;
  100014. _this._directionOffset = 1;
  100015. return _this;
  100016. }
  100017. /**
  100018. * Gets a string describing the action executed by the current optimization
  100019. * @return description string
  100020. */
  100021. HardwareScalingOptimization.prototype.getDescription = function () {
  100022. return "Setting hardware scaling level to " + this._currentScale;
  100023. };
  100024. /**
  100025. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100026. * @param scene defines the current scene where to apply this optimization
  100027. * @param optimizer defines the current optimizer
  100028. * @returns true if everything that can be done was applied
  100029. */
  100030. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  100031. if (this._currentScale === -1) {
  100032. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  100033. if (this._currentScale > this.maximumScale) {
  100034. this._directionOffset = -1;
  100035. }
  100036. }
  100037. this._currentScale += this._directionOffset * this.step;
  100038. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  100039. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  100040. };
  100041. ;
  100042. return HardwareScalingOptimization;
  100043. }(SceneOptimization));
  100044. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  100045. /**
  100046. * Defines an optimization used to remove shadows
  100047. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100048. */
  100049. var ShadowsOptimization = /** @class */ (function (_super) {
  100050. __extends(ShadowsOptimization, _super);
  100051. function ShadowsOptimization() {
  100052. return _super !== null && _super.apply(this, arguments) || this;
  100053. }
  100054. /**
  100055. * Gets a string describing the action executed by the current optimization
  100056. * @return description string
  100057. */
  100058. ShadowsOptimization.prototype.getDescription = function () {
  100059. return "Turning shadows on/off";
  100060. };
  100061. /**
  100062. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100063. * @param scene defines the current scene where to apply this optimization
  100064. * @param optimizer defines the current optimizer
  100065. * @returns true if everything that can be done was applied
  100066. */
  100067. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  100068. scene.shadowsEnabled = optimizer.isInImprovementMode;
  100069. return true;
  100070. };
  100071. ;
  100072. return ShadowsOptimization;
  100073. }(SceneOptimization));
  100074. BABYLON.ShadowsOptimization = ShadowsOptimization;
  100075. /**
  100076. * Defines an optimization used to turn post-processes off
  100077. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100078. */
  100079. var PostProcessesOptimization = /** @class */ (function (_super) {
  100080. __extends(PostProcessesOptimization, _super);
  100081. function PostProcessesOptimization() {
  100082. return _super !== null && _super.apply(this, arguments) || this;
  100083. }
  100084. /**
  100085. * Gets a string describing the action executed by the current optimization
  100086. * @return description string
  100087. */
  100088. PostProcessesOptimization.prototype.getDescription = function () {
  100089. return "Turning post-processes on/off";
  100090. };
  100091. /**
  100092. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100093. * @param scene defines the current scene where to apply this optimization
  100094. * @param optimizer defines the current optimizer
  100095. * @returns true if everything that can be done was applied
  100096. */
  100097. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  100098. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  100099. return true;
  100100. };
  100101. ;
  100102. return PostProcessesOptimization;
  100103. }(SceneOptimization));
  100104. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  100105. /**
  100106. * Defines an optimization used to turn lens flares off
  100107. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100108. */
  100109. var LensFlaresOptimization = /** @class */ (function (_super) {
  100110. __extends(LensFlaresOptimization, _super);
  100111. function LensFlaresOptimization() {
  100112. return _super !== null && _super.apply(this, arguments) || this;
  100113. }
  100114. /**
  100115. * Gets a string describing the action executed by the current optimization
  100116. * @return description string
  100117. */
  100118. LensFlaresOptimization.prototype.getDescription = function () {
  100119. return "Turning lens flares on/off";
  100120. };
  100121. /**
  100122. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100123. * @param scene defines the current scene where to apply this optimization
  100124. * @param optimizer defines the current optimizer
  100125. * @returns true if everything that can be done was applied
  100126. */
  100127. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  100128. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  100129. return true;
  100130. };
  100131. ;
  100132. return LensFlaresOptimization;
  100133. }(SceneOptimization));
  100134. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  100135. /**
  100136. * Defines an optimization based on user defined callback.
  100137. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100138. */
  100139. var CustomOptimization = /** @class */ (function (_super) {
  100140. __extends(CustomOptimization, _super);
  100141. function CustomOptimization() {
  100142. return _super !== null && _super.apply(this, arguments) || this;
  100143. }
  100144. /**
  100145. * Gets a string describing the action executed by the current optimization
  100146. * @returns description string
  100147. */
  100148. CustomOptimization.prototype.getDescription = function () {
  100149. if (this.onGetDescription) {
  100150. return this.onGetDescription();
  100151. }
  100152. return "Running user defined callback";
  100153. };
  100154. /**
  100155. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100156. * @param scene defines the current scene where to apply this optimization
  100157. * @param optimizer defines the current optimizer
  100158. * @returns true if everything that can be done was applied
  100159. */
  100160. CustomOptimization.prototype.apply = function (scene, optimizer) {
  100161. if (this.onApply) {
  100162. return this.onApply(scene, optimizer);
  100163. }
  100164. return true;
  100165. };
  100166. ;
  100167. return CustomOptimization;
  100168. }(SceneOptimization));
  100169. BABYLON.CustomOptimization = CustomOptimization;
  100170. /**
  100171. * Defines an optimization used to turn particles off
  100172. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100173. */
  100174. var ParticlesOptimization = /** @class */ (function (_super) {
  100175. __extends(ParticlesOptimization, _super);
  100176. function ParticlesOptimization() {
  100177. return _super !== null && _super.apply(this, arguments) || this;
  100178. }
  100179. /**
  100180. * Gets a string describing the action executed by the current optimization
  100181. * @return description string
  100182. */
  100183. ParticlesOptimization.prototype.getDescription = function () {
  100184. return "Turning particles on/off";
  100185. };
  100186. /**
  100187. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100188. * @param scene defines the current scene where to apply this optimization
  100189. * @param optimizer defines the current optimizer
  100190. * @returns true if everything that can be done was applied
  100191. */
  100192. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  100193. scene.particlesEnabled = optimizer.isInImprovementMode;
  100194. return true;
  100195. };
  100196. ;
  100197. return ParticlesOptimization;
  100198. }(SceneOptimization));
  100199. BABYLON.ParticlesOptimization = ParticlesOptimization;
  100200. /**
  100201. * Defines an optimization used to turn render targets off
  100202. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100203. */
  100204. var RenderTargetsOptimization = /** @class */ (function (_super) {
  100205. __extends(RenderTargetsOptimization, _super);
  100206. function RenderTargetsOptimization() {
  100207. return _super !== null && _super.apply(this, arguments) || this;
  100208. }
  100209. /**
  100210. * Gets a string describing the action executed by the current optimization
  100211. * @return description string
  100212. */
  100213. RenderTargetsOptimization.prototype.getDescription = function () {
  100214. return "Turning render targets off";
  100215. };
  100216. /**
  100217. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100218. * @param scene defines the current scene where to apply this optimization
  100219. * @param optimizer defines the current optimizer
  100220. * @returns true if everything that can be done was applied
  100221. */
  100222. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  100223. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  100224. return true;
  100225. };
  100226. ;
  100227. return RenderTargetsOptimization;
  100228. }(SceneOptimization));
  100229. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  100230. /**
  100231. * Defines an optimization used to merge meshes with compatible materials
  100232. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100233. */
  100234. var MergeMeshesOptimization = /** @class */ (function (_super) {
  100235. __extends(MergeMeshesOptimization, _super);
  100236. function MergeMeshesOptimization() {
  100237. var _this = _super !== null && _super.apply(this, arguments) || this;
  100238. _this._canBeMerged = function (abstractMesh) {
  100239. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  100240. return false;
  100241. }
  100242. var mesh = abstractMesh;
  100243. if (mesh.isDisposed()) {
  100244. return false;
  100245. }
  100246. if (!mesh.isVisible || !mesh.isEnabled()) {
  100247. return false;
  100248. }
  100249. if (mesh.instances.length > 0) {
  100250. return false;
  100251. }
  100252. if (mesh.skeleton || mesh.hasLODLevels) {
  100253. return false;
  100254. }
  100255. return true;
  100256. };
  100257. return _this;
  100258. }
  100259. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  100260. /**
  100261. * Gets or sets a boolean which defines if optimization octree has to be updated
  100262. */
  100263. get: function () {
  100264. return MergeMeshesOptimization._UpdateSelectionTree;
  100265. },
  100266. /**
  100267. * Gets or sets a boolean which defines if optimization octree has to be updated
  100268. */
  100269. set: function (value) {
  100270. MergeMeshesOptimization._UpdateSelectionTree = value;
  100271. },
  100272. enumerable: true,
  100273. configurable: true
  100274. });
  100275. /**
  100276. * Gets a string describing the action executed by the current optimization
  100277. * @return description string
  100278. */
  100279. MergeMeshesOptimization.prototype.getDescription = function () {
  100280. return "Merging similar meshes together";
  100281. };
  100282. /**
  100283. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100284. * @param scene defines the current scene where to apply this optimization
  100285. * @param optimizer defines the current optimizer
  100286. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  100287. * @returns true if everything that can be done was applied
  100288. */
  100289. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  100290. var globalPool = scene.meshes.slice(0);
  100291. var globalLength = globalPool.length;
  100292. for (var index = 0; index < globalLength; index++) {
  100293. var currentPool = new Array();
  100294. var current = globalPool[index];
  100295. // Checks
  100296. if (!this._canBeMerged(current)) {
  100297. continue;
  100298. }
  100299. currentPool.push(current);
  100300. // Find compatible meshes
  100301. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  100302. var otherMesh = globalPool[subIndex];
  100303. if (!this._canBeMerged(otherMesh)) {
  100304. continue;
  100305. }
  100306. if (otherMesh.material !== current.material) {
  100307. continue;
  100308. }
  100309. if (otherMesh.checkCollisions !== current.checkCollisions) {
  100310. continue;
  100311. }
  100312. currentPool.push(otherMesh);
  100313. globalLength--;
  100314. globalPool.splice(subIndex, 1);
  100315. subIndex--;
  100316. }
  100317. if (currentPool.length < 2) {
  100318. continue;
  100319. }
  100320. // Merge meshes
  100321. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  100322. }
  100323. // Call the octree system optimization if it is defined.
  100324. var sceneAsAny = scene;
  100325. if (sceneAsAny.createOrUpdateSelectionOctree) {
  100326. if (updateSelectionTree != undefined) {
  100327. if (updateSelectionTree) {
  100328. sceneAsAny.createOrUpdateSelectionOctree();
  100329. }
  100330. }
  100331. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  100332. sceneAsAny.createOrUpdateSelectionOctree();
  100333. }
  100334. }
  100335. return true;
  100336. };
  100337. ;
  100338. MergeMeshesOptimization._UpdateSelectionTree = false;
  100339. return MergeMeshesOptimization;
  100340. }(SceneOptimization));
  100341. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  100342. /**
  100343. * Defines a list of options used by SceneOptimizer
  100344. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100345. */
  100346. var SceneOptimizerOptions = /** @class */ (function () {
  100347. /**
  100348. * Creates a new list of options used by SceneOptimizer
  100349. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  100350. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  100351. */
  100352. function SceneOptimizerOptions(
  100353. /**
  100354. * Defines the target frame rate to reach (60 by default)
  100355. */
  100356. targetFrameRate,
  100357. /**
  100358. * Defines the interval between two checkes (2000ms by default)
  100359. */
  100360. trackerDuration) {
  100361. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  100362. if (trackerDuration === void 0) { trackerDuration = 2000; }
  100363. this.targetFrameRate = targetFrameRate;
  100364. this.trackerDuration = trackerDuration;
  100365. /**
  100366. * Gets the list of optimizations to apply
  100367. */
  100368. this.optimizations = new Array();
  100369. }
  100370. /**
  100371. * Add a new optimization
  100372. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  100373. * @returns the current SceneOptimizerOptions
  100374. */
  100375. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  100376. this.optimizations.push(optimization);
  100377. return this;
  100378. };
  100379. /**
  100380. * Add a new custom optimization
  100381. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  100382. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  100383. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100384. * @returns the current SceneOptimizerOptions
  100385. */
  100386. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  100387. if (priority === void 0) { priority = 0; }
  100388. var optimization = new CustomOptimization(priority);
  100389. optimization.onApply = onApply;
  100390. optimization.onGetDescription = onGetDescription;
  100391. this.optimizations.push(optimization);
  100392. return this;
  100393. };
  100394. /**
  100395. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  100396. * @param targetFrameRate defines the target frame rate (60 by default)
  100397. * @returns a SceneOptimizerOptions object
  100398. */
  100399. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  100400. var result = new SceneOptimizerOptions(targetFrameRate);
  100401. var priority = 0;
  100402. result.addOptimization(new MergeMeshesOptimization(priority));
  100403. result.addOptimization(new ShadowsOptimization(priority));
  100404. result.addOptimization(new LensFlaresOptimization(priority));
  100405. // Next priority
  100406. priority++;
  100407. result.addOptimization(new PostProcessesOptimization(priority));
  100408. result.addOptimization(new ParticlesOptimization(priority));
  100409. // Next priority
  100410. priority++;
  100411. result.addOptimization(new TextureOptimization(priority, 1024));
  100412. return result;
  100413. };
  100414. /**
  100415. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  100416. * @param targetFrameRate defines the target frame rate (60 by default)
  100417. * @returns a SceneOptimizerOptions object
  100418. */
  100419. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  100420. var result = new SceneOptimizerOptions(targetFrameRate);
  100421. var priority = 0;
  100422. result.addOptimization(new MergeMeshesOptimization(priority));
  100423. result.addOptimization(new ShadowsOptimization(priority));
  100424. result.addOptimization(new LensFlaresOptimization(priority));
  100425. // Next priority
  100426. priority++;
  100427. result.addOptimization(new PostProcessesOptimization(priority));
  100428. result.addOptimization(new ParticlesOptimization(priority));
  100429. // Next priority
  100430. priority++;
  100431. result.addOptimization(new TextureOptimization(priority, 512));
  100432. // Next priority
  100433. priority++;
  100434. result.addOptimization(new RenderTargetsOptimization(priority));
  100435. // Next priority
  100436. priority++;
  100437. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  100438. return result;
  100439. };
  100440. /**
  100441. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  100442. * @param targetFrameRate defines the target frame rate (60 by default)
  100443. * @returns a SceneOptimizerOptions object
  100444. */
  100445. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  100446. var result = new SceneOptimizerOptions(targetFrameRate);
  100447. var priority = 0;
  100448. result.addOptimization(new MergeMeshesOptimization(priority));
  100449. result.addOptimization(new ShadowsOptimization(priority));
  100450. result.addOptimization(new LensFlaresOptimization(priority));
  100451. // Next priority
  100452. priority++;
  100453. result.addOptimization(new PostProcessesOptimization(priority));
  100454. result.addOptimization(new ParticlesOptimization(priority));
  100455. // Next priority
  100456. priority++;
  100457. result.addOptimization(new TextureOptimization(priority, 256));
  100458. // Next priority
  100459. priority++;
  100460. result.addOptimization(new RenderTargetsOptimization(priority));
  100461. // Next priority
  100462. priority++;
  100463. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  100464. return result;
  100465. };
  100466. return SceneOptimizerOptions;
  100467. }());
  100468. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  100469. /**
  100470. * Class used to run optimizations in order to reach a target frame rate
  100471. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100472. */
  100473. var SceneOptimizer = /** @class */ (function () {
  100474. /**
  100475. * Creates a new SceneOptimizer
  100476. * @param scene defines the scene to work on
  100477. * @param options defines the options to use with the SceneOptimizer
  100478. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  100479. * @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)
  100480. */
  100481. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  100482. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  100483. if (improvementMode === void 0) { improvementMode = false; }
  100484. var _this = this;
  100485. this._isRunning = false;
  100486. this._currentPriorityLevel = 0;
  100487. this._targetFrameRate = 60;
  100488. this._trackerDuration = 2000;
  100489. this._currentFrameRate = 0;
  100490. this._improvementMode = false;
  100491. /**
  100492. * Defines an observable called when the optimizer reaches the target frame rate
  100493. */
  100494. this.onSuccessObservable = new BABYLON.Observable();
  100495. /**
  100496. * Defines an observable called when the optimizer enables an optimization
  100497. */
  100498. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  100499. /**
  100500. * Defines an observable called when the optimizer is not able to reach the target frame rate
  100501. */
  100502. this.onFailureObservable = new BABYLON.Observable();
  100503. if (!options) {
  100504. this._options = new SceneOptimizerOptions();
  100505. }
  100506. else {
  100507. this._options = options;
  100508. }
  100509. if (this._options.targetFrameRate) {
  100510. this._targetFrameRate = this._options.targetFrameRate;
  100511. }
  100512. if (this._options.trackerDuration) {
  100513. this._trackerDuration = this._options.trackerDuration;
  100514. }
  100515. if (autoGeneratePriorities) {
  100516. var priority = 0;
  100517. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  100518. var optim = _a[_i];
  100519. optim.priority = priority++;
  100520. }
  100521. }
  100522. this._improvementMode = improvementMode;
  100523. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100524. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  100525. _this._sceneDisposeObserver = null;
  100526. _this.dispose();
  100527. });
  100528. }
  100529. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  100530. /**
  100531. * Gets a boolean indicating if the optimizer is in improvement mode
  100532. */
  100533. get: function () {
  100534. return this._improvementMode;
  100535. },
  100536. enumerable: true,
  100537. configurable: true
  100538. });
  100539. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  100540. /**
  100541. * Gets the current priority level (0 at start)
  100542. */
  100543. get: function () {
  100544. return this._currentPriorityLevel;
  100545. },
  100546. enumerable: true,
  100547. configurable: true
  100548. });
  100549. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  100550. /**
  100551. * Gets the current frame rate checked by the SceneOptimizer
  100552. */
  100553. get: function () {
  100554. return this._currentFrameRate;
  100555. },
  100556. enumerable: true,
  100557. configurable: true
  100558. });
  100559. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  100560. /**
  100561. * Gets or sets the current target frame rate (60 by default)
  100562. */
  100563. get: function () {
  100564. return this._targetFrameRate;
  100565. },
  100566. /**
  100567. * Gets or sets the current target frame rate (60 by default)
  100568. */
  100569. set: function (value) {
  100570. this._targetFrameRate = value;
  100571. },
  100572. enumerable: true,
  100573. configurable: true
  100574. });
  100575. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  100576. /**
  100577. * Gets or sets the current interval between two checks (every 2000ms by default)
  100578. */
  100579. get: function () {
  100580. return this._trackerDuration;
  100581. },
  100582. /**
  100583. * Gets or sets the current interval between two checks (every 2000ms by default)
  100584. */
  100585. set: function (value) {
  100586. this._trackerDuration = value;
  100587. },
  100588. enumerable: true,
  100589. configurable: true
  100590. });
  100591. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  100592. /**
  100593. * Gets the list of active optimizations
  100594. */
  100595. get: function () {
  100596. return this._options.optimizations;
  100597. },
  100598. enumerable: true,
  100599. configurable: true
  100600. });
  100601. /**
  100602. * Stops the current optimizer
  100603. */
  100604. SceneOptimizer.prototype.stop = function () {
  100605. this._isRunning = false;
  100606. };
  100607. /**
  100608. * Reset the optimizer to initial step (current priority level = 0)
  100609. */
  100610. SceneOptimizer.prototype.reset = function () {
  100611. this._currentPriorityLevel = 0;
  100612. };
  100613. /**
  100614. * Start the optimizer. By default it will try to reach a specific framerate
  100615. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  100616. */
  100617. SceneOptimizer.prototype.start = function () {
  100618. var _this = this;
  100619. if (this._isRunning) {
  100620. return;
  100621. }
  100622. this._isRunning = true;
  100623. // Let's wait for the scene to be ready before running our check
  100624. this._scene.executeWhenReady(function () {
  100625. setTimeout(function () {
  100626. _this._checkCurrentState();
  100627. }, _this._trackerDuration);
  100628. });
  100629. };
  100630. SceneOptimizer.prototype._checkCurrentState = function () {
  100631. var _this = this;
  100632. if (!this._isRunning) {
  100633. return;
  100634. }
  100635. var scene = this._scene;
  100636. var options = this._options;
  100637. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  100638. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  100639. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  100640. this._isRunning = false;
  100641. this.onSuccessObservable.notifyObservers(this);
  100642. return;
  100643. }
  100644. // Apply current level of optimizations
  100645. var allDone = true;
  100646. var noOptimizationApplied = true;
  100647. for (var index = 0; index < options.optimizations.length; index++) {
  100648. var optimization = options.optimizations[index];
  100649. if (optimization.priority === this._currentPriorityLevel) {
  100650. noOptimizationApplied = false;
  100651. allDone = allDone && optimization.apply(scene, this);
  100652. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  100653. }
  100654. }
  100655. // If no optimization was applied, this is a failure :(
  100656. if (noOptimizationApplied) {
  100657. this._isRunning = false;
  100658. this.onFailureObservable.notifyObservers(this);
  100659. return;
  100660. }
  100661. // If all optimizations were done, move to next level
  100662. if (allDone) {
  100663. this._currentPriorityLevel++;
  100664. }
  100665. // Let's the system running for a specific amount of time before checking FPS
  100666. scene.executeWhenReady(function () {
  100667. setTimeout(function () {
  100668. _this._checkCurrentState();
  100669. }, _this._trackerDuration);
  100670. });
  100671. };
  100672. /**
  100673. * Release all resources
  100674. */
  100675. SceneOptimizer.prototype.dispose = function () {
  100676. this.stop();
  100677. this.onSuccessObservable.clear();
  100678. this.onFailureObservable.clear();
  100679. this.onNewOptimizationAppliedObservable.clear();
  100680. if (this._sceneDisposeObserver) {
  100681. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100682. }
  100683. };
  100684. /**
  100685. * Helper function to create a SceneOptimizer with one single line of code
  100686. * @param scene defines the scene to work on
  100687. * @param options defines the options to use with the SceneOptimizer
  100688. * @param onSuccess defines a callback to call on success
  100689. * @param onFailure defines a callback to call on failure
  100690. * @returns the new SceneOptimizer object
  100691. */
  100692. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  100693. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  100694. if (onSuccess) {
  100695. optimizer.onSuccessObservable.add(function () {
  100696. onSuccess();
  100697. });
  100698. }
  100699. if (onFailure) {
  100700. optimizer.onFailureObservable.add(function () {
  100701. onFailure();
  100702. });
  100703. }
  100704. optimizer.start();
  100705. return optimizer;
  100706. };
  100707. return SceneOptimizer;
  100708. }());
  100709. BABYLON.SceneOptimizer = SceneOptimizer;
  100710. })(BABYLON || (BABYLON = {}));
  100711. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  100712. var BABYLON;
  100713. (function (BABYLON) {
  100714. /**
  100715. * Gets the outline renderer associated with the scene
  100716. * @returns a OutlineRenderer
  100717. */
  100718. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  100719. if (!this._outlineRenderer) {
  100720. this._outlineRenderer = new OutlineRenderer(this);
  100721. }
  100722. return this._outlineRenderer;
  100723. };
  100724. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  100725. get: function () {
  100726. return this._renderOutline;
  100727. },
  100728. set: function (value) {
  100729. if (value) {
  100730. // Lazy Load the component.
  100731. this.getScene().getOutlineRenderer();
  100732. }
  100733. this._renderOutline = value;
  100734. },
  100735. enumerable: true,
  100736. configurable: true
  100737. });
  100738. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  100739. get: function () {
  100740. return this._renderOverlay;
  100741. },
  100742. set: function (value) {
  100743. if (value) {
  100744. // Lazy Load the component.
  100745. this.getScene().getOutlineRenderer();
  100746. }
  100747. this._renderOverlay = value;
  100748. },
  100749. enumerable: true,
  100750. configurable: true
  100751. });
  100752. /**
  100753. * This class is responsible to draw bothe outline/overlay of meshes.
  100754. * It should not be used directly but through the available method on mesh.
  100755. */
  100756. var OutlineRenderer = /** @class */ (function () {
  100757. /**
  100758. * Instantiates a new outline renderer. (There could be only one per scene).
  100759. * @param scene Defines the scene it belongs to
  100760. */
  100761. function OutlineRenderer(scene) {
  100762. /**
  100763. * The name of the component. Each component must have a unique name.
  100764. */
  100765. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  100766. /**
  100767. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  100768. */
  100769. this.zOffset = 1;
  100770. this.scene = scene;
  100771. this._engine = scene.getEngine();
  100772. this.scene._addComponent(this);
  100773. }
  100774. /**
  100775. * Register the component to one instance of a scene.
  100776. */
  100777. OutlineRenderer.prototype.register = function () {
  100778. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  100779. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  100780. };
  100781. /**
  100782. * Rebuilds the elements related to this component in case of
  100783. * context lost for instance.
  100784. */
  100785. OutlineRenderer.prototype.rebuild = function () {
  100786. // Nothing to do here.
  100787. };
  100788. /**
  100789. * Disposes the component and the associated ressources.
  100790. */
  100791. OutlineRenderer.prototype.dispose = function () {
  100792. // Nothing to do here.
  100793. };
  100794. /**
  100795. * Renders the outline in the canvas.
  100796. * @param subMesh Defines the sumesh to render
  100797. * @param batch Defines the batch of meshes in case of instances
  100798. * @param useOverlay Defines if the rendering is for the overlay or the outline
  100799. */
  100800. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  100801. var _this = this;
  100802. if (useOverlay === void 0) { useOverlay = false; }
  100803. var scene = this.scene;
  100804. var engine = scene.getEngine();
  100805. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100806. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  100807. return;
  100808. }
  100809. var mesh = subMesh.getRenderingMesh();
  100810. var material = subMesh.getMaterial();
  100811. if (!material || !scene.activeCamera) {
  100812. return;
  100813. }
  100814. engine.enableEffect(this._effect);
  100815. // Logarithmic depth
  100816. if (material.useLogarithmicDepth) {
  100817. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  100818. }
  100819. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  100820. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  100821. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  100822. // Bones
  100823. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100824. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100825. }
  100826. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  100827. // Alpha test
  100828. if (material && material.needAlphaTesting()) {
  100829. var alphaTexture = material.getAlphaTestTexture();
  100830. if (alphaTexture) {
  100831. this._effect.setTexture("diffuseSampler", alphaTexture);
  100832. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  100833. }
  100834. }
  100835. engine.setZOffset(-this.zOffset);
  100836. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  100837. engine.setZOffset(0);
  100838. };
  100839. /**
  100840. * Returns whether or not the outline renderer is ready for a given submesh.
  100841. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  100842. * @param subMesh Defines the submesh to check readyness for
  100843. * @param useInstances Defines wheter wee are trying to render instances or not
  100844. * @returns true if ready otherwise false
  100845. */
  100846. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  100847. var defines = [];
  100848. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  100849. var mesh = subMesh.getMesh();
  100850. var material = subMesh.getMaterial();
  100851. if (material) {
  100852. // Alpha test
  100853. if (material.needAlphaTesting()) {
  100854. defines.push("#define ALPHATEST");
  100855. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100856. attribs.push(BABYLON.VertexBuffer.UVKind);
  100857. defines.push("#define UV1");
  100858. }
  100859. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  100860. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100861. defines.push("#define UV2");
  100862. }
  100863. }
  100864. //Logarithmic depth
  100865. if (material.useLogarithmicDepth) {
  100866. defines.push("#define LOGARITHMICDEPTH");
  100867. }
  100868. }
  100869. // Bones
  100870. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100871. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100872. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100873. if (mesh.numBoneInfluencers > 4) {
  100874. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100875. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100876. }
  100877. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100878. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  100879. }
  100880. else {
  100881. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100882. }
  100883. // Instances
  100884. if (useInstances) {
  100885. defines.push("#define INSTANCES");
  100886. attribs.push("world0");
  100887. attribs.push("world1");
  100888. attribs.push("world2");
  100889. attribs.push("world3");
  100890. }
  100891. // Get correct effect
  100892. var join = defines.join("\n");
  100893. if (this._cachedDefines !== join) {
  100894. this._cachedDefines = join;
  100895. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  100896. }
  100897. return this._effect.isReady();
  100898. };
  100899. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  100900. // Outline - step 1
  100901. this._savedDepthWrite = this._engine.getDepthWrite();
  100902. if (mesh.renderOutline) {
  100903. this._engine.setDepthWrite(false);
  100904. this.render(subMesh, batch);
  100905. this._engine.setDepthWrite(this._savedDepthWrite);
  100906. }
  100907. };
  100908. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  100909. // Outline - step 2
  100910. if (mesh.renderOutline && this._savedDepthWrite) {
  100911. this._engine.setDepthWrite(true);
  100912. this._engine.setColorWrite(false);
  100913. this.render(subMesh, batch);
  100914. this._engine.setColorWrite(true);
  100915. }
  100916. // Overlay
  100917. if (mesh.renderOverlay) {
  100918. var currentMode = this._engine.getAlphaMode();
  100919. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  100920. this.render(subMesh, batch, true);
  100921. this._engine.setAlphaMode(currentMode);
  100922. }
  100923. };
  100924. return OutlineRenderer;
  100925. }());
  100926. BABYLON.OutlineRenderer = OutlineRenderer;
  100927. })(BABYLON || (BABYLON = {}));
  100928. //# sourceMappingURL=babylon.outlineRenderer.js.map
  100929. var BABYLON;
  100930. (function (BABYLON) {
  100931. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  100932. if (this._edgesRenderer) {
  100933. this._edgesRenderer.dispose();
  100934. this._edgesRenderer = null;
  100935. }
  100936. return this;
  100937. };
  100938. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100939. if (epsilon === void 0) { epsilon = 0.95; }
  100940. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100941. this.disableEdgesRendering();
  100942. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100943. return this;
  100944. };
  100945. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  100946. get: function () {
  100947. return this._edgesRenderer;
  100948. },
  100949. enumerable: true,
  100950. configurable: true
  100951. });
  100952. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100953. if (epsilon === void 0) { epsilon = 0.95; }
  100954. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100955. this.disableEdgesRendering();
  100956. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100957. return this;
  100958. };
  100959. /**
  100960. * FaceAdjacencies Helper class to generate edges
  100961. */
  100962. var FaceAdjacencies = /** @class */ (function () {
  100963. function FaceAdjacencies() {
  100964. this.edges = new Array();
  100965. this.edgesConnectedCount = 0;
  100966. }
  100967. return FaceAdjacencies;
  100968. }());
  100969. /**
  100970. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  100971. */
  100972. var EdgesRenderer = /** @class */ (function () {
  100973. /**
  100974. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  100975. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  100976. * @param source Mesh used to create edges
  100977. * @param epsilon sum of angles in adjacency to check for edge
  100978. * @param checkVerticesInsteadOfIndices
  100979. * @param generateEdgesLines - should generate Lines or only prepare resources.
  100980. */
  100981. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  100982. if (epsilon === void 0) { epsilon = 0.95; }
  100983. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100984. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  100985. var _this = this;
  100986. this.edgesWidthScalerForOrthographic = 1000.0;
  100987. this.edgesWidthScalerForPerspective = 50.0;
  100988. this._linesPositions = new Array();
  100989. this._linesNormals = new Array();
  100990. this._linesIndices = new Array();
  100991. this._buffers = {};
  100992. this._checkVerticesInsteadOfIndices = false;
  100993. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  100994. this.isEnabled = true;
  100995. this._source = source;
  100996. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  100997. this._epsilon = epsilon;
  100998. this._prepareRessources();
  100999. if (generateEdgesLines) {
  101000. this._generateEdgesLines();
  101001. }
  101002. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  101003. _this._rebuild();
  101004. });
  101005. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  101006. _this.dispose();
  101007. });
  101008. }
  101009. EdgesRenderer.prototype._prepareRessources = function () {
  101010. if (this._lineShader) {
  101011. return;
  101012. }
  101013. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  101014. attributes: ["position", "normal"],
  101015. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  101016. });
  101017. this._lineShader.disableDepthWrite = true;
  101018. this._lineShader.backFaceCulling = false;
  101019. };
  101020. /** @hidden */
  101021. EdgesRenderer.prototype._rebuild = function () {
  101022. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101023. if (buffer) {
  101024. buffer._rebuild();
  101025. }
  101026. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101027. if (buffer) {
  101028. buffer._rebuild();
  101029. }
  101030. var scene = this._source.getScene();
  101031. var engine = scene.getEngine();
  101032. this._ib = engine.createIndexBuffer(this._linesIndices);
  101033. };
  101034. /**
  101035. * Releases the required resources for the edges renderer
  101036. */
  101037. EdgesRenderer.prototype.dispose = function () {
  101038. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  101039. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  101040. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101041. if (buffer) {
  101042. buffer.dispose();
  101043. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  101044. }
  101045. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101046. if (buffer) {
  101047. buffer.dispose();
  101048. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  101049. }
  101050. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  101051. this._lineShader.dispose();
  101052. };
  101053. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  101054. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  101055. return 0;
  101056. }
  101057. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  101058. return 1;
  101059. }
  101060. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  101061. return 2;
  101062. }
  101063. return -1;
  101064. };
  101065. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  101066. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  101067. return 0;
  101068. }
  101069. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  101070. return 1;
  101071. }
  101072. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  101073. return 2;
  101074. }
  101075. return -1;
  101076. };
  101077. /**
  101078. * Checks if the pair of p0 and p1 is en edge
  101079. * @param faceIndex
  101080. * @param edge
  101081. * @param faceNormals
  101082. * @param p0
  101083. * @param p1
  101084. * @private
  101085. */
  101086. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101087. var needToCreateLine;
  101088. if (edge === undefined) {
  101089. needToCreateLine = true;
  101090. }
  101091. else {
  101092. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  101093. needToCreateLine = dotProduct < this._epsilon;
  101094. }
  101095. if (needToCreateLine) {
  101096. var offset = this._linesPositions.length / 3;
  101097. var normal = p0.subtract(p1);
  101098. normal.normalize();
  101099. // Positions
  101100. this._linesPositions.push(p0.x);
  101101. this._linesPositions.push(p0.y);
  101102. this._linesPositions.push(p0.z);
  101103. this._linesPositions.push(p0.x);
  101104. this._linesPositions.push(p0.y);
  101105. this._linesPositions.push(p0.z);
  101106. this._linesPositions.push(p1.x);
  101107. this._linesPositions.push(p1.y);
  101108. this._linesPositions.push(p1.z);
  101109. this._linesPositions.push(p1.x);
  101110. this._linesPositions.push(p1.y);
  101111. this._linesPositions.push(p1.z);
  101112. // Normals
  101113. this._linesNormals.push(p1.x);
  101114. this._linesNormals.push(p1.y);
  101115. this._linesNormals.push(p1.z);
  101116. this._linesNormals.push(-1);
  101117. this._linesNormals.push(p1.x);
  101118. this._linesNormals.push(p1.y);
  101119. this._linesNormals.push(p1.z);
  101120. this._linesNormals.push(1);
  101121. this._linesNormals.push(p0.x);
  101122. this._linesNormals.push(p0.y);
  101123. this._linesNormals.push(p0.z);
  101124. this._linesNormals.push(-1);
  101125. this._linesNormals.push(p0.x);
  101126. this._linesNormals.push(p0.y);
  101127. this._linesNormals.push(p0.z);
  101128. this._linesNormals.push(1);
  101129. // Indices
  101130. this._linesIndices.push(offset);
  101131. this._linesIndices.push(offset + 1);
  101132. this._linesIndices.push(offset + 2);
  101133. this._linesIndices.push(offset);
  101134. this._linesIndices.push(offset + 2);
  101135. this._linesIndices.push(offset + 3);
  101136. }
  101137. };
  101138. /**
  101139. * Generates lines edges from adjacencjes
  101140. * @private
  101141. */
  101142. EdgesRenderer.prototype._generateEdgesLines = function () {
  101143. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101144. var indices = this._source.getIndices();
  101145. if (!indices || !positions) {
  101146. return;
  101147. }
  101148. // First let's find adjacencies
  101149. var adjacencies = new Array();
  101150. var faceNormals = new Array();
  101151. var index;
  101152. var faceAdjacencies;
  101153. // Prepare faces
  101154. for (index = 0; index < indices.length; index += 3) {
  101155. faceAdjacencies = new FaceAdjacencies();
  101156. var p0Index = indices[index];
  101157. var p1Index = indices[index + 1];
  101158. var p2Index = indices[index + 2];
  101159. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  101160. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  101161. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  101162. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  101163. faceNormal.normalize();
  101164. faceNormals.push(faceNormal);
  101165. adjacencies.push(faceAdjacencies);
  101166. }
  101167. // Scan
  101168. for (index = 0; index < adjacencies.length; index++) {
  101169. faceAdjacencies = adjacencies[index];
  101170. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  101171. var otherFaceAdjacencies = adjacencies[otherIndex];
  101172. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  101173. break;
  101174. }
  101175. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  101176. continue;
  101177. }
  101178. var otherP0 = indices[otherIndex * 3];
  101179. var otherP1 = indices[otherIndex * 3 + 1];
  101180. var otherP2 = indices[otherIndex * 3 + 2];
  101181. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  101182. var otherEdgeIndex = 0;
  101183. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  101184. continue;
  101185. }
  101186. switch (edgeIndex) {
  101187. case 0:
  101188. if (this._checkVerticesInsteadOfIndices) {
  101189. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101190. }
  101191. else {
  101192. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  101193. }
  101194. break;
  101195. case 1:
  101196. if (this._checkVerticesInsteadOfIndices) {
  101197. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101198. }
  101199. else {
  101200. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  101201. }
  101202. break;
  101203. case 2:
  101204. if (this._checkVerticesInsteadOfIndices) {
  101205. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101206. }
  101207. else {
  101208. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  101209. }
  101210. break;
  101211. }
  101212. if (otherEdgeIndex === -1) {
  101213. continue;
  101214. }
  101215. faceAdjacencies.edges[edgeIndex] = otherIndex;
  101216. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  101217. faceAdjacencies.edgesConnectedCount++;
  101218. otherFaceAdjacencies.edgesConnectedCount++;
  101219. if (faceAdjacencies.edgesConnectedCount === 3) {
  101220. break;
  101221. }
  101222. }
  101223. }
  101224. }
  101225. // Create lines
  101226. for (index = 0; index < adjacencies.length; index++) {
  101227. // 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
  101228. var current = adjacencies[index];
  101229. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101230. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  101231. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  101232. }
  101233. // Merge into a single mesh
  101234. var engine = this._source.getScene().getEngine();
  101235. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101236. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101237. this._ib = engine.createIndexBuffer(this._linesIndices);
  101238. this._indicesCount = this._linesIndices.length;
  101239. };
  101240. /**
  101241. * Checks wether or not the edges renderer is ready to render.
  101242. * @return true if ready, otherwise false.
  101243. */
  101244. EdgesRenderer.prototype.isReady = function () {
  101245. return this._lineShader.isReady();
  101246. };
  101247. /**
  101248. * Renders the edges of the attached mesh,
  101249. */
  101250. EdgesRenderer.prototype.render = function () {
  101251. var scene = this._source.getScene();
  101252. if (!this.isReady() || !scene.activeCamera) {
  101253. return;
  101254. }
  101255. var engine = scene.getEngine();
  101256. this._lineShader._preBind();
  101257. if (this._source.edgesColor.a !== 1) {
  101258. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101259. }
  101260. else {
  101261. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  101262. }
  101263. // VBOs
  101264. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  101265. scene.resetCachedMaterial();
  101266. this._lineShader.setColor4("color", this._source.edgesColor);
  101267. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  101268. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  101269. }
  101270. else {
  101271. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  101272. }
  101273. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  101274. this._lineShader.bind(this._source.getWorldMatrix());
  101275. // Draw order
  101276. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  101277. this._lineShader.unbind();
  101278. };
  101279. return EdgesRenderer;
  101280. }());
  101281. BABYLON.EdgesRenderer = EdgesRenderer;
  101282. })(BABYLON || (BABYLON = {}));
  101283. //# sourceMappingURL=babylon.edgesRenderer.js.map
  101284. var BABYLON;
  101285. (function (BABYLON) {
  101286. /**
  101287. * FaceAdjacencies Helper class to generate edges
  101288. */
  101289. var FaceAdjacencies = /** @class */ (function () {
  101290. function FaceAdjacencies() {
  101291. this.edges = new Array();
  101292. this.edgesConnectedCount = 0;
  101293. }
  101294. return FaceAdjacencies;
  101295. }());
  101296. /**
  101297. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  101298. */
  101299. var LineEdgesRenderer = /** @class */ (function (_super) {
  101300. __extends(LineEdgesRenderer, _super);
  101301. /**
  101302. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  101303. * @param source LineMesh used to generate edges
  101304. * @param epsilon not important (specified angle for edge detection)
  101305. * @param checkVerticesInsteadOfIndices not important for LineMesh
  101306. */
  101307. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  101308. if (epsilon === void 0) { epsilon = 0.95; }
  101309. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101310. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  101311. _this._generateEdgesLines();
  101312. return _this;
  101313. }
  101314. /**
  101315. * Always create the edge since its a line so only important things are p0 and p1
  101316. * @param faceIndex not important for LineMesh
  101317. * @param edge not important for LineMesh
  101318. * @param faceNormals not important for LineMesh
  101319. * @param p0 beginnig of line
  101320. * @param p1 end of line
  101321. */
  101322. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101323. var offset = this._linesPositions.length / 3;
  101324. var normal = p0.subtract(p1);
  101325. normal.normalize();
  101326. // Positions
  101327. this._linesPositions.push(p0.x);
  101328. this._linesPositions.push(p0.y);
  101329. this._linesPositions.push(p0.z);
  101330. this._linesPositions.push(p0.x);
  101331. this._linesPositions.push(p0.y);
  101332. this._linesPositions.push(p0.z);
  101333. this._linesPositions.push(p1.x);
  101334. this._linesPositions.push(p1.y);
  101335. this._linesPositions.push(p1.z);
  101336. this._linesPositions.push(p1.x);
  101337. this._linesPositions.push(p1.y);
  101338. this._linesPositions.push(p1.z);
  101339. // Normals
  101340. this._linesNormals.push(p1.x);
  101341. this._linesNormals.push(p1.y);
  101342. this._linesNormals.push(p1.z);
  101343. this._linesNormals.push(-1);
  101344. this._linesNormals.push(p1.x);
  101345. this._linesNormals.push(p1.y);
  101346. this._linesNormals.push(p1.z);
  101347. this._linesNormals.push(1);
  101348. this._linesNormals.push(p0.x);
  101349. this._linesNormals.push(p0.y);
  101350. this._linesNormals.push(p0.z);
  101351. this._linesNormals.push(-1);
  101352. this._linesNormals.push(p0.x);
  101353. this._linesNormals.push(p0.y);
  101354. this._linesNormals.push(p0.z);
  101355. this._linesNormals.push(1);
  101356. // Indices
  101357. this._linesIndices.push(offset);
  101358. this._linesIndices.push(offset + 1);
  101359. this._linesIndices.push(offset + 2);
  101360. this._linesIndices.push(offset);
  101361. this._linesIndices.push(offset + 2);
  101362. this._linesIndices.push(offset + 3);
  101363. };
  101364. /**
  101365. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  101366. */
  101367. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  101368. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101369. var indices = this._source.getIndices();
  101370. if (!indices || !positions) {
  101371. return;
  101372. }
  101373. // First let's find adjacencies
  101374. var adjacencies = new Array();
  101375. var faceNormals = new Array();
  101376. var index;
  101377. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  101378. var currentAdjecancy = new FaceAdjacencies();
  101379. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  101380. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  101381. adjacencies.push(currentAdjecancy);
  101382. }
  101383. // Create lines
  101384. for (index = 0; index < adjacencies.length; index++) {
  101385. // 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
  101386. var current = adjacencies[index];
  101387. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101388. }
  101389. // Merge into a single mesh
  101390. var engine = this._source.getScene().getEngine();
  101391. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101392. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101393. this._ib = engine.createIndexBuffer(this._linesIndices);
  101394. this._indicesCount = this._linesIndices.length;
  101395. };
  101396. return LineEdgesRenderer;
  101397. }(BABYLON.EdgesRenderer));
  101398. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  101399. })(BABYLON || (BABYLON = {}));
  101400. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  101401. var BABYLON;
  101402. (function (BABYLON) {
  101403. // Adds the parser to the scene parsers.
  101404. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  101405. if (parsedData.effectLayers) {
  101406. if (!container.effectLayers) {
  101407. container.effectLayers = new Array();
  101408. }
  101409. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  101410. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  101411. container.effectLayers.push(effectLayer);
  101412. }
  101413. }
  101414. });
  101415. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  101416. var index = this.effectLayers.indexOf(toRemove);
  101417. if (index !== -1) {
  101418. this.effectLayers.splice(index, 1);
  101419. }
  101420. return index;
  101421. };
  101422. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  101423. this.effectLayers.push(newEffectLayer);
  101424. };
  101425. /**
  101426. * Defines the layer scene component responsible to manage any effect layers
  101427. * in a given scene.
  101428. */
  101429. var EffectLayerSceneComponent = /** @class */ (function () {
  101430. /**
  101431. * Creates a new instance of the component for the given scene
  101432. * @param scene Defines the scene to register the component in
  101433. */
  101434. function EffectLayerSceneComponent(scene) {
  101435. /**
  101436. * The component name helpfull to identify the component in the list of scene components.
  101437. */
  101438. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  101439. this._renderEffects = false;
  101440. this._needStencil = false;
  101441. this._previousStencilState = false;
  101442. this.scene = scene;
  101443. this._engine = scene.getEngine();
  101444. scene.effectLayers = new Array();
  101445. }
  101446. /**
  101447. * Registers the component in a given scene
  101448. */
  101449. EffectLayerSceneComponent.prototype.register = function () {
  101450. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  101451. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  101452. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  101453. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  101454. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  101455. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  101456. };
  101457. /**
  101458. * Rebuilds the elements related to this component in case of
  101459. * context lost for instance.
  101460. */
  101461. EffectLayerSceneComponent.prototype.rebuild = function () {
  101462. var layers = this.scene.effectLayers;
  101463. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  101464. var effectLayer = layers_1[_i];
  101465. effectLayer._rebuild();
  101466. }
  101467. };
  101468. /**
  101469. * Serializes the component data to the specified json object
  101470. * @param serializationObject The object to serialize to
  101471. */
  101472. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  101473. // Effect layers
  101474. serializationObject.effectLayers = [];
  101475. var layers = this.scene.effectLayers;
  101476. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  101477. var effectLayer = layers_2[_i];
  101478. if (effectLayer.serialize) {
  101479. serializationObject.effectLayers.push(effectLayer.serialize());
  101480. }
  101481. }
  101482. };
  101483. /**
  101484. * Adds all the element from the container to the scene
  101485. * @param container the container holding the elements
  101486. */
  101487. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  101488. var _this = this;
  101489. if (!container.effectLayers) {
  101490. return;
  101491. }
  101492. container.effectLayers.forEach(function (o) {
  101493. _this.scene.addEffectLayer(o);
  101494. });
  101495. };
  101496. /**
  101497. * Removes all the elements in the container from the scene
  101498. * @param container contains the elements to remove
  101499. */
  101500. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  101501. var _this = this;
  101502. if (!container.effectLayers) {
  101503. return;
  101504. }
  101505. container.effectLayers.forEach(function (o) {
  101506. _this.scene.removeEffectLayer(o);
  101507. });
  101508. };
  101509. /**
  101510. * Disposes the component and the associated ressources.
  101511. */
  101512. EffectLayerSceneComponent.prototype.dispose = function () {
  101513. var layers = this.scene.effectLayers;
  101514. while (layers.length) {
  101515. layers[0].dispose();
  101516. }
  101517. };
  101518. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  101519. var layers = this.scene.effectLayers;
  101520. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  101521. var layer = layers_3[_i];
  101522. if (!layer.hasMesh(mesh)) {
  101523. continue;
  101524. }
  101525. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  101526. var subMesh = _b[_a];
  101527. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  101528. return false;
  101529. }
  101530. }
  101531. }
  101532. return true;
  101533. };
  101534. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  101535. this._renderEffects = false;
  101536. this._needStencil = false;
  101537. var layers = this.scene.effectLayers;
  101538. if (layers && layers.length > 0) {
  101539. this._previousStencilState = this._engine.getStencilBuffer();
  101540. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  101541. var effectLayer = layers_4[_i];
  101542. if (effectLayer.shouldRender() &&
  101543. (!effectLayer.camera ||
  101544. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  101545. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  101546. this._renderEffects = true;
  101547. this._needStencil = this._needStencil || effectLayer.needStencil();
  101548. var renderTarget = effectLayer._mainTexture;
  101549. if (renderTarget._shouldRender()) {
  101550. this.scene.incrementRenderId();
  101551. renderTarget.render(false, false);
  101552. }
  101553. }
  101554. }
  101555. this.scene.incrementRenderId();
  101556. }
  101557. };
  101558. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  101559. // Activate effect Layer stencil
  101560. if (this._needStencil) {
  101561. this._engine.setStencilBuffer(true);
  101562. }
  101563. };
  101564. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  101565. // Restore effect Layer stencil
  101566. if (this._needStencil) {
  101567. this._engine.setStencilBuffer(this._previousStencilState);
  101568. }
  101569. };
  101570. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  101571. if (this._renderEffects) {
  101572. this._engine.setDepthBuffer(false);
  101573. var layers = this.scene.effectLayers;
  101574. for (var i = 0; i < layers.length; i++) {
  101575. var effectLayer = layers[i];
  101576. if (effectLayer.renderingGroupId === renderingGroupId) {
  101577. if (effectLayer.shouldRender()) {
  101578. effectLayer.render();
  101579. }
  101580. }
  101581. }
  101582. this._engine.setDepthBuffer(true);
  101583. }
  101584. };
  101585. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  101586. if (this._renderEffects) {
  101587. this._draw(-1);
  101588. }
  101589. };
  101590. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  101591. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  101592. this._draw(index);
  101593. }
  101594. };
  101595. return EffectLayerSceneComponent;
  101596. }());
  101597. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  101598. })(BABYLON || (BABYLON = {}));
  101599. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  101600. var __assign = (this && this.__assign) || function () {
  101601. __assign = Object.assign || function(t) {
  101602. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101603. s = arguments[i];
  101604. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101605. t[p] = s[p];
  101606. }
  101607. return t;
  101608. };
  101609. return __assign.apply(this, arguments);
  101610. };
  101611. var BABYLON;
  101612. (function (BABYLON) {
  101613. /**
  101614. * The effect layer Helps adding post process effect blended with the main pass.
  101615. *
  101616. * This can be for instance use to generate glow or higlight effects on the scene.
  101617. *
  101618. * The effect layer class can not be used directly and is intented to inherited from to be
  101619. * customized per effects.
  101620. */
  101621. var EffectLayer = /** @class */ (function () {
  101622. /**
  101623. * Instantiates a new effect Layer and references it in the scene.
  101624. * @param name The name of the layer
  101625. * @param scene The scene to use the layer in
  101626. */
  101627. function EffectLayer(
  101628. /** The Friendly of the effect in the scene */
  101629. name, scene) {
  101630. this._vertexBuffers = {};
  101631. this._maxSize = 0;
  101632. this._mainTextureDesiredSize = { width: 0, height: 0 };
  101633. this._shouldRender = true;
  101634. this._postProcesses = [];
  101635. this._textures = [];
  101636. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  101637. /**
  101638. * The clear color of the texture used to generate the glow map.
  101639. */
  101640. this.neutralColor = new BABYLON.Color4();
  101641. /**
  101642. * Specifies wether the highlight layer is enabled or not.
  101643. */
  101644. this.isEnabled = true;
  101645. /**
  101646. * An event triggered when the effect layer has been disposed.
  101647. */
  101648. this.onDisposeObservable = new BABYLON.Observable();
  101649. /**
  101650. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  101651. */
  101652. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  101653. /**
  101654. * An event triggered when the generated texture is being merged in the scene.
  101655. */
  101656. this.onBeforeComposeObservable = new BABYLON.Observable();
  101657. /**
  101658. * An event triggered when the generated texture has been merged in the scene.
  101659. */
  101660. this.onAfterComposeObservable = new BABYLON.Observable();
  101661. /**
  101662. * An event triggered when the efffect layer changes its size.
  101663. */
  101664. this.onSizeChangedObservable = new BABYLON.Observable();
  101665. this.name = name;
  101666. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101667. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  101668. if (!component) {
  101669. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  101670. this._scene._addComponent(component);
  101671. }
  101672. this._engine = this._scene.getEngine();
  101673. this._maxSize = this._engine.getCaps().maxTextureSize;
  101674. this._scene.effectLayers.push(this);
  101675. // Generate Buffers
  101676. this._generateIndexBuffer();
  101677. this._genrateVertexBuffer();
  101678. }
  101679. Object.defineProperty(EffectLayer.prototype, "camera", {
  101680. /**
  101681. * Gets the camera attached to the layer.
  101682. */
  101683. get: function () {
  101684. return this._effectLayerOptions.camera;
  101685. },
  101686. enumerable: true,
  101687. configurable: true
  101688. });
  101689. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  101690. /**
  101691. * Gets the rendering group id the layer should render in.
  101692. */
  101693. get: function () {
  101694. return this._effectLayerOptions.renderingGroupId;
  101695. },
  101696. enumerable: true,
  101697. configurable: true
  101698. });
  101699. /**
  101700. * Initializes the effect layer with the required options.
  101701. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  101702. */
  101703. EffectLayer.prototype._init = function (options) {
  101704. // Adapt options
  101705. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  101706. this._setMainTextureSize();
  101707. this._createMainTexture();
  101708. this._createTextureAndPostProcesses();
  101709. this._mergeEffect = this._createMergeEffect();
  101710. };
  101711. /**
  101712. * Generates the index buffer of the full screen quad blending to the main canvas.
  101713. */
  101714. EffectLayer.prototype._generateIndexBuffer = function () {
  101715. // Indices
  101716. var indices = [];
  101717. indices.push(0);
  101718. indices.push(1);
  101719. indices.push(2);
  101720. indices.push(0);
  101721. indices.push(2);
  101722. indices.push(3);
  101723. this._indexBuffer = this._engine.createIndexBuffer(indices);
  101724. };
  101725. /**
  101726. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  101727. */
  101728. EffectLayer.prototype._genrateVertexBuffer = function () {
  101729. // VBO
  101730. var vertices = [];
  101731. vertices.push(1, 1);
  101732. vertices.push(-1, 1);
  101733. vertices.push(-1, -1);
  101734. vertices.push(1, -1);
  101735. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  101736. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  101737. };
  101738. /**
  101739. * Sets the main texture desired size which is the closest power of two
  101740. * of the engine canvas size.
  101741. */
  101742. EffectLayer.prototype._setMainTextureSize = function () {
  101743. if (this._effectLayerOptions.mainTextureFixedSize) {
  101744. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  101745. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  101746. }
  101747. else {
  101748. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  101749. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  101750. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  101751. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  101752. }
  101753. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  101754. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  101755. };
  101756. /**
  101757. * Creates the main texture for the effect layer.
  101758. */
  101759. EffectLayer.prototype._createMainTexture = function () {
  101760. var _this = this;
  101761. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  101762. width: this._mainTextureDesiredSize.width,
  101763. height: this._mainTextureDesiredSize.height
  101764. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  101765. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  101766. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101767. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101768. this._mainTexture.anisotropicFilteringLevel = 1;
  101769. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101770. this._mainTexture.renderParticles = false;
  101771. this._mainTexture.renderList = null;
  101772. this._mainTexture.ignoreCameraViewport = true;
  101773. // Custom render function
  101774. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  101775. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  101776. var index;
  101777. var engine = _this._scene.getEngine();
  101778. if (depthOnlySubMeshes.length) {
  101779. engine.setColorWrite(false);
  101780. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  101781. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  101782. }
  101783. engine.setColorWrite(true);
  101784. }
  101785. for (index = 0; index < opaqueSubMeshes.length; index++) {
  101786. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  101787. }
  101788. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  101789. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  101790. }
  101791. for (index = 0; index < transparentSubMeshes.length; index++) {
  101792. _this._renderSubMesh(transparentSubMeshes.data[index]);
  101793. }
  101794. };
  101795. this._mainTexture.onClearObservable.add(function (engine) {
  101796. engine.clear(_this.neutralColor, true, true, true);
  101797. });
  101798. };
  101799. /**
  101800. * Checks for the readiness of the element composing the layer.
  101801. * @param subMesh the mesh to check for
  101802. * @param useInstances specify wether or not to use instances to render the mesh
  101803. * @param emissiveTexture the associated emissive texture used to generate the glow
  101804. * @return true if ready otherwise, false
  101805. */
  101806. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  101807. var material = subMesh.getMaterial();
  101808. if (!material) {
  101809. return false;
  101810. }
  101811. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  101812. return false;
  101813. }
  101814. var defines = [];
  101815. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101816. var mesh = subMesh.getMesh();
  101817. var uv1 = false;
  101818. var uv2 = false;
  101819. // Alpha test
  101820. if (material && material.needAlphaTesting()) {
  101821. var alphaTexture = material.getAlphaTestTexture();
  101822. if (alphaTexture) {
  101823. defines.push("#define ALPHATEST");
  101824. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101825. alphaTexture.coordinatesIndex === 1) {
  101826. defines.push("#define DIFFUSEUV2");
  101827. uv2 = true;
  101828. }
  101829. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101830. defines.push("#define DIFFUSEUV1");
  101831. uv1 = true;
  101832. }
  101833. }
  101834. }
  101835. // Emissive
  101836. if (emissiveTexture) {
  101837. defines.push("#define EMISSIVE");
  101838. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101839. emissiveTexture.coordinatesIndex === 1) {
  101840. defines.push("#define EMISSIVEUV2");
  101841. uv2 = true;
  101842. }
  101843. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101844. defines.push("#define EMISSIVEUV1");
  101845. uv1 = true;
  101846. }
  101847. }
  101848. if (uv1) {
  101849. attribs.push(BABYLON.VertexBuffer.UVKind);
  101850. defines.push("#define UV1");
  101851. }
  101852. if (uv2) {
  101853. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101854. defines.push("#define UV2");
  101855. }
  101856. // Bones
  101857. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101858. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101859. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101860. if (mesh.numBoneInfluencers > 4) {
  101861. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101862. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101863. }
  101864. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101865. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  101866. }
  101867. else {
  101868. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101869. }
  101870. // Morph targets
  101871. var manager = mesh.morphTargetManager;
  101872. var morphInfluencers = 0;
  101873. if (manager) {
  101874. if (manager.numInfluencers > 0) {
  101875. defines.push("#define MORPHTARGETS");
  101876. morphInfluencers = manager.numInfluencers;
  101877. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  101878. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  101879. }
  101880. }
  101881. // Instances
  101882. if (useInstances) {
  101883. defines.push("#define INSTANCES");
  101884. attribs.push("world0");
  101885. attribs.push("world1");
  101886. attribs.push("world2");
  101887. attribs.push("world3");
  101888. }
  101889. // Get correct effect
  101890. var join = defines.join("\n");
  101891. if (this._cachedDefines !== join) {
  101892. this._cachedDefines = join;
  101893. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  101894. }
  101895. return this._effectLayerMapGenerationEffect.isReady();
  101896. };
  101897. /**
  101898. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  101899. */
  101900. EffectLayer.prototype.render = function () {
  101901. var currentEffect = this._mergeEffect;
  101902. // Check
  101903. if (!currentEffect.isReady())
  101904. return;
  101905. for (var i = 0; i < this._postProcesses.length; i++) {
  101906. if (!this._postProcesses[i].isReady()) {
  101907. return;
  101908. }
  101909. }
  101910. var engine = this._scene.getEngine();
  101911. this.onBeforeComposeObservable.notifyObservers(this);
  101912. // Render
  101913. engine.enableEffect(currentEffect);
  101914. engine.setState(false);
  101915. // VBOs
  101916. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  101917. // Cache
  101918. var previousAlphaMode = engine.getAlphaMode();
  101919. // Go Blend.
  101920. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  101921. // Blends the map on the main canvas.
  101922. this._internalRender(currentEffect);
  101923. // Restore Alpha
  101924. engine.setAlphaMode(previousAlphaMode);
  101925. this.onAfterComposeObservable.notifyObservers(this);
  101926. // Handle size changes.
  101927. var size = this._mainTexture.getSize();
  101928. this._setMainTextureSize();
  101929. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  101930. // Recreate RTT and post processes on size change.
  101931. this.onSizeChangedObservable.notifyObservers(this);
  101932. this._disposeTextureAndPostProcesses();
  101933. this._createMainTexture();
  101934. this._createTextureAndPostProcesses();
  101935. }
  101936. };
  101937. /**
  101938. * Determine if a given mesh will be used in the current effect.
  101939. * @param mesh mesh to test
  101940. * @returns true if the mesh will be used
  101941. */
  101942. EffectLayer.prototype.hasMesh = function (mesh) {
  101943. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  101944. return true;
  101945. }
  101946. return false;
  101947. };
  101948. /**
  101949. * Returns true if the layer contains information to display, otherwise false.
  101950. * @returns true if the glow layer should be rendered
  101951. */
  101952. EffectLayer.prototype.shouldRender = function () {
  101953. return this.isEnabled && this._shouldRender;
  101954. };
  101955. /**
  101956. * Returns true if the mesh should render, otherwise false.
  101957. * @param mesh The mesh to render
  101958. * @returns true if it should render otherwise false
  101959. */
  101960. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  101961. return true;
  101962. };
  101963. /**
  101964. * Returns true if the mesh should render, otherwise false.
  101965. * @param mesh The mesh to render
  101966. * @returns true if it should render otherwise false
  101967. */
  101968. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  101969. return true;
  101970. };
  101971. /**
  101972. * Renders the submesh passed in parameter to the generation map.
  101973. */
  101974. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  101975. var _this = this;
  101976. if (!this.shouldRender()) {
  101977. return;
  101978. }
  101979. var material = subMesh.getMaterial();
  101980. var mesh = subMesh.getRenderingMesh();
  101981. var scene = this._scene;
  101982. var engine = scene.getEngine();
  101983. if (!material) {
  101984. return;
  101985. }
  101986. // Do not block in blend mode.
  101987. if (material.needAlphaBlendingForMesh(mesh)) {
  101988. return;
  101989. }
  101990. // Culling
  101991. engine.setState(material.backFaceCulling);
  101992. // Managing instances
  101993. var batch = mesh._getInstancesRenderList(subMesh._id);
  101994. if (batch.mustReturn) {
  101995. return;
  101996. }
  101997. // Early Exit per mesh
  101998. if (!this._shouldRenderMesh(mesh)) {
  101999. return;
  102000. }
  102001. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  102002. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  102003. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  102004. engine.enableEffect(this._effectLayerMapGenerationEffect);
  102005. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  102006. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  102007. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  102008. // Alpha test
  102009. if (material && material.needAlphaTesting()) {
  102010. var alphaTexture = material.getAlphaTestTexture();
  102011. if (alphaTexture) {
  102012. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  102013. var textureMatrix = alphaTexture.getTextureMatrix();
  102014. if (textureMatrix) {
  102015. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  102016. }
  102017. }
  102018. }
  102019. // Glow emissive only
  102020. if (this._emissiveTextureAndColor.texture) {
  102021. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  102022. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  102023. }
  102024. // Bones
  102025. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  102026. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  102027. }
  102028. // Morph targets
  102029. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  102030. // Draw
  102031. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  102032. }
  102033. else {
  102034. // Need to reset refresh rate of the main map
  102035. this._mainTexture.resetRefreshCounter();
  102036. }
  102037. };
  102038. /**
  102039. * Rebuild the required buffers.
  102040. * @hidden Internal use only.
  102041. */
  102042. EffectLayer.prototype._rebuild = function () {
  102043. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102044. if (vb) {
  102045. vb._rebuild();
  102046. }
  102047. this._generateIndexBuffer();
  102048. };
  102049. /**
  102050. * Dispose only the render target textures and post process.
  102051. */
  102052. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  102053. this._mainTexture.dispose();
  102054. for (var i = 0; i < this._postProcesses.length; i++) {
  102055. if (this._postProcesses[i]) {
  102056. this._postProcesses[i].dispose();
  102057. }
  102058. }
  102059. this._postProcesses = [];
  102060. for (var i = 0; i < this._textures.length; i++) {
  102061. if (this._textures[i]) {
  102062. this._textures[i].dispose();
  102063. }
  102064. }
  102065. this._textures = [];
  102066. };
  102067. /**
  102068. * Dispose the highlight layer and free resources.
  102069. */
  102070. EffectLayer.prototype.dispose = function () {
  102071. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102072. if (vertexBuffer) {
  102073. vertexBuffer.dispose();
  102074. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102075. }
  102076. if (this._indexBuffer) {
  102077. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102078. this._indexBuffer = null;
  102079. }
  102080. // Clean textures and post processes
  102081. this._disposeTextureAndPostProcesses();
  102082. // Remove from scene
  102083. var index = this._scene.effectLayers.indexOf(this, 0);
  102084. if (index > -1) {
  102085. this._scene.effectLayers.splice(index, 1);
  102086. }
  102087. // Callback
  102088. this.onDisposeObservable.notifyObservers(this);
  102089. this.onDisposeObservable.clear();
  102090. this.onBeforeRenderMainTextureObservable.clear();
  102091. this.onBeforeComposeObservable.clear();
  102092. this.onAfterComposeObservable.clear();
  102093. this.onSizeChangedObservable.clear();
  102094. };
  102095. /**
  102096. * Gets the class name of the effect layer
  102097. * @returns the string with the class name of the effect layer
  102098. */
  102099. EffectLayer.prototype.getClassName = function () {
  102100. return "EffectLayer";
  102101. };
  102102. /**
  102103. * Creates an effect layer from parsed effect layer data
  102104. * @param parsedEffectLayer defines effect layer data
  102105. * @param scene defines the current scene
  102106. * @param rootUrl defines the root URL containing the effect layer information
  102107. * @returns a parsed effect Layer
  102108. */
  102109. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  102110. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  102111. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  102112. };
  102113. __decorate([
  102114. BABYLON.serialize()
  102115. ], EffectLayer.prototype, "name", void 0);
  102116. __decorate([
  102117. BABYLON.serializeAsColor4()
  102118. ], EffectLayer.prototype, "neutralColor", void 0);
  102119. __decorate([
  102120. BABYLON.serialize()
  102121. ], EffectLayer.prototype, "isEnabled", void 0);
  102122. __decorate([
  102123. BABYLON.serializeAsCameraReference()
  102124. ], EffectLayer.prototype, "camera", null);
  102125. __decorate([
  102126. BABYLON.serialize()
  102127. ], EffectLayer.prototype, "renderingGroupId", null);
  102128. return EffectLayer;
  102129. }());
  102130. BABYLON.EffectLayer = EffectLayer;
  102131. })(BABYLON || (BABYLON = {}));
  102132. //# sourceMappingURL=babylon.effectLayer.js.map
  102133. var BABYLON;
  102134. (function (BABYLON) {
  102135. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  102136. for (var index = 0; index < this.effectLayers.length; index++) {
  102137. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  102138. return this.effectLayers[index];
  102139. }
  102140. }
  102141. return null;
  102142. };
  102143. /**
  102144. * Special Glow Blur post process only blurring the alpha channel
  102145. * It enforces keeping the most luminous color in the color channel.
  102146. */
  102147. var GlowBlurPostProcess = /** @class */ (function (_super) {
  102148. __extends(GlowBlurPostProcess, _super);
  102149. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  102150. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  102151. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  102152. _this.direction = direction;
  102153. _this.kernel = kernel;
  102154. _this.onApplyObservable.add(function (effect) {
  102155. effect.setFloat2("screenSize", _this.width, _this.height);
  102156. effect.setVector2("direction", _this.direction);
  102157. effect.setFloat("blurWidth", _this.kernel);
  102158. });
  102159. return _this;
  102160. }
  102161. return GlowBlurPostProcess;
  102162. }(BABYLON.PostProcess));
  102163. /**
  102164. * The highlight layer Helps adding a glow effect around a mesh.
  102165. *
  102166. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102167. * glowy meshes to your scene.
  102168. *
  102169. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  102170. */
  102171. var HighlightLayer = /** @class */ (function (_super) {
  102172. __extends(HighlightLayer, _super);
  102173. /**
  102174. * Instantiates a new highlight Layer and references it to the scene..
  102175. * @param name The name of the layer
  102176. * @param scene The scene to use the layer in
  102177. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  102178. */
  102179. function HighlightLayer(name, scene, options) {
  102180. var _this = _super.call(this, name, scene) || this;
  102181. _this.name = name;
  102182. /**
  102183. * Specifies whether or not the inner glow is ACTIVE in the layer.
  102184. */
  102185. _this.innerGlow = true;
  102186. /**
  102187. * Specifies whether or not the outer glow is ACTIVE in the layer.
  102188. */
  102189. _this.outerGlow = true;
  102190. /**
  102191. * An event triggered when the highlight layer is being blurred.
  102192. */
  102193. _this.onBeforeBlurObservable = new BABYLON.Observable();
  102194. /**
  102195. * An event triggered when the highlight layer has been blurred.
  102196. */
  102197. _this.onAfterBlurObservable = new BABYLON.Observable();
  102198. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  102199. _this._meshes = {};
  102200. _this._excludedMeshes = {};
  102201. _this.neutralColor = HighlightLayer.NeutralColor;
  102202. // Warn on stencil
  102203. if (!_this._engine.isStencilEnable) {
  102204. 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 }");
  102205. }
  102206. // Adapt options
  102207. _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);
  102208. // Initialize the layer
  102209. _this._init({
  102210. alphaBlendingMode: _this._options.alphaBlendingMode,
  102211. camera: _this._options.camera,
  102212. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102213. mainTextureRatio: _this._options.mainTextureRatio,
  102214. renderingGroupId: _this._options.renderingGroupId
  102215. });
  102216. // Do not render as long as no meshes have been added
  102217. _this._shouldRender = false;
  102218. return _this;
  102219. }
  102220. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  102221. /**
  102222. * Gets the horizontal size of the blur.
  102223. */
  102224. get: function () {
  102225. return this._horizontalBlurPostprocess.kernel;
  102226. },
  102227. /**
  102228. * Specifies the horizontal size of the blur.
  102229. */
  102230. set: function (value) {
  102231. this._horizontalBlurPostprocess.kernel = value;
  102232. },
  102233. enumerable: true,
  102234. configurable: true
  102235. });
  102236. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  102237. /**
  102238. * Gets the vertical size of the blur.
  102239. */
  102240. get: function () {
  102241. return this._verticalBlurPostprocess.kernel;
  102242. },
  102243. /**
  102244. * Specifies the vertical size of the blur.
  102245. */
  102246. set: function (value) {
  102247. this._verticalBlurPostprocess.kernel = value;
  102248. },
  102249. enumerable: true,
  102250. configurable: true
  102251. });
  102252. /**
  102253. * Get the effect name of the layer.
  102254. * @return The effect name
  102255. */
  102256. HighlightLayer.prototype.getEffectName = function () {
  102257. return HighlightLayer.EffectName;
  102258. };
  102259. /**
  102260. * Create the merge effect. This is the shader use to blit the information back
  102261. * to the main canvas at the end of the scene rendering.
  102262. */
  102263. HighlightLayer.prototype._createMergeEffect = function () {
  102264. // Effect
  102265. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  102266. };
  102267. /**
  102268. * Creates the render target textures and post processes used in the highlight layer.
  102269. */
  102270. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  102271. var _this = this;
  102272. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  102273. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  102274. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102275. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102276. var textureType = 0;
  102277. if (this._engine.getCaps().textureHalfFloatRender) {
  102278. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102279. }
  102280. else {
  102281. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102282. }
  102283. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  102284. width: blurTextureWidth,
  102285. height: blurTextureHeight
  102286. }, this._scene, false, true, textureType);
  102287. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102288. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102289. this._blurTexture.anisotropicFilteringLevel = 16;
  102290. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  102291. this._blurTexture.renderParticles = false;
  102292. this._blurTexture.ignoreCameraViewport = true;
  102293. this._textures = [this._blurTexture];
  102294. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  102295. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102296. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  102297. effect.setTexture("textureSampler", _this._mainTexture);
  102298. });
  102299. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102300. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102301. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102302. });
  102303. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102304. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  102305. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102306. });
  102307. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102308. }
  102309. else {
  102310. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  102311. width: blurTextureWidth,
  102312. height: blurTextureHeight
  102313. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102314. this._horizontalBlurPostprocess.width = blurTextureWidth;
  102315. this._horizontalBlurPostprocess.height = blurTextureHeight;
  102316. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102317. effect.setTexture("textureSampler", _this._mainTexture);
  102318. });
  102319. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  102320. width: blurTextureWidth,
  102321. height: blurTextureHeight
  102322. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102323. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102324. }
  102325. this._mainTexture.onAfterUnbindObservable.add(function () {
  102326. _this.onBeforeBlurObservable.notifyObservers(_this);
  102327. var internalTexture = _this._blurTexture.getInternalTexture();
  102328. if (internalTexture) {
  102329. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  102330. }
  102331. _this.onAfterBlurObservable.notifyObservers(_this);
  102332. });
  102333. // Prevent autoClear.
  102334. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102335. };
  102336. /**
  102337. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102338. */
  102339. HighlightLayer.prototype.needStencil = function () {
  102340. return true;
  102341. };
  102342. /**
  102343. * Checks for the readiness of the element composing the layer.
  102344. * @param subMesh the mesh to check for
  102345. * @param useInstances specify wether or not to use instances to render the mesh
  102346. * @param emissiveTexture the associated emissive texture used to generate the glow
  102347. * @return true if ready otherwise, false
  102348. */
  102349. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  102350. var material = subMesh.getMaterial();
  102351. var mesh = subMesh.getRenderingMesh();
  102352. if (!material || !mesh || !this._meshes) {
  102353. return false;
  102354. }
  102355. var emissiveTexture = null;
  102356. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102357. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102358. emissiveTexture = material.emissiveTexture;
  102359. }
  102360. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102361. };
  102362. /**
  102363. * Implementation specific of rendering the generating effect on the main canvas.
  102364. * @param effect The effect used to render through
  102365. */
  102366. HighlightLayer.prototype._internalRender = function (effect) {
  102367. // Texture
  102368. effect.setTexture("textureSampler", this._blurTexture);
  102369. // Cache
  102370. var engine = this._engine;
  102371. var previousStencilBuffer = engine.getStencilBuffer();
  102372. var previousStencilFunction = engine.getStencilFunction();
  102373. var previousStencilMask = engine.getStencilMask();
  102374. var previousStencilOperationPass = engine.getStencilOperationPass();
  102375. var previousStencilOperationFail = engine.getStencilOperationFail();
  102376. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  102377. var previousStencilReference = engine.getStencilFunctionReference();
  102378. // Stencil operations
  102379. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  102380. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  102381. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  102382. // Draw order
  102383. engine.setStencilMask(0x00);
  102384. engine.setStencilBuffer(true);
  102385. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  102386. // 2 passes inner outer
  102387. if (this.outerGlow) {
  102388. effect.setFloat("offset", 0);
  102389. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  102390. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102391. }
  102392. if (this.innerGlow) {
  102393. effect.setFloat("offset", 1);
  102394. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  102395. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102396. }
  102397. // Restore Cache
  102398. engine.setStencilFunction(previousStencilFunction);
  102399. engine.setStencilMask(previousStencilMask);
  102400. engine.setStencilBuffer(previousStencilBuffer);
  102401. engine.setStencilOperationPass(previousStencilOperationPass);
  102402. engine.setStencilOperationFail(previousStencilOperationFail);
  102403. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  102404. engine.setStencilFunctionReference(previousStencilReference);
  102405. };
  102406. /**
  102407. * Returns true if the layer contains information to display, otherwise false.
  102408. */
  102409. HighlightLayer.prototype.shouldRender = function () {
  102410. if (_super.prototype.shouldRender.call(this)) {
  102411. return this._meshes ? true : false;
  102412. }
  102413. return false;
  102414. };
  102415. /**
  102416. * Returns true if the mesh should render, otherwise false.
  102417. * @param mesh The mesh to render
  102418. * @returns true if it should render otherwise false
  102419. */
  102420. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  102421. // Excluded Mesh
  102422. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  102423. return false;
  102424. }
  102425. ;
  102426. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102427. return false;
  102428. }
  102429. return true;
  102430. };
  102431. /**
  102432. * Sets the required values for both the emissive texture and and the main color.
  102433. */
  102434. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102435. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102436. if (highlightLayerMesh) {
  102437. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  102438. }
  102439. else {
  102440. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102441. }
  102442. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102443. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102444. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  102445. }
  102446. else {
  102447. this._emissiveTextureAndColor.texture = null;
  102448. }
  102449. };
  102450. /**
  102451. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  102452. * @param mesh The mesh to exclude from the highlight layer
  102453. */
  102454. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  102455. if (!this._excludedMeshes) {
  102456. return;
  102457. }
  102458. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  102459. if (!meshExcluded) {
  102460. this._excludedMeshes[mesh.uniqueId] = {
  102461. mesh: mesh,
  102462. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  102463. mesh.getEngine().setStencilBuffer(false);
  102464. }),
  102465. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  102466. mesh.getEngine().setStencilBuffer(true);
  102467. }),
  102468. };
  102469. }
  102470. };
  102471. /**
  102472. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  102473. * @param mesh The mesh to highlight
  102474. */
  102475. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  102476. if (!this._excludedMeshes) {
  102477. return;
  102478. }
  102479. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  102480. if (meshExcluded) {
  102481. if (meshExcluded.beforeRender) {
  102482. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  102483. }
  102484. if (meshExcluded.afterRender) {
  102485. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  102486. }
  102487. }
  102488. this._excludedMeshes[mesh.uniqueId] = null;
  102489. };
  102490. /**
  102491. * Determine if a given mesh will be highlighted by the current HighlightLayer
  102492. * @param mesh mesh to test
  102493. * @returns true if the mesh will be highlighted by the current HighlightLayer
  102494. */
  102495. HighlightLayer.prototype.hasMesh = function (mesh) {
  102496. if (!this._meshes) {
  102497. return false;
  102498. }
  102499. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102500. return false;
  102501. }
  102502. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  102503. };
  102504. /**
  102505. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  102506. * @param mesh The mesh to highlight
  102507. * @param color The color of the highlight
  102508. * @param glowEmissiveOnly Extract the glow from the emissive texture
  102509. */
  102510. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  102511. var _this = this;
  102512. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  102513. if (!this._meshes) {
  102514. return;
  102515. }
  102516. var meshHighlight = this._meshes[mesh.uniqueId];
  102517. if (meshHighlight) {
  102518. meshHighlight.color = color;
  102519. }
  102520. else {
  102521. this._meshes[mesh.uniqueId] = {
  102522. mesh: mesh,
  102523. color: color,
  102524. // Lambda required for capture due to Observable this context
  102525. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  102526. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  102527. _this._defaultStencilReference(mesh);
  102528. }
  102529. else {
  102530. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  102531. }
  102532. }),
  102533. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  102534. glowEmissiveOnly: glowEmissiveOnly
  102535. };
  102536. mesh.onDisposeObservable.add(function () {
  102537. _this._disposeMesh(mesh);
  102538. });
  102539. }
  102540. this._shouldRender = true;
  102541. };
  102542. /**
  102543. * Remove a mesh from the highlight layer in order to make it stop glowing.
  102544. * @param mesh The mesh to highlight
  102545. */
  102546. HighlightLayer.prototype.removeMesh = function (mesh) {
  102547. if (!this._meshes) {
  102548. return;
  102549. }
  102550. var meshHighlight = this._meshes[mesh.uniqueId];
  102551. if (meshHighlight) {
  102552. if (meshHighlight.observerHighlight) {
  102553. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  102554. }
  102555. if (meshHighlight.observerDefault) {
  102556. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  102557. }
  102558. delete this._meshes[mesh.uniqueId];
  102559. }
  102560. this._shouldRender = false;
  102561. for (var meshHighlightToCheck in this._meshes) {
  102562. if (this._meshes[meshHighlightToCheck]) {
  102563. this._shouldRender = true;
  102564. break;
  102565. }
  102566. }
  102567. };
  102568. /**
  102569. * Force the stencil to the normal expected value for none glowing parts
  102570. */
  102571. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  102572. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  102573. };
  102574. /**
  102575. * Free any resources and references associated to a mesh.
  102576. * Internal use
  102577. * @param mesh The mesh to free.
  102578. * @hidden
  102579. */
  102580. HighlightLayer.prototype._disposeMesh = function (mesh) {
  102581. this.removeMesh(mesh);
  102582. this.removeExcludedMesh(mesh);
  102583. };
  102584. /**
  102585. * Dispose the highlight layer and free resources.
  102586. */
  102587. HighlightLayer.prototype.dispose = function () {
  102588. if (this._meshes) {
  102589. // Clean mesh references
  102590. for (var id in this._meshes) {
  102591. var meshHighlight = this._meshes[id];
  102592. if (meshHighlight && meshHighlight.mesh) {
  102593. if (meshHighlight.observerHighlight) {
  102594. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  102595. }
  102596. if (meshHighlight.observerDefault) {
  102597. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  102598. }
  102599. }
  102600. }
  102601. this._meshes = null;
  102602. }
  102603. if (this._excludedMeshes) {
  102604. for (var id in this._excludedMeshes) {
  102605. var meshHighlight = this._excludedMeshes[id];
  102606. if (meshHighlight) {
  102607. if (meshHighlight.beforeRender) {
  102608. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  102609. }
  102610. if (meshHighlight.afterRender) {
  102611. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  102612. }
  102613. }
  102614. }
  102615. this._excludedMeshes = null;
  102616. }
  102617. _super.prototype.dispose.call(this);
  102618. };
  102619. /**
  102620. * Gets the class name of the effect layer
  102621. * @returns the string with the class name of the effect layer
  102622. */
  102623. HighlightLayer.prototype.getClassName = function () {
  102624. return "HighlightLayer";
  102625. };
  102626. /**
  102627. * Serializes this Highlight layer
  102628. * @returns a serialized Highlight layer object
  102629. */
  102630. HighlightLayer.prototype.serialize = function () {
  102631. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102632. serializationObject.customType = "BABYLON.HighlightLayer";
  102633. // Highlighted meshes
  102634. serializationObject.meshes = [];
  102635. if (this._meshes) {
  102636. for (var m in this._meshes) {
  102637. var mesh = this._meshes[m];
  102638. if (mesh) {
  102639. serializationObject.meshes.push({
  102640. glowEmissiveOnly: mesh.glowEmissiveOnly,
  102641. color: mesh.color.asArray(),
  102642. meshId: mesh.mesh.id
  102643. });
  102644. }
  102645. }
  102646. }
  102647. // Excluded meshes
  102648. serializationObject.excludedMeshes = [];
  102649. if (this._excludedMeshes) {
  102650. for (var e in this._excludedMeshes) {
  102651. var excludedMesh = this._excludedMeshes[e];
  102652. if (excludedMesh) {
  102653. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  102654. }
  102655. }
  102656. }
  102657. return serializationObject;
  102658. };
  102659. /**
  102660. * Creates a Highlight layer from parsed Highlight layer data
  102661. * @param parsedHightlightLayer defines the Highlight layer data
  102662. * @param scene defines the current scene
  102663. * @param rootUrl defines the root URL containing the Highlight layer information
  102664. * @returns a parsed Highlight layer
  102665. */
  102666. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  102667. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  102668. var index;
  102669. // Excluded meshes
  102670. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  102671. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  102672. if (mesh) {
  102673. hl.addExcludedMesh(mesh);
  102674. }
  102675. }
  102676. // Included meshes
  102677. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  102678. var highlightedMesh = parsedHightlightLayer.meshes[index];
  102679. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  102680. if (mesh) {
  102681. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  102682. }
  102683. }
  102684. return hl;
  102685. };
  102686. /**
  102687. * Effect Name of the highlight layer.
  102688. */
  102689. HighlightLayer.EffectName = "HighlightLayer";
  102690. /**
  102691. * The neutral color used during the preparation of the glow effect.
  102692. * This is black by default as the blend operation is a blend operation.
  102693. */
  102694. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  102695. /**
  102696. * Stencil value used for glowing meshes.
  102697. */
  102698. HighlightLayer.GlowingMeshStencilReference = 0x02;
  102699. /**
  102700. * Stencil value used for the other meshes in the scene.
  102701. */
  102702. HighlightLayer.NormalMeshStencilReference = 0x01;
  102703. __decorate([
  102704. BABYLON.serialize()
  102705. ], HighlightLayer.prototype, "innerGlow", void 0);
  102706. __decorate([
  102707. BABYLON.serialize()
  102708. ], HighlightLayer.prototype, "outerGlow", void 0);
  102709. __decorate([
  102710. BABYLON.serialize()
  102711. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  102712. __decorate([
  102713. BABYLON.serialize()
  102714. ], HighlightLayer.prototype, "blurVerticalSize", null);
  102715. __decorate([
  102716. BABYLON.serialize("options")
  102717. ], HighlightLayer.prototype, "_options", void 0);
  102718. return HighlightLayer;
  102719. }(BABYLON.EffectLayer));
  102720. BABYLON.HighlightLayer = HighlightLayer;
  102721. })(BABYLON || (BABYLON = {}));
  102722. //# sourceMappingURL=babylon.highlightLayer.js.map
  102723. var BABYLON;
  102724. (function (BABYLON) {
  102725. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  102726. for (var index = 0; index < this.effectLayers.length; index++) {
  102727. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  102728. return this.effectLayers[index];
  102729. }
  102730. }
  102731. return null;
  102732. };
  102733. /**
  102734. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  102735. *
  102736. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102737. * glowy meshes to your scene.
  102738. *
  102739. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  102740. */
  102741. var GlowLayer = /** @class */ (function (_super) {
  102742. __extends(GlowLayer, _super);
  102743. /**
  102744. * Instantiates a new glow Layer and references it to the scene.
  102745. * @param name The name of the layer
  102746. * @param scene The scene to use the layer in
  102747. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  102748. */
  102749. function GlowLayer(name, scene, options) {
  102750. var _this = _super.call(this, name, scene) || this;
  102751. _this._intensity = 1.0;
  102752. _this._includedOnlyMeshes = [];
  102753. _this._excludedMeshes = [];
  102754. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  102755. // Adapt options
  102756. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  102757. // Initialize the layer
  102758. _this._init({
  102759. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  102760. camera: _this._options.camera,
  102761. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102762. mainTextureRatio: _this._options.mainTextureRatio,
  102763. renderingGroupId: _this._options.renderingGroupId
  102764. });
  102765. return _this;
  102766. }
  102767. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  102768. /**
  102769. * Gets the kernel size of the blur.
  102770. */
  102771. get: function () {
  102772. return this._horizontalBlurPostprocess1.kernel;
  102773. },
  102774. /**
  102775. * Sets the kernel size of the blur.
  102776. */
  102777. set: function (value) {
  102778. this._horizontalBlurPostprocess1.kernel = value;
  102779. this._verticalBlurPostprocess1.kernel = value;
  102780. this._horizontalBlurPostprocess2.kernel = value;
  102781. this._verticalBlurPostprocess2.kernel = value;
  102782. },
  102783. enumerable: true,
  102784. configurable: true
  102785. });
  102786. Object.defineProperty(GlowLayer.prototype, "intensity", {
  102787. /**
  102788. * Gets the glow intensity.
  102789. */
  102790. get: function () {
  102791. return this._intensity;
  102792. },
  102793. /**
  102794. * Sets the glow intensity.
  102795. */
  102796. set: function (value) {
  102797. this._intensity = value;
  102798. },
  102799. enumerable: true,
  102800. configurable: true
  102801. });
  102802. /**
  102803. * Get the effect name of the layer.
  102804. * @return The effect name
  102805. */
  102806. GlowLayer.prototype.getEffectName = function () {
  102807. return GlowLayer.EffectName;
  102808. };
  102809. /**
  102810. * Create the merge effect. This is the shader use to blit the information back
  102811. * to the main canvas at the end of the scene rendering.
  102812. */
  102813. GlowLayer.prototype._createMergeEffect = function () {
  102814. // Effect
  102815. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  102816. };
  102817. /**
  102818. * Creates the render target textures and post processes used in the glow layer.
  102819. */
  102820. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  102821. var _this = this;
  102822. var blurTextureWidth = this._mainTextureDesiredSize.width;
  102823. var blurTextureHeight = this._mainTextureDesiredSize.height;
  102824. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102825. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102826. var textureType = 0;
  102827. if (this._engine.getCaps().textureHalfFloatRender) {
  102828. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102829. }
  102830. else {
  102831. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102832. }
  102833. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  102834. width: blurTextureWidth,
  102835. height: blurTextureHeight
  102836. }, this._scene, false, true, textureType);
  102837. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102838. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102839. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102840. this._blurTexture1.renderParticles = false;
  102841. this._blurTexture1.ignoreCameraViewport = true;
  102842. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  102843. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  102844. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  102845. width: blurTextureWidth2,
  102846. height: blurTextureHeight2
  102847. }, this._scene, false, true, textureType);
  102848. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102849. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102850. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102851. this._blurTexture2.renderParticles = false;
  102852. this._blurTexture2.ignoreCameraViewport = true;
  102853. this._textures = [this._blurTexture1, this._blurTexture2];
  102854. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102855. width: blurTextureWidth,
  102856. height: blurTextureHeight
  102857. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102858. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  102859. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  102860. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  102861. effect.setTexture("textureSampler", _this._mainTexture);
  102862. });
  102863. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102864. width: blurTextureWidth,
  102865. height: blurTextureHeight
  102866. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102867. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102868. width: blurTextureWidth2,
  102869. height: blurTextureHeight2
  102870. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102871. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  102872. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  102873. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  102874. effect.setTexture("textureSampler", _this._blurTexture1);
  102875. });
  102876. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102877. width: blurTextureWidth2,
  102878. height: blurTextureHeight2
  102879. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102880. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102881. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  102882. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102883. this._mainTexture.samples = this._options.mainTextureSamples;
  102884. this._mainTexture.onAfterUnbindObservable.add(function () {
  102885. var internalTexture = _this._blurTexture1.getInternalTexture();
  102886. if (internalTexture) {
  102887. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  102888. internalTexture = _this._blurTexture2.getInternalTexture();
  102889. if (internalTexture) {
  102890. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  102891. }
  102892. }
  102893. });
  102894. // Prevent autoClear.
  102895. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102896. };
  102897. /**
  102898. * Checks for the readiness of the element composing the layer.
  102899. * @param subMesh the mesh to check for
  102900. * @param useInstances specify wether or not to use instances to render the mesh
  102901. * @param emissiveTexture the associated emissive texture used to generate the glow
  102902. * @return true if ready otherwise, false
  102903. */
  102904. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  102905. var material = subMesh.getMaterial();
  102906. var mesh = subMesh.getRenderingMesh();
  102907. if (!material || !mesh) {
  102908. return false;
  102909. }
  102910. var emissiveTexture = material.emissiveTexture;
  102911. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102912. };
  102913. /**
  102914. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102915. */
  102916. GlowLayer.prototype.needStencil = function () {
  102917. return false;
  102918. };
  102919. /**
  102920. * Implementation specific of rendering the generating effect on the main canvas.
  102921. * @param effect The effect used to render through
  102922. */
  102923. GlowLayer.prototype._internalRender = function (effect) {
  102924. // Texture
  102925. effect.setTexture("textureSampler", this._blurTexture1);
  102926. effect.setTexture("textureSampler2", this._blurTexture2);
  102927. effect.setFloat("offset", this._intensity);
  102928. // Cache
  102929. var engine = this._engine;
  102930. var previousStencilBuffer = engine.getStencilBuffer();
  102931. // Draw order
  102932. engine.setStencilBuffer(false);
  102933. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102934. // Draw order
  102935. engine.setStencilBuffer(previousStencilBuffer);
  102936. };
  102937. /**
  102938. * Sets the required values for both the emissive texture and and the main color.
  102939. */
  102940. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102941. var textureLevel = 1.0;
  102942. if (this.customEmissiveTextureSelector) {
  102943. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  102944. }
  102945. else {
  102946. if (material) {
  102947. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102948. if (this._emissiveTextureAndColor.texture) {
  102949. textureLevel = this._emissiveTextureAndColor.texture.level;
  102950. }
  102951. }
  102952. else {
  102953. this._emissiveTextureAndColor.texture = null;
  102954. }
  102955. }
  102956. if (this.customEmissiveColorSelector) {
  102957. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  102958. }
  102959. else {
  102960. if (material.emissiveColor) {
  102961. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  102962. }
  102963. else {
  102964. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102965. }
  102966. }
  102967. };
  102968. /**
  102969. * Returns true if the mesh should render, otherwise false.
  102970. * @param mesh The mesh to render
  102971. * @returns true if it should render otherwise false
  102972. */
  102973. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  102974. return this.hasMesh(mesh);
  102975. };
  102976. /**
  102977. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  102978. * @param mesh The mesh to exclude from the glow layer
  102979. */
  102980. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  102981. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  102982. this._excludedMeshes.push(mesh.uniqueId);
  102983. }
  102984. };
  102985. /**
  102986. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  102987. * @param mesh The mesh to remove
  102988. */
  102989. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  102990. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  102991. if (index !== -1) {
  102992. this._excludedMeshes.splice(index, 1);
  102993. }
  102994. };
  102995. /**
  102996. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  102997. * @param mesh The mesh to include in the glow layer
  102998. */
  102999. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  103000. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  103001. this._includedOnlyMeshes.push(mesh.uniqueId);
  103002. }
  103003. };
  103004. /**
  103005. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  103006. * @param mesh The mesh to remove
  103007. */
  103008. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  103009. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  103010. if (index !== -1) {
  103011. this._includedOnlyMeshes.splice(index, 1);
  103012. }
  103013. };
  103014. /**
  103015. * Determine if a given mesh will be used in the glow layer
  103016. * @param mesh The mesh to test
  103017. * @returns true if the mesh will be highlighted by the current glow layer
  103018. */
  103019. GlowLayer.prototype.hasMesh = function (mesh) {
  103020. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103021. return false;
  103022. }
  103023. // Included Mesh
  103024. if (this._includedOnlyMeshes.length) {
  103025. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  103026. }
  103027. ;
  103028. // Excluded Mesh
  103029. if (this._excludedMeshes.length) {
  103030. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  103031. }
  103032. ;
  103033. return true;
  103034. };
  103035. /**
  103036. * Free any resources and references associated to a mesh.
  103037. * Internal use
  103038. * @param mesh The mesh to free.
  103039. * @hidden
  103040. */
  103041. GlowLayer.prototype._disposeMesh = function (mesh) {
  103042. this.removeIncludedOnlyMesh(mesh);
  103043. this.removeExcludedMesh(mesh);
  103044. };
  103045. /**
  103046. * Gets the class name of the effect layer
  103047. * @returns the string with the class name of the effect layer
  103048. */
  103049. GlowLayer.prototype.getClassName = function () {
  103050. return "GlowLayer";
  103051. };
  103052. /**
  103053. * Serializes this glow layer
  103054. * @returns a serialized glow layer object
  103055. */
  103056. GlowLayer.prototype.serialize = function () {
  103057. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103058. serializationObject.customType = "BABYLON.GlowLayer";
  103059. var index;
  103060. // Included meshes
  103061. serializationObject.includedMeshes = [];
  103062. if (this._includedOnlyMeshes.length) {
  103063. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  103064. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  103065. if (mesh) {
  103066. serializationObject.includedMeshes.push(mesh.id);
  103067. }
  103068. }
  103069. }
  103070. // Excluded meshes
  103071. serializationObject.excludedMeshes = [];
  103072. if (this._excludedMeshes.length) {
  103073. for (index = 0; index < this._excludedMeshes.length; index++) {
  103074. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  103075. if (mesh) {
  103076. serializationObject.excludedMeshes.push(mesh.id);
  103077. }
  103078. }
  103079. }
  103080. return serializationObject;
  103081. };
  103082. /**
  103083. * Creates a Glow Layer from parsed glow layer data
  103084. * @param parsedGlowLayer defines glow layer data
  103085. * @param scene defines the current scene
  103086. * @param rootUrl defines the root URL containing the glow layer information
  103087. * @returns a parsed Glow Layer
  103088. */
  103089. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  103090. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  103091. var index;
  103092. // Excluded meshes
  103093. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  103094. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  103095. if (mesh) {
  103096. gl.addExcludedMesh(mesh);
  103097. }
  103098. }
  103099. // Included meshes
  103100. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  103101. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  103102. if (mesh) {
  103103. gl.addIncludedOnlyMesh(mesh);
  103104. }
  103105. }
  103106. return gl;
  103107. };
  103108. /**
  103109. * Effect Name of the layer.
  103110. */
  103111. GlowLayer.EffectName = "GlowLayer";
  103112. /**
  103113. * The default blur kernel size used for the glow.
  103114. */
  103115. GlowLayer.DefaultBlurKernelSize = 32;
  103116. /**
  103117. * The default texture size ratio used for the glow.
  103118. */
  103119. GlowLayer.DefaultTextureRatio = 0.5;
  103120. __decorate([
  103121. BABYLON.serialize()
  103122. ], GlowLayer.prototype, "blurKernelSize", null);
  103123. __decorate([
  103124. BABYLON.serialize()
  103125. ], GlowLayer.prototype, "intensity", null);
  103126. __decorate([
  103127. BABYLON.serialize("options")
  103128. ], GlowLayer.prototype, "_options", void 0);
  103129. return GlowLayer;
  103130. }(BABYLON.EffectLayer));
  103131. BABYLON.GlowLayer = GlowLayer;
  103132. })(BABYLON || (BABYLON = {}));
  103133. //# sourceMappingURL=babylon.glowLayer.js.map
  103134. var BABYLON;
  103135. (function (BABYLON) {
  103136. /**
  103137. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  103138. */
  103139. var AssetTaskState;
  103140. (function (AssetTaskState) {
  103141. /**
  103142. * Initialization
  103143. */
  103144. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  103145. /**
  103146. * Running
  103147. */
  103148. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  103149. /**
  103150. * Done
  103151. */
  103152. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  103153. /**
  103154. * Error
  103155. */
  103156. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  103157. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  103158. /**
  103159. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  103160. */
  103161. var AbstractAssetTask = /** @class */ (function () {
  103162. /**
  103163. * Creates a new {BABYLON.AssetsManager}
  103164. * @param name defines the name of the task
  103165. */
  103166. function AbstractAssetTask(
  103167. /**
  103168. * Task name
  103169. */ name) {
  103170. this.name = name;
  103171. this._isCompleted = false;
  103172. this._taskState = AssetTaskState.INIT;
  103173. }
  103174. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  103175. /**
  103176. * Get if the task is completed
  103177. */
  103178. get: function () {
  103179. return this._isCompleted;
  103180. },
  103181. enumerable: true,
  103182. configurable: true
  103183. });
  103184. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  103185. /**
  103186. * Gets the current state of the task
  103187. */
  103188. get: function () {
  103189. return this._taskState;
  103190. },
  103191. enumerable: true,
  103192. configurable: true
  103193. });
  103194. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  103195. /**
  103196. * Gets the current error object (if task is in error)
  103197. */
  103198. get: function () {
  103199. return this._errorObject;
  103200. },
  103201. enumerable: true,
  103202. configurable: true
  103203. });
  103204. /**
  103205. * Internal only
  103206. * @hidden
  103207. */
  103208. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  103209. if (this._errorObject) {
  103210. return;
  103211. }
  103212. this._errorObject = {
  103213. message: message,
  103214. exception: exception
  103215. };
  103216. };
  103217. /**
  103218. * Execute the current task
  103219. * @param scene defines the scene where you want your assets to be loaded
  103220. * @param onSuccess is a callback called when the task is successfully executed
  103221. * @param onError is a callback called if an error occurs
  103222. */
  103223. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103224. var _this = this;
  103225. this._taskState = AssetTaskState.RUNNING;
  103226. this.runTask(scene, function () {
  103227. _this.onDoneCallback(onSuccess, onError);
  103228. }, function (msg, exception) {
  103229. _this.onErrorCallback(onError, msg, exception);
  103230. });
  103231. };
  103232. /**
  103233. * Execute the current task
  103234. * @param scene defines the scene where you want your assets to be loaded
  103235. * @param onSuccess is a callback called when the task is successfully executed
  103236. * @param onError is a callback called if an error occurs
  103237. */
  103238. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103239. throw new Error("runTask is not implemented");
  103240. };
  103241. /**
  103242. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  103243. * This can be used with failed tasks that have the reason for failure fixed.
  103244. */
  103245. AbstractAssetTask.prototype.reset = function () {
  103246. this._taskState = AssetTaskState.INIT;
  103247. };
  103248. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  103249. this._taskState = AssetTaskState.ERROR;
  103250. this._errorObject = {
  103251. message: message,
  103252. exception: exception
  103253. };
  103254. if (this.onError) {
  103255. this.onError(this, message, exception);
  103256. }
  103257. onError();
  103258. };
  103259. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  103260. try {
  103261. this._taskState = AssetTaskState.DONE;
  103262. this._isCompleted = true;
  103263. if (this.onSuccess) {
  103264. this.onSuccess(this);
  103265. }
  103266. onSuccess();
  103267. }
  103268. catch (e) {
  103269. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  103270. }
  103271. };
  103272. return AbstractAssetTask;
  103273. }());
  103274. BABYLON.AbstractAssetTask = AbstractAssetTask;
  103275. /**
  103276. * Class used to share progress information about assets loading
  103277. */
  103278. var AssetsProgressEvent = /** @class */ (function () {
  103279. /**
  103280. * Creates a {BABYLON.AssetsProgressEvent}
  103281. * @param remainingCount defines the number of remaining tasks to process
  103282. * @param totalCount defines the total number of tasks
  103283. * @param task defines the task that was just processed
  103284. */
  103285. function AssetsProgressEvent(remainingCount, totalCount, task) {
  103286. this.remainingCount = remainingCount;
  103287. this.totalCount = totalCount;
  103288. this.task = task;
  103289. }
  103290. return AssetsProgressEvent;
  103291. }());
  103292. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  103293. /**
  103294. * Define a task used by {BABYLON.AssetsManager} to load meshes
  103295. */
  103296. var MeshAssetTask = /** @class */ (function (_super) {
  103297. __extends(MeshAssetTask, _super);
  103298. /**
  103299. * Creates a new {BABYLON.MeshAssetTask}
  103300. * @param name defines the name of the task
  103301. * @param meshesNames defines the list of mesh's names you want to load
  103302. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  103303. * @param sceneFilename defines the filename of the scene to load from
  103304. */
  103305. function MeshAssetTask(
  103306. /**
  103307. * Defines the name of the task
  103308. */
  103309. name,
  103310. /**
  103311. * Defines the list of mesh's names you want to load
  103312. */
  103313. meshesNames,
  103314. /**
  103315. * Defines the root url to use as a base to load your meshes and associated resources
  103316. */
  103317. rootUrl,
  103318. /**
  103319. * Defines the filename of the scene to load from
  103320. */
  103321. sceneFilename) {
  103322. var _this = _super.call(this, name) || this;
  103323. _this.name = name;
  103324. _this.meshesNames = meshesNames;
  103325. _this.rootUrl = rootUrl;
  103326. _this.sceneFilename = sceneFilename;
  103327. return _this;
  103328. }
  103329. /**
  103330. * Execute the current task
  103331. * @param scene defines the scene where you want your assets to be loaded
  103332. * @param onSuccess is a callback called when the task is successfully executed
  103333. * @param onError is a callback called if an error occurs
  103334. */
  103335. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103336. var _this = this;
  103337. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  103338. _this.loadedMeshes = meshes;
  103339. _this.loadedParticleSystems = particleSystems;
  103340. _this.loadedSkeletons = skeletons;
  103341. onSuccess();
  103342. }, null, function (scene, message, exception) {
  103343. onError(message, exception);
  103344. });
  103345. };
  103346. return MeshAssetTask;
  103347. }(AbstractAssetTask));
  103348. BABYLON.MeshAssetTask = MeshAssetTask;
  103349. /**
  103350. * Define a task used by {BABYLON.AssetsManager} to load text content
  103351. */
  103352. var TextFileAssetTask = /** @class */ (function (_super) {
  103353. __extends(TextFileAssetTask, _super);
  103354. /**
  103355. * Creates a new TextFileAssetTask object
  103356. * @param name defines the name of the task
  103357. * @param url defines the location of the file to load
  103358. */
  103359. function TextFileAssetTask(
  103360. /**
  103361. * Defines the name of the task
  103362. */
  103363. name,
  103364. /**
  103365. * Defines the location of the file to load
  103366. */
  103367. url) {
  103368. var _this = _super.call(this, name) || this;
  103369. _this.name = name;
  103370. _this.url = url;
  103371. return _this;
  103372. }
  103373. /**
  103374. * Execute the current task
  103375. * @param scene defines the scene where you want your assets to be loaded
  103376. * @param onSuccess is a callback called when the task is successfully executed
  103377. * @param onError is a callback called if an error occurs
  103378. */
  103379. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103380. var _this = this;
  103381. scene._loadFile(this.url, function (data) {
  103382. _this.text = data;
  103383. onSuccess();
  103384. }, undefined, false, false, function (request, exception) {
  103385. if (request) {
  103386. onError(request.status + " " + request.statusText, exception);
  103387. }
  103388. });
  103389. };
  103390. return TextFileAssetTask;
  103391. }(AbstractAssetTask));
  103392. BABYLON.TextFileAssetTask = TextFileAssetTask;
  103393. /**
  103394. * Define a task used by {BABYLON.AssetsManager} to load binary data
  103395. */
  103396. var BinaryFileAssetTask = /** @class */ (function (_super) {
  103397. __extends(BinaryFileAssetTask, _super);
  103398. /**
  103399. * Creates a new BinaryFileAssetTask object
  103400. * @param name defines the name of the new task
  103401. * @param url defines the location of the file to load
  103402. */
  103403. function BinaryFileAssetTask(
  103404. /**
  103405. * Defines the name of the task
  103406. */
  103407. name,
  103408. /**
  103409. * Defines the location of the file to load
  103410. */
  103411. url) {
  103412. var _this = _super.call(this, name) || this;
  103413. _this.name = name;
  103414. _this.url = url;
  103415. return _this;
  103416. }
  103417. /**
  103418. * Execute the current task
  103419. * @param scene defines the scene where you want your assets to be loaded
  103420. * @param onSuccess is a callback called when the task is successfully executed
  103421. * @param onError is a callback called if an error occurs
  103422. */
  103423. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103424. var _this = this;
  103425. scene._loadFile(this.url, function (data) {
  103426. _this.data = data;
  103427. onSuccess();
  103428. }, undefined, true, true, function (request, exception) {
  103429. if (request) {
  103430. onError(request.status + " " + request.statusText, exception);
  103431. }
  103432. });
  103433. };
  103434. return BinaryFileAssetTask;
  103435. }(AbstractAssetTask));
  103436. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  103437. /**
  103438. * Define a task used by {BABYLON.AssetsManager} to load images
  103439. */
  103440. var ImageAssetTask = /** @class */ (function (_super) {
  103441. __extends(ImageAssetTask, _super);
  103442. /**
  103443. * Creates a new ImageAssetTask
  103444. * @param name defines the name of the task
  103445. * @param url defines the location of the image to load
  103446. */
  103447. function ImageAssetTask(
  103448. /**
  103449. * Defines the name of the task
  103450. */
  103451. name,
  103452. /**
  103453. * Defines the location of the image to load
  103454. */
  103455. url) {
  103456. var _this = _super.call(this, name) || this;
  103457. _this.name = name;
  103458. _this.url = url;
  103459. return _this;
  103460. }
  103461. /**
  103462. * Execute the current task
  103463. * @param scene defines the scene where you want your assets to be loaded
  103464. * @param onSuccess is a callback called when the task is successfully executed
  103465. * @param onError is a callback called if an error occurs
  103466. */
  103467. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103468. var _this = this;
  103469. var img = new Image();
  103470. BABYLON.Tools.SetCorsBehavior(this.url, img);
  103471. img.onload = function () {
  103472. _this.image = img;
  103473. onSuccess();
  103474. };
  103475. img.onerror = function (err) {
  103476. onError("Error loading image", err);
  103477. };
  103478. img.src = this.url;
  103479. };
  103480. return ImageAssetTask;
  103481. }(AbstractAssetTask));
  103482. BABYLON.ImageAssetTask = ImageAssetTask;
  103483. /**
  103484. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  103485. */
  103486. var TextureAssetTask = /** @class */ (function (_super) {
  103487. __extends(TextureAssetTask, _super);
  103488. /**
  103489. * Creates a new TextureAssetTask object
  103490. * @param name defines the name of the task
  103491. * @param url defines the location of the file to load
  103492. * @param noMipmap defines if mipmap should not be generated (default is false)
  103493. * @param invertY defines if texture must be inverted on Y axis (default is false)
  103494. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  103495. */
  103496. function TextureAssetTask(
  103497. /**
  103498. * Defines the name of the task
  103499. */
  103500. name,
  103501. /**
  103502. * Defines the location of the file to load
  103503. */
  103504. url,
  103505. /**
  103506. * Defines if mipmap should not be generated (default is false)
  103507. */
  103508. noMipmap,
  103509. /**
  103510. * Defines if texture must be inverted on Y axis (default is false)
  103511. */
  103512. invertY,
  103513. /**
  103514. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  103515. */
  103516. samplingMode) {
  103517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103518. var _this = _super.call(this, name) || this;
  103519. _this.name = name;
  103520. _this.url = url;
  103521. _this.noMipmap = noMipmap;
  103522. _this.invertY = invertY;
  103523. _this.samplingMode = samplingMode;
  103524. return _this;
  103525. }
  103526. /**
  103527. * Execute the current task
  103528. * @param scene defines the scene where you want your assets to be loaded
  103529. * @param onSuccess is a callback called when the task is successfully executed
  103530. * @param onError is a callback called if an error occurs
  103531. */
  103532. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103533. var onload = function () {
  103534. onSuccess();
  103535. };
  103536. var onerror = function (message, exception) {
  103537. onError(message, exception);
  103538. };
  103539. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  103540. };
  103541. return TextureAssetTask;
  103542. }(AbstractAssetTask));
  103543. BABYLON.TextureAssetTask = TextureAssetTask;
  103544. /**
  103545. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  103546. */
  103547. var CubeTextureAssetTask = /** @class */ (function (_super) {
  103548. __extends(CubeTextureAssetTask, _super);
  103549. /**
  103550. * Creates a new CubeTextureAssetTask
  103551. * @param name defines the name of the task
  103552. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  103553. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  103554. * @param noMipmap defines if mipmaps should not be generated (default is false)
  103555. * @param files defines the explicit list of files (undefined by default)
  103556. */
  103557. function CubeTextureAssetTask(
  103558. /**
  103559. * Defines the name of the task
  103560. */
  103561. name,
  103562. /**
  103563. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  103564. */
  103565. url,
  103566. /**
  103567. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  103568. */
  103569. extensions,
  103570. /**
  103571. * Defines if mipmaps should not be generated (default is false)
  103572. */
  103573. noMipmap,
  103574. /**
  103575. * Defines the explicit list of files (undefined by default)
  103576. */
  103577. files) {
  103578. var _this = _super.call(this, name) || this;
  103579. _this.name = name;
  103580. _this.url = url;
  103581. _this.extensions = extensions;
  103582. _this.noMipmap = noMipmap;
  103583. _this.files = files;
  103584. return _this;
  103585. }
  103586. /**
  103587. * Execute the current task
  103588. * @param scene defines the scene where you want your assets to be loaded
  103589. * @param onSuccess is a callback called when the task is successfully executed
  103590. * @param onError is a callback called if an error occurs
  103591. */
  103592. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103593. var onload = function () {
  103594. onSuccess();
  103595. };
  103596. var onerror = function (message, exception) {
  103597. onError(message, exception);
  103598. };
  103599. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  103600. };
  103601. return CubeTextureAssetTask;
  103602. }(AbstractAssetTask));
  103603. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  103604. /**
  103605. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  103606. */
  103607. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  103608. __extends(HDRCubeTextureAssetTask, _super);
  103609. /**
  103610. * Creates a new HDRCubeTextureAssetTask object
  103611. * @param name defines the name of the task
  103612. * @param url defines the location of the file to load
  103613. * @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.
  103614. * @param noMipmap defines if mipmaps should not be generated (default is false)
  103615. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  103616. * @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)
  103617. * @param reserved Internal use only
  103618. */
  103619. function HDRCubeTextureAssetTask(
  103620. /**
  103621. * Defines the name of the task
  103622. */
  103623. name,
  103624. /**
  103625. * Defines the location of the file to load
  103626. */
  103627. url,
  103628. /**
  103629. * Defines the desired size (the more it increases the longer the generation will be)
  103630. */
  103631. size,
  103632. /**
  103633. * Defines if mipmaps should not be generated (default is false)
  103634. */
  103635. noMipmap,
  103636. /**
  103637. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  103638. */
  103639. generateHarmonics,
  103640. /**
  103641. * 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)
  103642. */
  103643. gammaSpace,
  103644. /**
  103645. * Internal Use Only
  103646. */
  103647. reserved) {
  103648. if (noMipmap === void 0) { noMipmap = false; }
  103649. if (generateHarmonics === void 0) { generateHarmonics = true; }
  103650. if (gammaSpace === void 0) { gammaSpace = false; }
  103651. if (reserved === void 0) { reserved = false; }
  103652. var _this = _super.call(this, name) || this;
  103653. _this.name = name;
  103654. _this.url = url;
  103655. _this.size = size;
  103656. _this.noMipmap = noMipmap;
  103657. _this.generateHarmonics = generateHarmonics;
  103658. _this.gammaSpace = gammaSpace;
  103659. _this.reserved = reserved;
  103660. return _this;
  103661. }
  103662. /**
  103663. * Execute the current task
  103664. * @param scene defines the scene where you want your assets to be loaded
  103665. * @param onSuccess is a callback called when the task is successfully executed
  103666. * @param onError is a callback called if an error occurs
  103667. */
  103668. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103669. var onload = function () {
  103670. onSuccess();
  103671. };
  103672. var onerror = function (message, exception) {
  103673. onError(message, exception);
  103674. };
  103675. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  103676. };
  103677. return HDRCubeTextureAssetTask;
  103678. }(AbstractAssetTask));
  103679. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  103680. /**
  103681. * This class can be used to easily import assets into a scene
  103682. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  103683. */
  103684. var AssetsManager = /** @class */ (function () {
  103685. /**
  103686. * Creates a new AssetsManager
  103687. * @param scene defines the scene to work on
  103688. */
  103689. function AssetsManager(scene) {
  103690. this._isLoading = false;
  103691. this._tasks = new Array();
  103692. this._waitingTasksCount = 0;
  103693. this._totalTasksCount = 0;
  103694. /**
  103695. * Observable called when all tasks are processed
  103696. */
  103697. this.onTaskSuccessObservable = new BABYLON.Observable();
  103698. /**
  103699. * Observable called when a task had an error
  103700. */
  103701. this.onTaskErrorObservable = new BABYLON.Observable();
  103702. /**
  103703. * Observable called when a task is successful
  103704. */
  103705. this.onTasksDoneObservable = new BABYLON.Observable();
  103706. /**
  103707. * Observable called when a task is done (whatever the result is)
  103708. */
  103709. this.onProgressObservable = new BABYLON.Observable();
  103710. /**
  103711. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  103712. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  103713. */
  103714. this.useDefaultLoadingScreen = true;
  103715. this._scene = scene;
  103716. }
  103717. /**
  103718. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  103719. * @param taskName defines the name of the new task
  103720. * @param meshesNames defines the name of meshes to load
  103721. * @param rootUrl defines the root url to use to locate files
  103722. * @param sceneFilename defines the filename of the scene file
  103723. * @returns a new {BABYLON.MeshAssetTask} object
  103724. */
  103725. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  103726. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  103727. this._tasks.push(task);
  103728. return task;
  103729. };
  103730. /**
  103731. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  103732. * @param taskName defines the name of the new task
  103733. * @param url defines the url of the file to load
  103734. * @returns a new {BABYLON.TextFileAssetTask} object
  103735. */
  103736. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  103737. var task = new TextFileAssetTask(taskName, url);
  103738. this._tasks.push(task);
  103739. return task;
  103740. };
  103741. /**
  103742. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  103743. * @param taskName defines the name of the new task
  103744. * @param url defines the url of the file to load
  103745. * @returns a new {BABYLON.BinaryFileAssetTask} object
  103746. */
  103747. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  103748. var task = new BinaryFileAssetTask(taskName, url);
  103749. this._tasks.push(task);
  103750. return task;
  103751. };
  103752. /**
  103753. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  103754. * @param taskName defines the name of the new task
  103755. * @param url defines the url of the file to load
  103756. * @returns a new {BABYLON.ImageAssetTask} object
  103757. */
  103758. AssetsManager.prototype.addImageTask = function (taskName, url) {
  103759. var task = new ImageAssetTask(taskName, url);
  103760. this._tasks.push(task);
  103761. return task;
  103762. };
  103763. /**
  103764. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  103765. * @param taskName defines the name of the new task
  103766. * @param url defines the url of the file to load
  103767. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103768. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  103769. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  103770. * @returns a new {BABYLON.TextureAssetTask} object
  103771. */
  103772. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  103773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103774. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  103775. this._tasks.push(task);
  103776. return task;
  103777. };
  103778. /**
  103779. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  103780. * @param taskName defines the name of the new task
  103781. * @param url defines the url of the file to load
  103782. * @param extensions defines the extension to use to load the cube map (can be null)
  103783. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103784. * @param files defines the list of files to load (can be null)
  103785. * @returns a new {BABYLON.CubeTextureAssetTask} object
  103786. */
  103787. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  103788. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  103789. this._tasks.push(task);
  103790. return task;
  103791. };
  103792. /**
  103793. *
  103794. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  103795. * @param taskName defines the name of the new task
  103796. * @param url defines the url of the file to load
  103797. * @param size defines the size you want for the cubemap (can be null)
  103798. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103799. * @param generateHarmonics defines if you want to automatically generate (true by default)
  103800. * @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)
  103801. * @param reserved Internal use only
  103802. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  103803. */
  103804. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  103805. if (noMipmap === void 0) { noMipmap = false; }
  103806. if (generateHarmonics === void 0) { generateHarmonics = true; }
  103807. if (gammaSpace === void 0) { gammaSpace = false; }
  103808. if (reserved === void 0) { reserved = false; }
  103809. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  103810. this._tasks.push(task);
  103811. return task;
  103812. };
  103813. /**
  103814. * Remove a task from the assets manager.
  103815. * @param task the task to remove
  103816. */
  103817. AssetsManager.prototype.removeTask = function (task) {
  103818. var index = this._tasks.indexOf(task);
  103819. if (index > -1) {
  103820. this._tasks.splice(index, 1);
  103821. }
  103822. };
  103823. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  103824. this._waitingTasksCount--;
  103825. try {
  103826. if (this.onProgress) {
  103827. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  103828. }
  103829. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  103830. }
  103831. catch (e) {
  103832. BABYLON.Tools.Error("Error running progress callbacks.");
  103833. console.log(e);
  103834. }
  103835. if (this._waitingTasksCount === 0) {
  103836. try {
  103837. if (this.onFinish) {
  103838. this.onFinish(this._tasks);
  103839. }
  103840. // Let's remove successfull tasks
  103841. var currentTasks = this._tasks.slice();
  103842. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  103843. var task = currentTasks_1[_i];
  103844. if (task.taskState === AssetTaskState.DONE) {
  103845. var index = this._tasks.indexOf(task);
  103846. if (index > -1) {
  103847. this._tasks.splice(index, 1);
  103848. }
  103849. }
  103850. }
  103851. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103852. }
  103853. catch (e) {
  103854. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  103855. console.log(e);
  103856. }
  103857. this._isLoading = false;
  103858. this._scene.getEngine().hideLoadingUI();
  103859. }
  103860. };
  103861. AssetsManager.prototype._runTask = function (task) {
  103862. var _this = this;
  103863. var done = function () {
  103864. try {
  103865. if (_this.onTaskSuccess) {
  103866. _this.onTaskSuccess(task);
  103867. }
  103868. _this.onTaskSuccessObservable.notifyObservers(task);
  103869. _this._decreaseWaitingTasksCount(task);
  103870. }
  103871. catch (e) {
  103872. error("Error executing task success callbacks", e);
  103873. }
  103874. };
  103875. var error = function (message, exception) {
  103876. task._setErrorObject(message, exception);
  103877. if (_this.onTaskError) {
  103878. _this.onTaskError(task);
  103879. }
  103880. _this.onTaskErrorObservable.notifyObservers(task);
  103881. _this._decreaseWaitingTasksCount(task);
  103882. };
  103883. task.run(this._scene, done, error);
  103884. };
  103885. /**
  103886. * Reset the {BABYLON.AssetsManager} and remove all tasks
  103887. * @return the current instance of the {BABYLON.AssetsManager}
  103888. */
  103889. AssetsManager.prototype.reset = function () {
  103890. this._isLoading = false;
  103891. this._tasks = new Array();
  103892. return this;
  103893. };
  103894. /**
  103895. * Start the loading process
  103896. * @return the current instance of the {BABYLON.AssetsManager}
  103897. */
  103898. AssetsManager.prototype.load = function () {
  103899. if (this._isLoading) {
  103900. return this;
  103901. }
  103902. this._isLoading = true;
  103903. this._waitingTasksCount = this._tasks.length;
  103904. this._totalTasksCount = this._tasks.length;
  103905. if (this._waitingTasksCount === 0) {
  103906. this._isLoading = false;
  103907. if (this.onFinish) {
  103908. this.onFinish(this._tasks);
  103909. }
  103910. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103911. return this;
  103912. }
  103913. if (this.useDefaultLoadingScreen) {
  103914. this._scene.getEngine().displayLoadingUI();
  103915. }
  103916. for (var index = 0; index < this._tasks.length; index++) {
  103917. var task = this._tasks[index];
  103918. if (task.taskState === AssetTaskState.INIT) {
  103919. this._runTask(task);
  103920. }
  103921. }
  103922. return this;
  103923. };
  103924. return AssetsManager;
  103925. }());
  103926. BABYLON.AssetsManager = AssetsManager;
  103927. })(BABYLON || (BABYLON = {}));
  103928. //# sourceMappingURL=babylon.assetsManager.js.map
  103929. var BABYLON;
  103930. (function (BABYLON) {
  103931. var serializedGeometries = [];
  103932. var serializeGeometry = function (geometry, serializationGeometries) {
  103933. if (serializedGeometries[geometry.id]) {
  103934. return;
  103935. }
  103936. if (geometry.doNotSerialize) {
  103937. return;
  103938. }
  103939. if (geometry instanceof BABYLON.BoxGeometry) {
  103940. serializationGeometries.boxes.push(geometry.serialize());
  103941. }
  103942. else if (geometry instanceof BABYLON.SphereGeometry) {
  103943. serializationGeometries.spheres.push(geometry.serialize());
  103944. }
  103945. else if (geometry instanceof BABYLON.CylinderGeometry) {
  103946. serializationGeometries.cylinders.push(geometry.serialize());
  103947. }
  103948. else if (geometry instanceof BABYLON.TorusGeometry) {
  103949. serializationGeometries.toruses.push(geometry.serialize());
  103950. }
  103951. else if (geometry instanceof BABYLON.GroundGeometry) {
  103952. serializationGeometries.grounds.push(geometry.serialize());
  103953. }
  103954. else if (geometry instanceof BABYLON.Plane) {
  103955. serializationGeometries.planes.push(geometry.serialize());
  103956. }
  103957. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  103958. serializationGeometries.torusKnots.push(geometry.serialize());
  103959. }
  103960. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  103961. throw new Error("Unknown primitive type");
  103962. }
  103963. else {
  103964. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  103965. }
  103966. serializedGeometries[geometry.id] = true;
  103967. };
  103968. var serializeMesh = function (mesh, serializationScene) {
  103969. var serializationObject = {};
  103970. // Geometry
  103971. var geometry = mesh._geometry;
  103972. if (geometry) {
  103973. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  103974. // 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
  103975. serializeGeometry(geometry, serializationScene.geometries);
  103976. }
  103977. }
  103978. // Custom
  103979. if (mesh.serialize) {
  103980. mesh.serialize(serializationObject);
  103981. }
  103982. return serializationObject;
  103983. };
  103984. var finalizeSingleMesh = function (mesh, serializationObject) {
  103985. //only works if the mesh is already loaded
  103986. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  103987. //serialize material
  103988. if (mesh.material) {
  103989. if (mesh.material instanceof BABYLON.MultiMaterial) {
  103990. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  103991. serializationObject.materials = serializationObject.materials || [];
  103992. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  103993. serializationObject.multiMaterials.push(mesh.material.serialize());
  103994. var _loop_1 = function (submaterial) {
  103995. if (submaterial) {
  103996. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  103997. serializationObject.materials.push(submaterial.serialize());
  103998. }
  103999. }
  104000. };
  104001. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  104002. var submaterial = _a[_i];
  104003. _loop_1(submaterial);
  104004. }
  104005. }
  104006. }
  104007. else {
  104008. serializationObject.materials = serializationObject.materials || [];
  104009. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104010. serializationObject.materials.push(mesh.material.serialize());
  104011. }
  104012. }
  104013. }
  104014. //serialize geometry
  104015. var geometry = mesh._geometry;
  104016. if (geometry) {
  104017. if (!serializationObject.geometries) {
  104018. serializationObject.geometries = {};
  104019. serializationObject.geometries.boxes = [];
  104020. serializationObject.geometries.spheres = [];
  104021. serializationObject.geometries.cylinders = [];
  104022. serializationObject.geometries.toruses = [];
  104023. serializationObject.geometries.grounds = [];
  104024. serializationObject.geometries.planes = [];
  104025. serializationObject.geometries.torusKnots = [];
  104026. serializationObject.geometries.vertexData = [];
  104027. }
  104028. serializeGeometry(geometry, serializationObject.geometries);
  104029. }
  104030. // Skeletons
  104031. if (mesh.skeleton) {
  104032. serializationObject.skeletons = serializationObject.skeletons || [];
  104033. serializationObject.skeletons.push(mesh.skeleton.serialize());
  104034. }
  104035. //serialize the actual mesh
  104036. serializationObject.meshes = serializationObject.meshes || [];
  104037. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104038. }
  104039. };
  104040. var SceneSerializer = /** @class */ (function () {
  104041. function SceneSerializer() {
  104042. }
  104043. SceneSerializer.ClearCache = function () {
  104044. serializedGeometries = [];
  104045. };
  104046. SceneSerializer.Serialize = function (scene) {
  104047. var serializationObject = {};
  104048. SceneSerializer.ClearCache();
  104049. // Scene
  104050. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  104051. serializationObject.autoClear = scene.autoClear;
  104052. serializationObject.clearColor = scene.clearColor.asArray();
  104053. serializationObject.ambientColor = scene.ambientColor.asArray();
  104054. serializationObject.gravity = scene.gravity.asArray();
  104055. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  104056. serializationObject.workerCollisions = scene.workerCollisions;
  104057. // Fog
  104058. if (scene.fogMode && scene.fogMode !== 0) {
  104059. serializationObject.fogMode = scene.fogMode;
  104060. serializationObject.fogColor = scene.fogColor.asArray();
  104061. serializationObject.fogStart = scene.fogStart;
  104062. serializationObject.fogEnd = scene.fogEnd;
  104063. serializationObject.fogDensity = scene.fogDensity;
  104064. }
  104065. //Physics
  104066. if (scene.isPhysicsEnabled()) {
  104067. var physicEngine = scene.getPhysicsEngine();
  104068. if (physicEngine) {
  104069. serializationObject.physicsEnabled = true;
  104070. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  104071. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  104072. }
  104073. }
  104074. // Metadata
  104075. if (scene.metadata) {
  104076. serializationObject.metadata = scene.metadata;
  104077. }
  104078. // Morph targets
  104079. serializationObject.morphTargetManagers = [];
  104080. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  104081. var abstractMesh = _a[_i];
  104082. var manager = abstractMesh.morphTargetManager;
  104083. if (manager) {
  104084. serializationObject.morphTargetManagers.push(manager.serialize());
  104085. }
  104086. }
  104087. // Lights
  104088. serializationObject.lights = [];
  104089. var index;
  104090. var light;
  104091. for (index = 0; index < scene.lights.length; index++) {
  104092. light = scene.lights[index];
  104093. if (!light.doNotSerialize) {
  104094. serializationObject.lights.push(light.serialize());
  104095. }
  104096. }
  104097. // Cameras
  104098. serializationObject.cameras = [];
  104099. for (index = 0; index < scene.cameras.length; index++) {
  104100. var camera = scene.cameras[index];
  104101. if (!camera.doNotSerialize) {
  104102. serializationObject.cameras.push(camera.serialize());
  104103. }
  104104. }
  104105. if (scene.activeCamera) {
  104106. serializationObject.activeCameraID = scene.activeCamera.id;
  104107. }
  104108. // Animations
  104109. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  104110. // Materials
  104111. serializationObject.materials = [];
  104112. serializationObject.multiMaterials = [];
  104113. var material;
  104114. for (index = 0; index < scene.materials.length; index++) {
  104115. material = scene.materials[index];
  104116. if (!material.doNotSerialize) {
  104117. serializationObject.materials.push(material.serialize());
  104118. }
  104119. }
  104120. // MultiMaterials
  104121. serializationObject.multiMaterials = [];
  104122. for (index = 0; index < scene.multiMaterials.length; index++) {
  104123. var multiMaterial = scene.multiMaterials[index];
  104124. serializationObject.multiMaterials.push(multiMaterial.serialize());
  104125. }
  104126. // Environment texture
  104127. if (scene.environmentTexture) {
  104128. serializationObject.environmentTexture = scene.environmentTexture.name;
  104129. }
  104130. // Skeletons
  104131. serializationObject.skeletons = [];
  104132. for (index = 0; index < scene.skeletons.length; index++) {
  104133. var skeleton = scene.skeletons[index];
  104134. if (!skeleton.doNotSerialize) {
  104135. serializationObject.skeletons.push(skeleton.serialize());
  104136. }
  104137. }
  104138. // Transform nodes
  104139. serializationObject.transformNodes = [];
  104140. for (index = 0; index < scene.transformNodes.length; index++) {
  104141. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  104142. }
  104143. // Geometries
  104144. serializationObject.geometries = {};
  104145. serializationObject.geometries.boxes = [];
  104146. serializationObject.geometries.spheres = [];
  104147. serializationObject.geometries.cylinders = [];
  104148. serializationObject.geometries.toruses = [];
  104149. serializationObject.geometries.grounds = [];
  104150. serializationObject.geometries.planes = [];
  104151. serializationObject.geometries.torusKnots = [];
  104152. serializationObject.geometries.vertexData = [];
  104153. serializedGeometries = [];
  104154. var geometries = scene.getGeometries();
  104155. for (index = 0; index < geometries.length; index++) {
  104156. var geometry = geometries[index];
  104157. if (geometry.isReady()) {
  104158. serializeGeometry(geometry, serializationObject.geometries);
  104159. }
  104160. }
  104161. // Meshes
  104162. serializationObject.meshes = [];
  104163. for (index = 0; index < scene.meshes.length; index++) {
  104164. var abstractMesh = scene.meshes[index];
  104165. if (abstractMesh instanceof BABYLON.Mesh) {
  104166. var mesh = abstractMesh;
  104167. if (!mesh.doNotSerialize) {
  104168. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104169. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104170. }
  104171. }
  104172. }
  104173. }
  104174. // Particles Systems
  104175. serializationObject.particleSystems = [];
  104176. for (index = 0; index < scene.particleSystems.length; index++) {
  104177. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  104178. }
  104179. // Action Manager
  104180. if (scene.actionManager) {
  104181. serializationObject.actions = scene.actionManager.serialize("scene");
  104182. }
  104183. // Audio
  104184. serializationObject.sounds = [];
  104185. for (index = 0; index < scene.soundTracks.length; index++) {
  104186. var soundtrack = scene.soundTracks[index];
  104187. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  104188. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  104189. }
  104190. }
  104191. // Components
  104192. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  104193. var component = _c[_b];
  104194. component.serialize(serializationObject);
  104195. }
  104196. return serializationObject;
  104197. };
  104198. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  104199. if (withParents === void 0) { withParents = false; }
  104200. if (withChildren === void 0) { withChildren = false; }
  104201. var serializationObject = {};
  104202. SceneSerializer.ClearCache();
  104203. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  104204. if (withParents || withChildren) {
  104205. //deliberate for loop! not for each, appended should be processed as well.
  104206. for (var i = 0; i < toSerialize.length; ++i) {
  104207. if (withChildren) {
  104208. toSerialize[i].getDescendants().forEach(function (node) {
  104209. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  104210. toSerialize.push(node);
  104211. }
  104212. });
  104213. }
  104214. //make sure the array doesn't contain the object already
  104215. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  104216. toSerialize.push(toSerialize[i].parent);
  104217. }
  104218. }
  104219. }
  104220. toSerialize.forEach(function (mesh) {
  104221. finalizeSingleMesh(mesh, serializationObject);
  104222. });
  104223. return serializationObject;
  104224. };
  104225. return SceneSerializer;
  104226. }());
  104227. BABYLON.SceneSerializer = SceneSerializer;
  104228. })(BABYLON || (BABYLON = {}));
  104229. //# sourceMappingURL=babylon.sceneSerializer.js.map
  104230. var BABYLON;
  104231. (function (BABYLON) {
  104232. /**
  104233. * Class used to generate realtime reflection / refraction cube textures
  104234. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  104235. */
  104236. var ReflectionProbe = /** @class */ (function () {
  104237. /**
  104238. * Creates a new reflection probe
  104239. * @param name defines the name of the probe
  104240. * @param size defines the texture resolution (for each face)
  104241. * @param scene defines the hosting scene
  104242. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  104243. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  104244. */
  104245. function ReflectionProbe(
  104246. /** defines the name of the probe */
  104247. name, size, scene, generateMipMaps, useFloat) {
  104248. if (generateMipMaps === void 0) { generateMipMaps = true; }
  104249. if (useFloat === void 0) { useFloat = false; }
  104250. var _this = this;
  104251. this.name = name;
  104252. this._viewMatrix = BABYLON.Matrix.Identity();
  104253. this._target = BABYLON.Vector3.Zero();
  104254. this._add = BABYLON.Vector3.Zero();
  104255. this._invertYAxis = false;
  104256. /** Gets or sets probe position (center of the cube map) */
  104257. this.position = BABYLON.Vector3.Zero();
  104258. this._scene = scene;
  104259. // Create the scene field if not exist.
  104260. if (!this._scene.reflectionProbes) {
  104261. this._scene.reflectionProbes = new Array();
  104262. }
  104263. this._scene.reflectionProbes.push(this);
  104264. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  104265. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  104266. switch (faceIndex) {
  104267. case 0:
  104268. _this._add.copyFromFloats(1, 0, 0);
  104269. break;
  104270. case 1:
  104271. _this._add.copyFromFloats(-1, 0, 0);
  104272. break;
  104273. case 2:
  104274. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  104275. break;
  104276. case 3:
  104277. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  104278. break;
  104279. case 4:
  104280. _this._add.copyFromFloats(0, 0, 1);
  104281. break;
  104282. case 5:
  104283. _this._add.copyFromFloats(0, 0, -1);
  104284. break;
  104285. }
  104286. if (_this._attachedMesh) {
  104287. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  104288. }
  104289. _this.position.addToRef(_this._add, _this._target);
  104290. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  104291. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  104292. scene._forcedViewPosition = _this.position;
  104293. });
  104294. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  104295. scene._forcedViewPosition = null;
  104296. scene.updateTransformMatrix(true);
  104297. });
  104298. if (scene.activeCamera) {
  104299. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  104300. }
  104301. }
  104302. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  104303. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  104304. get: function () {
  104305. return this._renderTargetTexture.samples;
  104306. },
  104307. set: function (value) {
  104308. this._renderTargetTexture.samples = value;
  104309. },
  104310. enumerable: true,
  104311. configurable: true
  104312. });
  104313. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  104314. /** Gets or sets the refresh rate to use (on every frame by default) */
  104315. get: function () {
  104316. return this._renderTargetTexture.refreshRate;
  104317. },
  104318. set: function (value) {
  104319. this._renderTargetTexture.refreshRate = value;
  104320. },
  104321. enumerable: true,
  104322. configurable: true
  104323. });
  104324. /**
  104325. * Gets the hosting scene
  104326. * @returns a Scene
  104327. */
  104328. ReflectionProbe.prototype.getScene = function () {
  104329. return this._scene;
  104330. };
  104331. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  104332. /** Gets the internal CubeTexture used to render to */
  104333. get: function () {
  104334. return this._renderTargetTexture;
  104335. },
  104336. enumerable: true,
  104337. configurable: true
  104338. });
  104339. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  104340. /** Gets the list of meshes to render */
  104341. get: function () {
  104342. return this._renderTargetTexture.renderList;
  104343. },
  104344. enumerable: true,
  104345. configurable: true
  104346. });
  104347. /**
  104348. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  104349. * @param mesh defines the mesh to attach to
  104350. */
  104351. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  104352. this._attachedMesh = mesh;
  104353. };
  104354. /**
  104355. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  104356. * @param renderingGroupId The rendering group id corresponding to its index
  104357. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  104358. */
  104359. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  104360. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  104361. };
  104362. /**
  104363. * Clean all associated resources
  104364. */
  104365. ReflectionProbe.prototype.dispose = function () {
  104366. var index = this._scene.reflectionProbes.indexOf(this);
  104367. if (index !== -1) {
  104368. // Remove from the scene if found
  104369. this._scene.reflectionProbes.splice(index, 1);
  104370. }
  104371. if (this._renderTargetTexture) {
  104372. this._renderTargetTexture.dispose();
  104373. this._renderTargetTexture = null;
  104374. }
  104375. };
  104376. return ReflectionProbe;
  104377. }());
  104378. BABYLON.ReflectionProbe = ReflectionProbe;
  104379. })(BABYLON || (BABYLON = {}));
  104380. //# sourceMappingURL=babylon.reflectionProbe.js.map
  104381. var BABYLON;
  104382. (function (BABYLON) {
  104383. /**
  104384. * Defines the layer scene component responsible to manage any layers
  104385. * in a given scene.
  104386. */
  104387. var LayerSceneComponent = /** @class */ (function () {
  104388. /**
  104389. * Creates a new instance of the component for the given scene
  104390. * @param scene Defines the scene to register the component in
  104391. */
  104392. function LayerSceneComponent(scene) {
  104393. /**
  104394. * The component name helpfull to identify the component in the list of scene components.
  104395. */
  104396. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  104397. this.scene = scene;
  104398. this._engine = scene.getEngine();
  104399. scene.layers = new Array();
  104400. }
  104401. /**
  104402. * Registers the component in a given scene
  104403. */
  104404. LayerSceneComponent.prototype.register = function () {
  104405. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  104406. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  104407. };
  104408. /**
  104409. * Rebuilds the elements related to this component in case of
  104410. * context lost for instance.
  104411. */
  104412. LayerSceneComponent.prototype.rebuild = function () {
  104413. var layers = this.scene.layers;
  104414. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104415. var layer = layers_1[_i];
  104416. layer._rebuild();
  104417. }
  104418. };
  104419. /**
  104420. * Disposes the component and the associated ressources.
  104421. */
  104422. LayerSceneComponent.prototype.dispose = function () {
  104423. var layers = this.scene.layers;
  104424. while (layers.length) {
  104425. layers[0].dispose();
  104426. }
  104427. };
  104428. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  104429. var layers = this.scene.layers;
  104430. if (layers.length) {
  104431. this._engine.setDepthBuffer(false);
  104432. var cameraLayerMask = camera.layerMask;
  104433. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104434. var layer = layers_2[_i];
  104435. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  104436. layer.render();
  104437. }
  104438. }
  104439. this._engine.setDepthBuffer(true);
  104440. }
  104441. };
  104442. LayerSceneComponent.prototype._drawBackground = function (camera) {
  104443. this._draw(camera, true);
  104444. };
  104445. LayerSceneComponent.prototype._drawForeground = function (camera) {
  104446. this._draw(camera, false);
  104447. };
  104448. return LayerSceneComponent;
  104449. }());
  104450. BABYLON.LayerSceneComponent = LayerSceneComponent;
  104451. })(BABYLON || (BABYLON = {}));
  104452. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  104453. var BABYLON;
  104454. (function (BABYLON) {
  104455. var Layer = /** @class */ (function () {
  104456. function Layer(name, imgUrl, scene, isBackground, color) {
  104457. this.name = name;
  104458. this.scale = new BABYLON.Vector2(1, 1);
  104459. this.offset = new BABYLON.Vector2(0, 0);
  104460. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  104461. this.layerMask = 0x0FFFFFFF;
  104462. this._vertexBuffers = {};
  104463. // Events
  104464. /**
  104465. * An event triggered when the layer is disposed.
  104466. */
  104467. this.onDisposeObservable = new BABYLON.Observable();
  104468. /**
  104469. * An event triggered before rendering the scene
  104470. */
  104471. this.onBeforeRenderObservable = new BABYLON.Observable();
  104472. /**
  104473. * An event triggered after rendering the scene
  104474. */
  104475. this.onAfterRenderObservable = new BABYLON.Observable();
  104476. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  104477. this.isBackground = isBackground === undefined ? true : isBackground;
  104478. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  104479. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  104480. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  104481. if (!layerComponent) {
  104482. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  104483. this._scene._addComponent(layerComponent);
  104484. }
  104485. this._scene.layers.push(this);
  104486. var engine = this._scene.getEngine();
  104487. // VBO
  104488. var vertices = [];
  104489. vertices.push(1, 1);
  104490. vertices.push(-1, 1);
  104491. vertices.push(-1, -1);
  104492. vertices.push(1, -1);
  104493. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  104494. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  104495. this._createIndexBuffer();
  104496. // Effects
  104497. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  104498. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  104499. }
  104500. Object.defineProperty(Layer.prototype, "onDispose", {
  104501. set: function (callback) {
  104502. if (this._onDisposeObserver) {
  104503. this.onDisposeObservable.remove(this._onDisposeObserver);
  104504. }
  104505. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104506. },
  104507. enumerable: true,
  104508. configurable: true
  104509. });
  104510. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  104511. set: function (callback) {
  104512. if (this._onBeforeRenderObserver) {
  104513. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  104514. }
  104515. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  104516. },
  104517. enumerable: true,
  104518. configurable: true
  104519. });
  104520. Object.defineProperty(Layer.prototype, "onAfterRender", {
  104521. set: function (callback) {
  104522. if (this._onAfterRenderObserver) {
  104523. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  104524. }
  104525. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  104526. },
  104527. enumerable: true,
  104528. configurable: true
  104529. });
  104530. Layer.prototype._createIndexBuffer = function () {
  104531. var engine = this._scene.getEngine();
  104532. // Indices
  104533. var indices = [];
  104534. indices.push(0);
  104535. indices.push(1);
  104536. indices.push(2);
  104537. indices.push(0);
  104538. indices.push(2);
  104539. indices.push(3);
  104540. this._indexBuffer = engine.createIndexBuffer(indices);
  104541. };
  104542. /** @hidden */
  104543. Layer.prototype._rebuild = function () {
  104544. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104545. if (vb) {
  104546. vb._rebuild();
  104547. }
  104548. this._createIndexBuffer();
  104549. };
  104550. Layer.prototype.render = function () {
  104551. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  104552. // Check
  104553. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  104554. return;
  104555. var engine = this._scene.getEngine();
  104556. this.onBeforeRenderObservable.notifyObservers(this);
  104557. // Render
  104558. engine.enableEffect(currentEffect);
  104559. engine.setState(false);
  104560. // Texture
  104561. currentEffect.setTexture("textureSampler", this.texture);
  104562. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  104563. // Color
  104564. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  104565. // Scale / offset
  104566. currentEffect.setVector2("offset", this.offset);
  104567. currentEffect.setVector2("scale", this.scale);
  104568. // VBOs
  104569. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  104570. // Draw order
  104571. if (!this.alphaTest) {
  104572. engine.setAlphaMode(this.alphaBlendingMode);
  104573. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104574. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  104575. }
  104576. else {
  104577. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104578. }
  104579. this.onAfterRenderObservable.notifyObservers(this);
  104580. };
  104581. Layer.prototype.dispose = function () {
  104582. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104583. if (vertexBuffer) {
  104584. vertexBuffer.dispose();
  104585. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  104586. }
  104587. if (this._indexBuffer) {
  104588. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  104589. this._indexBuffer = null;
  104590. }
  104591. if (this.texture) {
  104592. this.texture.dispose();
  104593. this.texture = null;
  104594. }
  104595. // Remove from scene
  104596. var index = this._scene.layers.indexOf(this);
  104597. this._scene.layers.splice(index, 1);
  104598. // Callback
  104599. this.onDisposeObservable.notifyObservers(this);
  104600. this.onDisposeObservable.clear();
  104601. this.onAfterRenderObservable.clear();
  104602. this.onBeforeRenderObservable.clear();
  104603. };
  104604. return Layer;
  104605. }());
  104606. BABYLON.Layer = Layer;
  104607. })(BABYLON || (BABYLON = {}));
  104608. //# sourceMappingURL=babylon.layer.js.map
  104609. var BABYLON;
  104610. (function (BABYLON) {
  104611. var TextureTools = /** @class */ (function () {
  104612. function TextureTools() {
  104613. }
  104614. /**
  104615. * Uses the GPU to create a copy texture rescaled at a given size
  104616. * @param texture Texture to copy from
  104617. * @param width Desired width
  104618. * @param height Desired height
  104619. * @return Generated texture
  104620. */
  104621. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  104622. if (useBilinearMode === void 0) { useBilinearMode = true; }
  104623. var scene = texture.getScene();
  104624. var engine = scene.getEngine();
  104625. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  104626. rtt.wrapU = texture.wrapU;
  104627. rtt.wrapV = texture.wrapV;
  104628. rtt.uOffset = texture.uOffset;
  104629. rtt.vOffset = texture.vOffset;
  104630. rtt.uScale = texture.uScale;
  104631. rtt.vScale = texture.vScale;
  104632. rtt.uAng = texture.uAng;
  104633. rtt.vAng = texture.vAng;
  104634. rtt.wAng = texture.wAng;
  104635. rtt.coordinatesIndex = texture.coordinatesIndex;
  104636. rtt.level = texture.level;
  104637. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  104638. rtt._texture.isReady = false;
  104639. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104640. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104641. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  104642. passPostProcess.getEffect().executeWhenCompiled(function () {
  104643. passPostProcess.onApply = function (effect) {
  104644. effect.setTexture("textureSampler", texture);
  104645. };
  104646. var internalTexture = rtt.getInternalTexture();
  104647. if (internalTexture) {
  104648. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  104649. engine.unBindFramebuffer(internalTexture);
  104650. rtt.disposeFramebufferObjects();
  104651. passPostProcess.dispose();
  104652. internalTexture.isReady = true;
  104653. }
  104654. });
  104655. return rtt;
  104656. };
  104657. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  104658. if (!scene._environmentBRDFTexture) {
  104659. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  104660. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104661. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104662. scene._environmentBRDFTexture = texture;
  104663. }
  104664. return scene._environmentBRDFTexture;
  104665. };
  104666. 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=";
  104667. return TextureTools;
  104668. }());
  104669. BABYLON.TextureTools = TextureTools;
  104670. })(BABYLON || (BABYLON = {}));
  104671. //# sourceMappingURL=babylon.textureTools.js.map
  104672. var BABYLON;
  104673. (function (BABYLON) {
  104674. var FramingBehavior = /** @class */ (function () {
  104675. function FramingBehavior() {
  104676. this._mode = FramingBehavior.FitFrustumSidesMode;
  104677. this._radiusScale = 1.0;
  104678. this._positionScale = 0.5;
  104679. this._defaultElevation = 0.3;
  104680. this._elevationReturnTime = 1500;
  104681. this._elevationReturnWaitTime = 1000;
  104682. this._zoomStopsAnimation = false;
  104683. this._framingTime = 1500;
  104684. this._isPointerDown = false;
  104685. this._lastInteractionTime = -Infinity;
  104686. // Framing control
  104687. this._animatables = new Array();
  104688. this._betaIsAnimating = false;
  104689. }
  104690. Object.defineProperty(FramingBehavior.prototype, "name", {
  104691. get: function () {
  104692. return "Framing";
  104693. },
  104694. enumerable: true,
  104695. configurable: true
  104696. });
  104697. Object.defineProperty(FramingBehavior.prototype, "mode", {
  104698. /**
  104699. * Gets current mode used by the behavior.
  104700. */
  104701. get: function () {
  104702. return this._mode;
  104703. },
  104704. /**
  104705. * Sets the current mode used by the behavior
  104706. */
  104707. set: function (mode) {
  104708. this._mode = mode;
  104709. },
  104710. enumerable: true,
  104711. configurable: true
  104712. });
  104713. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  104714. /**
  104715. * Gets the scale applied to the radius
  104716. */
  104717. get: function () {
  104718. return this._radiusScale;
  104719. },
  104720. /**
  104721. * Sets the scale applied to the radius (1 by default)
  104722. */
  104723. set: function (radius) {
  104724. this._radiusScale = radius;
  104725. },
  104726. enumerable: true,
  104727. configurable: true
  104728. });
  104729. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  104730. /**
  104731. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104732. */
  104733. get: function () {
  104734. return this._positionScale;
  104735. },
  104736. /**
  104737. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104738. */
  104739. set: function (scale) {
  104740. this._positionScale = scale;
  104741. },
  104742. enumerable: true,
  104743. configurable: true
  104744. });
  104745. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  104746. /**
  104747. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104748. * behaviour is triggered, in radians.
  104749. */
  104750. get: function () {
  104751. return this._defaultElevation;
  104752. },
  104753. /**
  104754. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104755. * behaviour is triggered, in radians.
  104756. */
  104757. set: function (elevation) {
  104758. this._defaultElevation = elevation;
  104759. },
  104760. enumerable: true,
  104761. configurable: true
  104762. });
  104763. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  104764. /**
  104765. * Gets the time (in milliseconds) taken to return to the default beta position.
  104766. * Negative value indicates camera should not return to default.
  104767. */
  104768. get: function () {
  104769. return this._elevationReturnTime;
  104770. },
  104771. /**
  104772. * Sets the time (in milliseconds) taken to return to the default beta position.
  104773. * Negative value indicates camera should not return to default.
  104774. */
  104775. set: function (speed) {
  104776. this._elevationReturnTime = speed;
  104777. },
  104778. enumerable: true,
  104779. configurable: true
  104780. });
  104781. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  104782. /**
  104783. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104784. */
  104785. get: function () {
  104786. return this._elevationReturnWaitTime;
  104787. },
  104788. /**
  104789. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104790. */
  104791. set: function (time) {
  104792. this._elevationReturnWaitTime = time;
  104793. },
  104794. enumerable: true,
  104795. configurable: true
  104796. });
  104797. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  104798. /**
  104799. * Gets the flag that indicates if user zooming should stop animation.
  104800. */
  104801. get: function () {
  104802. return this._zoomStopsAnimation;
  104803. },
  104804. /**
  104805. * Sets the flag that indicates if user zooming should stop animation.
  104806. */
  104807. set: function (flag) {
  104808. this._zoomStopsAnimation = flag;
  104809. },
  104810. enumerable: true,
  104811. configurable: true
  104812. });
  104813. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  104814. /**
  104815. * Gets the transition time when framing the mesh, in milliseconds
  104816. */
  104817. get: function () {
  104818. return this._framingTime;
  104819. },
  104820. /**
  104821. * Sets the transition time when framing the mesh, in milliseconds
  104822. */
  104823. set: function (time) {
  104824. this._framingTime = time;
  104825. },
  104826. enumerable: true,
  104827. configurable: true
  104828. });
  104829. FramingBehavior.prototype.init = function () {
  104830. // Do notihng
  104831. };
  104832. FramingBehavior.prototype.attach = function (camera) {
  104833. var _this = this;
  104834. this._attachedCamera = camera;
  104835. var scene = this._attachedCamera.getScene();
  104836. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  104837. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  104838. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  104839. _this._isPointerDown = true;
  104840. return;
  104841. }
  104842. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  104843. _this._isPointerDown = false;
  104844. }
  104845. });
  104846. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  104847. if (mesh) {
  104848. _this.zoomOnMesh(mesh);
  104849. }
  104850. });
  104851. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  104852. // Stop the animation if there is user interaction and the animation should stop for this interaction
  104853. _this._applyUserInteraction();
  104854. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  104855. // back to the default position after a given timeout
  104856. _this._maintainCameraAboveGround();
  104857. });
  104858. };
  104859. FramingBehavior.prototype.detach = function () {
  104860. if (!this._attachedCamera) {
  104861. return;
  104862. }
  104863. var scene = this._attachedCamera.getScene();
  104864. if (this._onPrePointerObservableObserver) {
  104865. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  104866. }
  104867. if (this._onAfterCheckInputsObserver) {
  104868. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  104869. }
  104870. if (this._onMeshTargetChangedObserver) {
  104871. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  104872. }
  104873. this._attachedCamera = null;
  104874. };
  104875. /**
  104876. * Targets the given mesh and updates zoom level accordingly.
  104877. * @param mesh The mesh to target.
  104878. * @param radius Optional. If a cached radius position already exists, overrides default.
  104879. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104880. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104881. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104882. */
  104883. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104884. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104885. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104886. mesh.computeWorldMatrix(true);
  104887. var boundingBox = mesh.getBoundingInfo().boundingBox;
  104888. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  104889. };
  104890. /**
  104891. * Targets the given mesh with its children and updates zoom level accordingly.
  104892. * @param mesh The mesh to target.
  104893. * @param radius Optional. If a cached radius position already exists, overrides default.
  104894. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104895. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104896. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104897. */
  104898. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104899. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104900. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104901. mesh.computeWorldMatrix(true);
  104902. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  104903. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  104904. };
  104905. /**
  104906. * Targets the given meshes with their children and updates zoom level accordingly.
  104907. * @param meshes The mesh to target.
  104908. * @param radius Optional. If a cached radius position already exists, overrides default.
  104909. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104910. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104911. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104912. */
  104913. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  104914. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104915. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104916. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  104917. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  104918. for (var i = 0; i < meshes.length; i++) {
  104919. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  104920. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  104921. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  104922. }
  104923. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  104924. };
  104925. /**
  104926. * Targets the given mesh and updates zoom level accordingly.
  104927. * @param mesh The mesh to target.
  104928. * @param radius Optional. If a cached radius position already exists, overrides default.
  104929. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104930. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104931. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104932. */
  104933. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  104934. var _this = this;
  104935. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104936. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104937. var zoomTarget;
  104938. if (!this._attachedCamera) {
  104939. return;
  104940. }
  104941. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  104942. var bottom = minimumWorld.y;
  104943. var top = maximumWorld.y;
  104944. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  104945. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  104946. if (focusOnOriginXZ) {
  104947. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  104948. }
  104949. else {
  104950. var centerWorld = minimumWorld.add(radiusWorld);
  104951. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  104952. }
  104953. if (!this._vectorTransition) {
  104954. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  104955. }
  104956. this._betaIsAnimating = true;
  104957. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  104958. if (animatable) {
  104959. this._animatables.push(animatable);
  104960. }
  104961. // sets the radius and lower radius bounds
  104962. // Small delta ensures camera is not always at lower zoom limit.
  104963. var radius = 0;
  104964. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  104965. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  104966. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  104967. radius = position;
  104968. }
  104969. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  104970. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  104971. if (this._attachedCamera.lowerRadiusLimit === null) {
  104972. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  104973. }
  104974. }
  104975. // Set sensibilities
  104976. var extend = maximumWorld.subtract(minimumWorld).length();
  104977. this._attachedCamera.panningSensibility = 5000 / extend;
  104978. this._attachedCamera.wheelPrecision = 100 / radius;
  104979. // transition to new radius
  104980. if (!this._radiusTransition) {
  104981. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  104982. }
  104983. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  104984. _this.stopAllAnimations();
  104985. if (onAnimationEnd) {
  104986. onAnimationEnd();
  104987. }
  104988. if (_this._attachedCamera) {
  104989. _this._attachedCamera.storeState();
  104990. }
  104991. });
  104992. if (animatable) {
  104993. this._animatables.push(animatable);
  104994. }
  104995. };
  104996. /**
  104997. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  104998. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  104999. * frustum width.
  105000. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  105001. * to fully enclose the mesh in the viewing frustum.
  105002. */
  105003. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  105004. var size = maximumWorld.subtract(minimumWorld);
  105005. var boxVectorGlobalDiagonal = size.length();
  105006. var frustumSlope = this._getFrustumSlope();
  105007. // Formula for setting distance
  105008. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  105009. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  105010. // Horizon distance
  105011. var radius = radiusWithoutFraming * this._radiusScale;
  105012. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  105013. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  105014. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  105015. var camera = this._attachedCamera;
  105016. if (!camera) {
  105017. return 0;
  105018. }
  105019. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105020. // Don't exceed the requested limit
  105021. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  105022. }
  105023. // Don't exceed the upper radius limit
  105024. if (camera.upperRadiusLimit) {
  105025. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  105026. }
  105027. return distance;
  105028. };
  105029. /**
  105030. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  105031. * is automatically returned to its default position (expected to be above ground plane).
  105032. */
  105033. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  105034. var _this = this;
  105035. if (this._elevationReturnTime < 0) {
  105036. return;
  105037. }
  105038. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  105039. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  105040. var limitBeta = Math.PI * 0.5;
  105041. // Bring the camera back up if below the ground plane
  105042. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  105043. this._betaIsAnimating = true;
  105044. //Transition to new position
  105045. this.stopAllAnimations();
  105046. if (!this._betaTransition) {
  105047. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105048. }
  105049. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  105050. _this._clearAnimationLocks();
  105051. _this.stopAllAnimations();
  105052. });
  105053. if (animatabe) {
  105054. this._animatables.push(animatabe);
  105055. }
  105056. }
  105057. };
  105058. /**
  105059. * Returns the frustum slope based on the canvas ratio and camera FOV
  105060. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  105061. */
  105062. FramingBehavior.prototype._getFrustumSlope = function () {
  105063. // Calculate the viewport ratio
  105064. // Aspect Ratio is Height/Width.
  105065. var camera = this._attachedCamera;
  105066. if (!camera) {
  105067. return BABYLON.Vector2.Zero();
  105068. }
  105069. var engine = camera.getScene().getEngine();
  105070. var aspectRatio = engine.getAspectRatio(camera);
  105071. // Camera FOV is the vertical field of view (top-bottom) in radians.
  105072. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  105073. var frustumSlopeY = Math.tan(camera.fov / 2);
  105074. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  105075. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  105076. // along the forward vector.
  105077. var frustumSlopeX = frustumSlopeY * aspectRatio;
  105078. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  105079. };
  105080. /**
  105081. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  105082. */
  105083. FramingBehavior.prototype._clearAnimationLocks = function () {
  105084. this._betaIsAnimating = false;
  105085. };
  105086. /**
  105087. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105088. */
  105089. FramingBehavior.prototype._applyUserInteraction = function () {
  105090. if (this.isUserIsMoving) {
  105091. this._lastInteractionTime = BABYLON.Tools.Now;
  105092. this.stopAllAnimations();
  105093. this._clearAnimationLocks();
  105094. }
  105095. };
  105096. /**
  105097. * Stops and removes all animations that have been applied to the camera
  105098. */
  105099. FramingBehavior.prototype.stopAllAnimations = function () {
  105100. if (this._attachedCamera) {
  105101. this._attachedCamera.animations = [];
  105102. }
  105103. while (this._animatables.length) {
  105104. if (this._animatables[0]) {
  105105. this._animatables[0].onAnimationEnd = null;
  105106. this._animatables[0].stop();
  105107. }
  105108. this._animatables.shift();
  105109. }
  105110. };
  105111. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  105112. /**
  105113. * Gets a value indicating if the user is moving the camera
  105114. */
  105115. get: function () {
  105116. if (!this._attachedCamera) {
  105117. return false;
  105118. }
  105119. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105120. this._attachedCamera.inertialBetaOffset !== 0 ||
  105121. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105122. this._attachedCamera.inertialPanningX !== 0 ||
  105123. this._attachedCamera.inertialPanningY !== 0 ||
  105124. this._isPointerDown;
  105125. },
  105126. enumerable: true,
  105127. configurable: true
  105128. });
  105129. /**
  105130. * The easing function used by animations
  105131. */
  105132. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  105133. /**
  105134. * The easing mode used by animations
  105135. */
  105136. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  105137. // Statics
  105138. /**
  105139. * The camera can move all the way towards the mesh.
  105140. */
  105141. FramingBehavior.IgnoreBoundsSizeMode = 0;
  105142. /**
  105143. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  105144. */
  105145. FramingBehavior.FitFrustumSidesMode = 1;
  105146. return FramingBehavior;
  105147. }());
  105148. BABYLON.FramingBehavior = FramingBehavior;
  105149. })(BABYLON || (BABYLON = {}));
  105150. //# sourceMappingURL=babylon.framingBehavior.js.map
  105151. var BABYLON;
  105152. (function (BABYLON) {
  105153. /**
  105154. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  105155. */
  105156. var BouncingBehavior = /** @class */ (function () {
  105157. function BouncingBehavior() {
  105158. /**
  105159. * The duration of the animation, in milliseconds
  105160. */
  105161. this.transitionDuration = 450;
  105162. /**
  105163. * Length of the distance animated by the transition when lower radius is reached
  105164. */
  105165. this.lowerRadiusTransitionRange = 2;
  105166. /**
  105167. * Length of the distance animated by the transition when upper radius is reached
  105168. */
  105169. this.upperRadiusTransitionRange = -2;
  105170. this._autoTransitionRange = false;
  105171. // Animations
  105172. this._radiusIsAnimating = false;
  105173. this._radiusBounceTransition = null;
  105174. this._animatables = new Array();
  105175. }
  105176. Object.defineProperty(BouncingBehavior.prototype, "name", {
  105177. get: function () {
  105178. return "Bouncing";
  105179. },
  105180. enumerable: true,
  105181. configurable: true
  105182. });
  105183. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  105184. /**
  105185. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105186. */
  105187. get: function () {
  105188. return this._autoTransitionRange;
  105189. },
  105190. /**
  105191. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105192. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  105193. */
  105194. set: function (value) {
  105195. var _this = this;
  105196. if (this._autoTransitionRange === value) {
  105197. return;
  105198. }
  105199. this._autoTransitionRange = value;
  105200. var camera = this._attachedCamera;
  105201. if (!camera) {
  105202. return;
  105203. }
  105204. if (value) {
  105205. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105206. if (!mesh) {
  105207. return;
  105208. }
  105209. mesh.computeWorldMatrix(true);
  105210. var diagonal = mesh.getBoundingInfo().diagonalLength;
  105211. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  105212. _this.upperRadiusTransitionRange = diagonal * 0.05;
  105213. });
  105214. }
  105215. else if (this._onMeshTargetChangedObserver) {
  105216. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105217. }
  105218. },
  105219. enumerable: true,
  105220. configurable: true
  105221. });
  105222. BouncingBehavior.prototype.init = function () {
  105223. // Do notihng
  105224. };
  105225. BouncingBehavior.prototype.attach = function (camera) {
  105226. var _this = this;
  105227. this._attachedCamera = camera;
  105228. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105229. if (!_this._attachedCamera) {
  105230. return;
  105231. }
  105232. // Add the bounce animation to the lower radius limit
  105233. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  105234. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  105235. }
  105236. // Add the bounce animation to the upper radius limit
  105237. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  105238. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  105239. }
  105240. });
  105241. };
  105242. BouncingBehavior.prototype.detach = function () {
  105243. if (!this._attachedCamera) {
  105244. return;
  105245. }
  105246. if (this._onAfterCheckInputsObserver) {
  105247. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105248. }
  105249. if (this._onMeshTargetChangedObserver) {
  105250. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105251. }
  105252. this._attachedCamera = null;
  105253. };
  105254. /**
  105255. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  105256. * @param radiusLimit The limit to check against.
  105257. * @return Bool to indicate if at limit.
  105258. */
  105259. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  105260. if (!this._attachedCamera) {
  105261. return false;
  105262. }
  105263. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  105264. return true;
  105265. }
  105266. return false;
  105267. };
  105268. /**
  105269. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  105270. * @param radiusDelta The delta by which to animate to. Can be negative.
  105271. */
  105272. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  105273. var _this = this;
  105274. if (!this._attachedCamera) {
  105275. return;
  105276. }
  105277. if (!this._radiusBounceTransition) {
  105278. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  105279. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  105280. }
  105281. // Prevent zoom until bounce has completed
  105282. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  105283. this._attachedCamera.wheelPrecision = Infinity;
  105284. this._attachedCamera.inertialRadiusOffset = 0;
  105285. // Animate to the radius limit
  105286. this.stopAllAnimations();
  105287. this._radiusIsAnimating = true;
  105288. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  105289. if (animatable) {
  105290. this._animatables.push(animatable);
  105291. }
  105292. };
  105293. /**
  105294. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  105295. */
  105296. BouncingBehavior.prototype._clearAnimationLocks = function () {
  105297. this._radiusIsAnimating = false;
  105298. if (this._attachedCamera) {
  105299. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  105300. }
  105301. };
  105302. /**
  105303. * Stops and removes all animations that have been applied to the camera
  105304. */
  105305. BouncingBehavior.prototype.stopAllAnimations = function () {
  105306. if (this._attachedCamera) {
  105307. this._attachedCamera.animations = [];
  105308. }
  105309. while (this._animatables.length) {
  105310. this._animatables[0].onAnimationEnd = null;
  105311. this._animatables[0].stop();
  105312. this._animatables.shift();
  105313. }
  105314. };
  105315. /**
  105316. * The easing function used by animations
  105317. */
  105318. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  105319. /**
  105320. * The easing mode used by animations
  105321. */
  105322. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  105323. return BouncingBehavior;
  105324. }());
  105325. BABYLON.BouncingBehavior = BouncingBehavior;
  105326. })(BABYLON || (BABYLON = {}));
  105327. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  105328. var BABYLON;
  105329. (function (BABYLON) {
  105330. var AutoRotationBehavior = /** @class */ (function () {
  105331. function AutoRotationBehavior() {
  105332. this._zoomStopsAnimation = false;
  105333. this._idleRotationSpeed = 0.05;
  105334. this._idleRotationWaitTime = 2000;
  105335. this._idleRotationSpinupTime = 2000;
  105336. this._isPointerDown = false;
  105337. this._lastFrameTime = null;
  105338. this._lastInteractionTime = -Infinity;
  105339. this._cameraRotationSpeed = 0;
  105340. this._lastFrameRadius = 0;
  105341. }
  105342. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  105343. get: function () {
  105344. return "AutoRotation";
  105345. },
  105346. enumerable: true,
  105347. configurable: true
  105348. });
  105349. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  105350. /**
  105351. * Gets the flag that indicates if user zooming should stop animation.
  105352. */
  105353. get: function () {
  105354. return this._zoomStopsAnimation;
  105355. },
  105356. /**
  105357. * Sets the flag that indicates if user zooming should stop animation.
  105358. */
  105359. set: function (flag) {
  105360. this._zoomStopsAnimation = flag;
  105361. },
  105362. enumerable: true,
  105363. configurable: true
  105364. });
  105365. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  105366. /**
  105367. * Gets the default speed at which the camera rotates around the model.
  105368. */
  105369. get: function () {
  105370. return this._idleRotationSpeed;
  105371. },
  105372. /**
  105373. * Sets the default speed at which the camera rotates around the model.
  105374. */
  105375. set: function (speed) {
  105376. this._idleRotationSpeed = speed;
  105377. },
  105378. enumerable: true,
  105379. configurable: true
  105380. });
  105381. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  105382. /**
  105383. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  105384. */
  105385. get: function () {
  105386. return this._idleRotationWaitTime;
  105387. },
  105388. /**
  105389. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  105390. */
  105391. set: function (time) {
  105392. this._idleRotationWaitTime = time;
  105393. },
  105394. enumerable: true,
  105395. configurable: true
  105396. });
  105397. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  105398. /**
  105399. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105400. */
  105401. get: function () {
  105402. return this._idleRotationSpinupTime;
  105403. },
  105404. /**
  105405. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105406. */
  105407. set: function (time) {
  105408. this._idleRotationSpinupTime = time;
  105409. },
  105410. enumerable: true,
  105411. configurable: true
  105412. });
  105413. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  105414. /**
  105415. * Gets a value indicating if the camera is currently rotating because of this behavior
  105416. */
  105417. get: function () {
  105418. return Math.abs(this._cameraRotationSpeed) > 0;
  105419. },
  105420. enumerable: true,
  105421. configurable: true
  105422. });
  105423. AutoRotationBehavior.prototype.init = function () {
  105424. // Do notihng
  105425. };
  105426. AutoRotationBehavior.prototype.attach = function (camera) {
  105427. var _this = this;
  105428. this._attachedCamera = camera;
  105429. var scene = this._attachedCamera.getScene();
  105430. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105431. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105432. _this._isPointerDown = true;
  105433. return;
  105434. }
  105435. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105436. _this._isPointerDown = false;
  105437. }
  105438. });
  105439. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105440. var now = BABYLON.Tools.Now;
  105441. var dt = 0;
  105442. if (_this._lastFrameTime != null) {
  105443. dt = now - _this._lastFrameTime;
  105444. }
  105445. _this._lastFrameTime = now;
  105446. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105447. _this._applyUserInteraction();
  105448. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  105449. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  105450. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  105451. // Step camera rotation by rotation speed
  105452. if (_this._attachedCamera) {
  105453. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  105454. }
  105455. });
  105456. };
  105457. AutoRotationBehavior.prototype.detach = function () {
  105458. if (!this._attachedCamera) {
  105459. return;
  105460. }
  105461. var scene = this._attachedCamera.getScene();
  105462. if (this._onPrePointerObservableObserver) {
  105463. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  105464. }
  105465. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105466. this._attachedCamera = null;
  105467. };
  105468. /**
  105469. * Returns true if user is scrolling.
  105470. * @return true if user is scrolling.
  105471. */
  105472. AutoRotationBehavior.prototype._userIsZooming = function () {
  105473. if (!this._attachedCamera) {
  105474. return false;
  105475. }
  105476. return this._attachedCamera.inertialRadiusOffset !== 0;
  105477. };
  105478. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  105479. if (!this._attachedCamera) {
  105480. return false;
  105481. }
  105482. var zoomHasHitLimit = false;
  105483. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  105484. zoomHasHitLimit = true;
  105485. }
  105486. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  105487. this._lastFrameRadius = this._attachedCamera.radius;
  105488. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  105489. };
  105490. /**
  105491. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105492. */
  105493. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  105494. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  105495. this._lastInteractionTime = BABYLON.Tools.Now;
  105496. }
  105497. };
  105498. // Tools
  105499. AutoRotationBehavior.prototype._userIsMoving = function () {
  105500. if (!this._attachedCamera) {
  105501. return false;
  105502. }
  105503. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105504. this._attachedCamera.inertialBetaOffset !== 0 ||
  105505. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105506. this._attachedCamera.inertialPanningX !== 0 ||
  105507. this._attachedCamera.inertialPanningY !== 0 ||
  105508. this._isPointerDown;
  105509. };
  105510. return AutoRotationBehavior;
  105511. }());
  105512. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  105513. })(BABYLON || (BABYLON = {}));
  105514. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  105515. var BABYLON;
  105516. (function (BABYLON) {
  105517. var NullEngineOptions = /** @class */ (function () {
  105518. function NullEngineOptions() {
  105519. this.renderWidth = 512;
  105520. this.renderHeight = 256;
  105521. this.textureSize = 512;
  105522. this.deterministicLockstep = false;
  105523. this.lockstepMaxSteps = 4;
  105524. }
  105525. return NullEngineOptions;
  105526. }());
  105527. BABYLON.NullEngineOptions = NullEngineOptions;
  105528. /**
  105529. * The null engine class provides support for headless version of babylon.js.
  105530. * This can be used in server side scenario or for testing purposes
  105531. */
  105532. var NullEngine = /** @class */ (function (_super) {
  105533. __extends(NullEngine, _super);
  105534. function NullEngine(options) {
  105535. if (options === void 0) { options = new NullEngineOptions(); }
  105536. var _this = _super.call(this, null) || this;
  105537. if (options.deterministicLockstep === undefined) {
  105538. options.deterministicLockstep = false;
  105539. }
  105540. if (options.lockstepMaxSteps === undefined) {
  105541. options.lockstepMaxSteps = 4;
  105542. }
  105543. _this._options = options;
  105544. // Init caps
  105545. // We consider we are on a webgl1 capable device
  105546. _this._caps = new BABYLON.EngineCapabilities();
  105547. _this._caps.maxTexturesImageUnits = 16;
  105548. _this._caps.maxVertexTextureImageUnits = 16;
  105549. _this._caps.maxTextureSize = 512;
  105550. _this._caps.maxCubemapTextureSize = 512;
  105551. _this._caps.maxRenderTextureSize = 512;
  105552. _this._caps.maxVertexAttribs = 16;
  105553. _this._caps.maxVaryingVectors = 16;
  105554. _this._caps.maxFragmentUniformVectors = 16;
  105555. _this._caps.maxVertexUniformVectors = 16;
  105556. // Extensions
  105557. _this._caps.standardDerivatives = false;
  105558. _this._caps.astc = null;
  105559. _this._caps.s3tc = null;
  105560. _this._caps.pvrtc = null;
  105561. _this._caps.etc1 = null;
  105562. _this._caps.etc2 = null;
  105563. _this._caps.textureAnisotropicFilterExtension = null;
  105564. _this._caps.maxAnisotropy = 0;
  105565. _this._caps.uintIndices = false;
  105566. _this._caps.fragmentDepthSupported = false;
  105567. _this._caps.highPrecisionShaderSupported = true;
  105568. _this._caps.colorBufferFloat = false;
  105569. _this._caps.textureFloat = false;
  105570. _this._caps.textureFloatLinearFiltering = false;
  105571. _this._caps.textureFloatRender = false;
  105572. _this._caps.textureHalfFloat = false;
  105573. _this._caps.textureHalfFloatLinearFiltering = false;
  105574. _this._caps.textureHalfFloatRender = false;
  105575. _this._caps.textureLOD = false;
  105576. _this._caps.drawBuffersExtension = false;
  105577. _this._caps.depthTextureExtension = false;
  105578. _this._caps.vertexArrayObject = false;
  105579. _this._caps.instancedArrays = false;
  105580. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  105581. // Wrappers
  105582. if (typeof URL === "undefined") {
  105583. URL = {
  105584. createObjectURL: function () { },
  105585. revokeObjectURL: function () { }
  105586. };
  105587. }
  105588. if (typeof Blob === "undefined") {
  105589. Blob = function () { };
  105590. }
  105591. return _this;
  105592. }
  105593. NullEngine.prototype.isDeterministicLockStep = function () {
  105594. return this._options.deterministicLockstep;
  105595. };
  105596. NullEngine.prototype.getLockstepMaxSteps = function () {
  105597. return this._options.lockstepMaxSteps;
  105598. };
  105599. NullEngine.prototype.getHardwareScalingLevel = function () {
  105600. return 1.0;
  105601. };
  105602. NullEngine.prototype.createVertexBuffer = function (vertices) {
  105603. return {
  105604. capacity: 0,
  105605. references: 1,
  105606. is32Bits: false
  105607. };
  105608. };
  105609. NullEngine.prototype.createIndexBuffer = function (indices) {
  105610. return {
  105611. capacity: 0,
  105612. references: 1,
  105613. is32Bits: false
  105614. };
  105615. };
  105616. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  105617. if (stencil === void 0) { stencil = false; }
  105618. };
  105619. NullEngine.prototype.getRenderWidth = function (useScreen) {
  105620. if (useScreen === void 0) { useScreen = false; }
  105621. if (!useScreen && this._currentRenderTarget) {
  105622. return this._currentRenderTarget.width;
  105623. }
  105624. return this._options.renderWidth;
  105625. };
  105626. NullEngine.prototype.getRenderHeight = function (useScreen) {
  105627. if (useScreen === void 0) { useScreen = false; }
  105628. if (!useScreen && this._currentRenderTarget) {
  105629. return this._currentRenderTarget.height;
  105630. }
  105631. return this._options.renderHeight;
  105632. };
  105633. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  105634. this._cachedViewport = viewport;
  105635. };
  105636. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  105637. return {
  105638. transformFeedback: null,
  105639. __SPECTOR_rebuildProgram: null
  105640. };
  105641. };
  105642. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  105643. return [];
  105644. };
  105645. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  105646. return [];
  105647. };
  105648. NullEngine.prototype.bindSamplers = function (effect) {
  105649. this._currentEffect = null;
  105650. };
  105651. NullEngine.prototype.enableEffect = function (effect) {
  105652. this._currentEffect = effect;
  105653. if (effect.onBind) {
  105654. effect.onBind(effect);
  105655. }
  105656. if (effect._onBindObservable) {
  105657. effect._onBindObservable.notifyObservers(effect);
  105658. }
  105659. };
  105660. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  105661. if (zOffset === void 0) { zOffset = 0; }
  105662. if (reverseSide === void 0) { reverseSide = false; }
  105663. };
  105664. NullEngine.prototype.setIntArray = function (uniform, array) {
  105665. };
  105666. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  105667. };
  105668. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  105669. };
  105670. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  105671. };
  105672. NullEngine.prototype.setFloatArray = function (uniform, array) {
  105673. };
  105674. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  105675. };
  105676. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  105677. };
  105678. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  105679. };
  105680. NullEngine.prototype.setArray = function (uniform, array) {
  105681. };
  105682. NullEngine.prototype.setArray2 = function (uniform, array) {
  105683. };
  105684. NullEngine.prototype.setArray3 = function (uniform, array) {
  105685. };
  105686. NullEngine.prototype.setArray4 = function (uniform, array) {
  105687. };
  105688. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  105689. };
  105690. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  105691. };
  105692. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  105693. };
  105694. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  105695. };
  105696. NullEngine.prototype.setFloat = function (uniform, value) {
  105697. };
  105698. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  105699. };
  105700. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  105701. };
  105702. NullEngine.prototype.setBool = function (uniform, bool) {
  105703. };
  105704. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  105705. };
  105706. NullEngine.prototype.setColor3 = function (uniform, color3) {
  105707. };
  105708. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  105709. };
  105710. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  105711. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  105712. if (this._alphaMode === mode) {
  105713. return;
  105714. }
  105715. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  105716. if (!noDepthWriteChange) {
  105717. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  105718. }
  105719. this._alphaMode = mode;
  105720. };
  105721. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  105722. };
  105723. NullEngine.prototype.wipeCaches = function (bruteForce) {
  105724. if (this.preventCacheWipeBetweenFrames) {
  105725. return;
  105726. }
  105727. this.resetTextureCache();
  105728. this._currentEffect = null;
  105729. if (bruteForce) {
  105730. this._currentProgram = null;
  105731. this._stencilState.reset();
  105732. this._depthCullingState.reset();
  105733. this._alphaState.reset();
  105734. }
  105735. this._cachedVertexBuffers = null;
  105736. this._cachedIndexBuffer = null;
  105737. this._cachedEffectForVertexBuffers = null;
  105738. };
  105739. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  105740. };
  105741. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  105742. };
  105743. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  105744. };
  105745. /** @hidden */
  105746. NullEngine.prototype._createTexture = function () {
  105747. return {};
  105748. };
  105749. /** @hidden */
  105750. NullEngine.prototype._releaseTexture = function (texture) {
  105751. };
  105752. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  105753. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  105754. if (onLoad === void 0) { onLoad = null; }
  105755. if (onError === void 0) { onError = null; }
  105756. if (buffer === void 0) { buffer = null; }
  105757. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  105758. var url = String(urlArg);
  105759. texture.url = url;
  105760. texture.generateMipMaps = !noMipmap;
  105761. texture.samplingMode = samplingMode;
  105762. texture.invertY = invertY;
  105763. texture.baseWidth = this._options.textureSize;
  105764. texture.baseHeight = this._options.textureSize;
  105765. texture.width = this._options.textureSize;
  105766. texture.height = this._options.textureSize;
  105767. if (format) {
  105768. texture.format = format;
  105769. }
  105770. texture.isReady = true;
  105771. if (onLoad) {
  105772. onLoad();
  105773. }
  105774. this._internalTexturesCache.push(texture);
  105775. return texture;
  105776. };
  105777. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  105778. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  105779. if (options !== undefined && typeof options === "object") {
  105780. fullOptions.generateMipMaps = options.generateMipMaps;
  105781. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  105782. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  105783. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  105784. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  105785. }
  105786. else {
  105787. fullOptions.generateMipMaps = options;
  105788. fullOptions.generateDepthBuffer = true;
  105789. fullOptions.generateStencilBuffer = false;
  105790. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105791. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  105792. }
  105793. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  105794. var width = size.width || size;
  105795. var height = size.height || size;
  105796. texture._depthStencilBuffer = {};
  105797. texture._framebuffer = {};
  105798. texture.baseWidth = width;
  105799. texture.baseHeight = height;
  105800. texture.width = width;
  105801. texture.height = height;
  105802. texture.isReady = true;
  105803. texture.samples = 1;
  105804. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  105805. texture.samplingMode = fullOptions.samplingMode;
  105806. texture.type = fullOptions.type;
  105807. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  105808. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  105809. this._internalTexturesCache.push(texture);
  105810. return texture;
  105811. };
  105812. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  105813. texture.samplingMode = samplingMode;
  105814. };
  105815. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  105816. if (this._currentRenderTarget) {
  105817. this.unBindFramebuffer(this._currentRenderTarget);
  105818. }
  105819. this._currentRenderTarget = texture;
  105820. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  105821. if (this._cachedViewport && !forceFullscreenViewport) {
  105822. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  105823. }
  105824. };
  105825. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  105826. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  105827. this._currentRenderTarget = null;
  105828. if (onBeforeUnbind) {
  105829. if (texture._MSAAFramebuffer) {
  105830. this._currentFramebuffer = texture._framebuffer;
  105831. }
  105832. onBeforeUnbind();
  105833. }
  105834. this._currentFramebuffer = null;
  105835. };
  105836. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  105837. var vbo = {
  105838. capacity: 1,
  105839. references: 1,
  105840. is32Bits: false
  105841. };
  105842. return vbo;
  105843. };
  105844. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  105845. if (premulAlpha === void 0) { premulAlpha = false; }
  105846. };
  105847. /**
  105848. * @hidden
  105849. * Get the current error code of the webGL context
  105850. * @returns the error code
  105851. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  105852. */
  105853. NullEngine.prototype.getError = function () {
  105854. return 0;
  105855. };
  105856. /** @hidden */
  105857. NullEngine.prototype._getUnpackAlignement = function () {
  105858. return 1;
  105859. };
  105860. /** @hidden */
  105861. NullEngine.prototype._unpackFlipY = function (value) {
  105862. };
  105863. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  105864. if (offset === void 0) { offset = 0; }
  105865. };
  105866. /**
  105867. * Updates a dynamic vertex buffer.
  105868. * @param vertexBuffer the vertex buffer to update
  105869. * @param data the data used to update the vertex buffer
  105870. * @param byteOffset the byte offset of the data (optional)
  105871. * @param byteLength the byte length of the data (optional)
  105872. */
  105873. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  105874. };
  105875. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  105876. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  105877. this._boundTexturesCache[this._activeChannel] = texture;
  105878. return true;
  105879. }
  105880. return false;
  105881. };
  105882. /** @hidden */
  105883. NullEngine.prototype._bindTexture = function (channel, texture) {
  105884. if (channel < 0) {
  105885. return;
  105886. }
  105887. this._bindTextureDirectly(0, texture);
  105888. };
  105889. /** @hidden */
  105890. NullEngine.prototype._releaseBuffer = function (buffer) {
  105891. buffer.references--;
  105892. if (buffer.references === 0) {
  105893. return true;
  105894. }
  105895. return false;
  105896. };
  105897. NullEngine.prototype.releaseEffects = function () {
  105898. };
  105899. NullEngine.prototype.displayLoadingUI = function () {
  105900. };
  105901. NullEngine.prototype.hideLoadingUI = function () {
  105902. };
  105903. /** @hidden */
  105904. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  105905. if (faceIndex === void 0) { faceIndex = 0; }
  105906. if (lod === void 0) { lod = 0; }
  105907. };
  105908. /** @hidden */
  105909. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  105910. if (faceIndex === void 0) { faceIndex = 0; }
  105911. if (lod === void 0) { lod = 0; }
  105912. };
  105913. /** @hidden */
  105914. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  105915. if (faceIndex === void 0) { faceIndex = 0; }
  105916. if (lod === void 0) { lod = 0; }
  105917. };
  105918. /** @hidden */
  105919. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  105920. if (faceIndex === void 0) { faceIndex = 0; }
  105921. if (lod === void 0) { lod = 0; }
  105922. };
  105923. return NullEngine;
  105924. }(BABYLON.Engine));
  105925. BABYLON.NullEngine = NullEngine;
  105926. })(BABYLON || (BABYLON = {}));
  105927. //# sourceMappingURL=babylon.nullEngine.js.map
  105928. var BABYLON;
  105929. (function (BABYLON) {
  105930. /**
  105931. * This class can be used to get instrumentation data from a Babylon engine
  105932. */
  105933. var EngineInstrumentation = /** @class */ (function () {
  105934. function EngineInstrumentation(engine) {
  105935. this.engine = engine;
  105936. this._captureGPUFrameTime = false;
  105937. this._gpuFrameTime = new BABYLON.PerfCounter();
  105938. this._captureShaderCompilationTime = false;
  105939. this._shaderCompilationTime = new BABYLON.PerfCounter();
  105940. // Observers
  105941. this._onBeginFrameObserver = null;
  105942. this._onEndFrameObserver = null;
  105943. this._onBeforeShaderCompilationObserver = null;
  105944. this._onAfterShaderCompilationObserver = null;
  105945. }
  105946. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  105947. // Properties
  105948. /**
  105949. * Gets the perf counter used for GPU frame time
  105950. */
  105951. get: function () {
  105952. return this._gpuFrameTime;
  105953. },
  105954. enumerable: true,
  105955. configurable: true
  105956. });
  105957. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  105958. /**
  105959. * Gets the GPU frame time capture status
  105960. */
  105961. get: function () {
  105962. return this._captureGPUFrameTime;
  105963. },
  105964. /**
  105965. * Enable or disable the GPU frame time capture
  105966. */
  105967. set: function (value) {
  105968. var _this = this;
  105969. if (value === this._captureGPUFrameTime) {
  105970. return;
  105971. }
  105972. this._captureGPUFrameTime = value;
  105973. if (value) {
  105974. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  105975. if (!_this._gpuFrameTimeToken) {
  105976. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  105977. }
  105978. });
  105979. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  105980. if (!_this._gpuFrameTimeToken) {
  105981. return;
  105982. }
  105983. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  105984. if (time > -1) {
  105985. _this._gpuFrameTimeToken = null;
  105986. _this._gpuFrameTime.fetchNewFrame();
  105987. _this._gpuFrameTime.addCount(time, true);
  105988. }
  105989. });
  105990. }
  105991. else {
  105992. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  105993. this._onBeginFrameObserver = null;
  105994. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  105995. this._onEndFrameObserver = null;
  105996. }
  105997. },
  105998. enumerable: true,
  105999. configurable: true
  106000. });
  106001. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  106002. /**
  106003. * Gets the perf counter used for shader compilation time
  106004. */
  106005. get: function () {
  106006. return this._shaderCompilationTime;
  106007. },
  106008. enumerable: true,
  106009. configurable: true
  106010. });
  106011. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  106012. /**
  106013. * Gets the shader compilation time capture status
  106014. */
  106015. get: function () {
  106016. return this._captureShaderCompilationTime;
  106017. },
  106018. /**
  106019. * Enable or disable the shader compilation time capture
  106020. */
  106021. set: function (value) {
  106022. var _this = this;
  106023. if (value === this._captureShaderCompilationTime) {
  106024. return;
  106025. }
  106026. this._captureShaderCompilationTime = value;
  106027. if (value) {
  106028. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  106029. _this._shaderCompilationTime.fetchNewFrame();
  106030. _this._shaderCompilationTime.beginMonitoring();
  106031. });
  106032. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  106033. _this._shaderCompilationTime.endMonitoring();
  106034. });
  106035. }
  106036. else {
  106037. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106038. this._onBeforeShaderCompilationObserver = null;
  106039. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106040. this._onAfterShaderCompilationObserver = null;
  106041. }
  106042. },
  106043. enumerable: true,
  106044. configurable: true
  106045. });
  106046. EngineInstrumentation.prototype.dispose = function () {
  106047. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106048. this._onBeginFrameObserver = null;
  106049. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106050. this._onEndFrameObserver = null;
  106051. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106052. this._onBeforeShaderCompilationObserver = null;
  106053. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106054. this._onAfterShaderCompilationObserver = null;
  106055. this.engine = null;
  106056. };
  106057. return EngineInstrumentation;
  106058. }());
  106059. BABYLON.EngineInstrumentation = EngineInstrumentation;
  106060. })(BABYLON || (BABYLON = {}));
  106061. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  106062. var BABYLON;
  106063. (function (BABYLON) {
  106064. /**
  106065. * This class can be used to get instrumentation data from a Babylon engine
  106066. */
  106067. var SceneInstrumentation = /** @class */ (function () {
  106068. function SceneInstrumentation(scene) {
  106069. var _this = this;
  106070. this.scene = scene;
  106071. this._captureActiveMeshesEvaluationTime = false;
  106072. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  106073. this._captureRenderTargetsRenderTime = false;
  106074. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  106075. this._captureFrameTime = false;
  106076. this._frameTime = new BABYLON.PerfCounter();
  106077. this._captureRenderTime = false;
  106078. this._renderTime = new BABYLON.PerfCounter();
  106079. this._captureInterFrameTime = false;
  106080. this._interFrameTime = new BABYLON.PerfCounter();
  106081. this._captureParticlesRenderTime = false;
  106082. this._particlesRenderTime = new BABYLON.PerfCounter();
  106083. this._captureSpritesRenderTime = false;
  106084. this._spritesRenderTime = new BABYLON.PerfCounter();
  106085. this._capturePhysicsTime = false;
  106086. this._physicsTime = new BABYLON.PerfCounter();
  106087. this._captureAnimationsTime = false;
  106088. this._animationsTime = new BABYLON.PerfCounter();
  106089. this._captureCameraRenderTime = false;
  106090. this._cameraRenderTime = new BABYLON.PerfCounter();
  106091. // Observers
  106092. this._onBeforeActiveMeshesEvaluationObserver = null;
  106093. this._onAfterActiveMeshesEvaluationObserver = null;
  106094. this._onBeforeRenderTargetsRenderObserver = null;
  106095. this._onAfterRenderTargetsRenderObserver = null;
  106096. this._onAfterRenderObserver = null;
  106097. this._onBeforeDrawPhaseObserver = null;
  106098. this._onAfterDrawPhaseObserver = null;
  106099. this._onBeforeAnimationsObserver = null;
  106100. this._onBeforeParticlesRenderingObserver = null;
  106101. this._onAfterParticlesRenderingObserver = null;
  106102. this._onBeforeSpritesRenderingObserver = null;
  106103. this._onAfterSpritesRenderingObserver = null;
  106104. this._onBeforePhysicsObserver = null;
  106105. this._onAfterPhysicsObserver = null;
  106106. this._onAfterAnimationsObserver = null;
  106107. this._onBeforeCameraRenderObserver = null;
  106108. this._onAfterCameraRenderObserver = null;
  106109. // Before render
  106110. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  106111. if (_this._captureActiveMeshesEvaluationTime) {
  106112. _this._activeMeshesEvaluationTime.fetchNewFrame();
  106113. }
  106114. if (_this._captureRenderTargetsRenderTime) {
  106115. _this._renderTargetsRenderTime.fetchNewFrame();
  106116. }
  106117. if (_this._captureFrameTime) {
  106118. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  106119. _this._frameTime.beginMonitoring();
  106120. }
  106121. if (_this._captureInterFrameTime) {
  106122. _this._interFrameTime.endMonitoring();
  106123. }
  106124. if (_this._captureParticlesRenderTime) {
  106125. _this._particlesRenderTime.fetchNewFrame();
  106126. }
  106127. if (_this._captureSpritesRenderTime) {
  106128. _this._spritesRenderTime.fetchNewFrame();
  106129. }
  106130. if (_this._captureAnimationsTime) {
  106131. _this._animationsTime.beginMonitoring();
  106132. }
  106133. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  106134. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  106135. });
  106136. // After render
  106137. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  106138. if (_this._captureFrameTime) {
  106139. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  106140. _this._frameTime.endMonitoring();
  106141. }
  106142. if (_this._captureRenderTime) {
  106143. _this._renderTime.endMonitoring(false);
  106144. }
  106145. if (_this._captureInterFrameTime) {
  106146. _this._interFrameTime.beginMonitoring();
  106147. }
  106148. });
  106149. }
  106150. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  106151. // Properties
  106152. /**
  106153. * Gets the perf counter used for active meshes evaluation time
  106154. */
  106155. get: function () {
  106156. return this._activeMeshesEvaluationTime;
  106157. },
  106158. enumerable: true,
  106159. configurable: true
  106160. });
  106161. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  106162. /**
  106163. * Gets the active meshes evaluation time capture status
  106164. */
  106165. get: function () {
  106166. return this._captureActiveMeshesEvaluationTime;
  106167. },
  106168. /**
  106169. * Enable or disable the active meshes evaluation time capture
  106170. */
  106171. set: function (value) {
  106172. var _this = this;
  106173. if (value === this._captureActiveMeshesEvaluationTime) {
  106174. return;
  106175. }
  106176. this._captureActiveMeshesEvaluationTime = value;
  106177. if (value) {
  106178. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  106179. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  106180. _this._activeMeshesEvaluationTime.beginMonitoring();
  106181. });
  106182. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  106183. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  106184. _this._activeMeshesEvaluationTime.endMonitoring();
  106185. });
  106186. }
  106187. else {
  106188. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106189. this._onBeforeActiveMeshesEvaluationObserver = null;
  106190. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106191. this._onAfterActiveMeshesEvaluationObserver = null;
  106192. }
  106193. },
  106194. enumerable: true,
  106195. configurable: true
  106196. });
  106197. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  106198. /**
  106199. * Gets the perf counter used for render targets render time
  106200. */
  106201. get: function () {
  106202. return this._renderTargetsRenderTime;
  106203. },
  106204. enumerable: true,
  106205. configurable: true
  106206. });
  106207. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  106208. /**
  106209. * Gets the render targets render time capture status
  106210. */
  106211. get: function () {
  106212. return this._captureRenderTargetsRenderTime;
  106213. },
  106214. /**
  106215. * Enable or disable the render targets render time capture
  106216. */
  106217. set: function (value) {
  106218. var _this = this;
  106219. if (value === this._captureRenderTargetsRenderTime) {
  106220. return;
  106221. }
  106222. this._captureRenderTargetsRenderTime = value;
  106223. if (value) {
  106224. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  106225. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  106226. _this._renderTargetsRenderTime.beginMonitoring();
  106227. });
  106228. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  106229. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  106230. _this._renderTargetsRenderTime.endMonitoring(false);
  106231. });
  106232. }
  106233. else {
  106234. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106235. this._onBeforeRenderTargetsRenderObserver = null;
  106236. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106237. this._onAfterRenderTargetsRenderObserver = null;
  106238. }
  106239. },
  106240. enumerable: true,
  106241. configurable: true
  106242. });
  106243. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  106244. /**
  106245. * Gets the perf counter used for particles render time
  106246. */
  106247. get: function () {
  106248. return this._particlesRenderTime;
  106249. },
  106250. enumerable: true,
  106251. configurable: true
  106252. });
  106253. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  106254. /**
  106255. * Gets the particles render time capture status
  106256. */
  106257. get: function () {
  106258. return this._captureParticlesRenderTime;
  106259. },
  106260. /**
  106261. * Enable or disable the particles render time capture
  106262. */
  106263. set: function (value) {
  106264. var _this = this;
  106265. if (value === this._captureParticlesRenderTime) {
  106266. return;
  106267. }
  106268. this._captureParticlesRenderTime = value;
  106269. if (value) {
  106270. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  106271. BABYLON.Tools.StartPerformanceCounter("Particles");
  106272. _this._particlesRenderTime.beginMonitoring();
  106273. });
  106274. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  106275. BABYLON.Tools.EndPerformanceCounter("Particles");
  106276. _this._particlesRenderTime.endMonitoring(false);
  106277. });
  106278. }
  106279. else {
  106280. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106281. this._onBeforeParticlesRenderingObserver = null;
  106282. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106283. this._onAfterParticlesRenderingObserver = null;
  106284. }
  106285. },
  106286. enumerable: true,
  106287. configurable: true
  106288. });
  106289. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  106290. /**
  106291. * Gets the perf counter used for sprites render time
  106292. */
  106293. get: function () {
  106294. return this._spritesRenderTime;
  106295. },
  106296. enumerable: true,
  106297. configurable: true
  106298. });
  106299. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  106300. /**
  106301. * Gets the sprites render time capture status
  106302. */
  106303. get: function () {
  106304. return this._captureSpritesRenderTime;
  106305. },
  106306. /**
  106307. * Enable or disable the sprites render time capture
  106308. */
  106309. set: function (value) {
  106310. var _this = this;
  106311. if (value === this._captureSpritesRenderTime) {
  106312. return;
  106313. }
  106314. this._captureSpritesRenderTime = value;
  106315. if (!this.scene.spriteManagers) {
  106316. return;
  106317. }
  106318. if (value) {
  106319. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  106320. BABYLON.Tools.StartPerformanceCounter("Sprites");
  106321. _this._spritesRenderTime.beginMonitoring();
  106322. });
  106323. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  106324. BABYLON.Tools.EndPerformanceCounter("Sprites");
  106325. _this._spritesRenderTime.endMonitoring(false);
  106326. });
  106327. }
  106328. else {
  106329. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106330. this._onBeforeSpritesRenderingObserver = null;
  106331. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106332. this._onAfterSpritesRenderingObserver = null;
  106333. }
  106334. },
  106335. enumerable: true,
  106336. configurable: true
  106337. });
  106338. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  106339. /**
  106340. * Gets the perf counter used for physics time
  106341. */
  106342. get: function () {
  106343. return this._physicsTime;
  106344. },
  106345. enumerable: true,
  106346. configurable: true
  106347. });
  106348. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  106349. /**
  106350. * Gets the physics time capture status
  106351. */
  106352. get: function () {
  106353. return this._capturePhysicsTime;
  106354. },
  106355. /**
  106356. * Enable or disable the physics time capture
  106357. */
  106358. set: function (value) {
  106359. var _this = this;
  106360. if (value === this._capturePhysicsTime) {
  106361. return;
  106362. }
  106363. this._capturePhysicsTime = value;
  106364. if (value) {
  106365. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  106366. BABYLON.Tools.StartPerformanceCounter("Physics");
  106367. _this._physicsTime.beginMonitoring();
  106368. });
  106369. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  106370. BABYLON.Tools.EndPerformanceCounter("Physics");
  106371. _this._physicsTime.endMonitoring();
  106372. });
  106373. }
  106374. else {
  106375. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106376. this._onBeforePhysicsObserver = null;
  106377. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106378. this._onAfterPhysicsObserver = null;
  106379. }
  106380. },
  106381. enumerable: true,
  106382. configurable: true
  106383. });
  106384. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  106385. /**
  106386. * Gets the perf counter used for animations time
  106387. */
  106388. get: function () {
  106389. return this._animationsTime;
  106390. },
  106391. enumerable: true,
  106392. configurable: true
  106393. });
  106394. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  106395. /**
  106396. * Gets the animations time capture status
  106397. */
  106398. get: function () {
  106399. return this._captureAnimationsTime;
  106400. },
  106401. /**
  106402. * Enable or disable the animations time capture
  106403. */
  106404. set: function (value) {
  106405. var _this = this;
  106406. if (value === this._captureAnimationsTime) {
  106407. return;
  106408. }
  106409. this._captureAnimationsTime = value;
  106410. if (value) {
  106411. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  106412. _this._animationsTime.endMonitoring();
  106413. });
  106414. }
  106415. else {
  106416. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106417. this._onAfterAnimationsObserver = null;
  106418. }
  106419. },
  106420. enumerable: true,
  106421. configurable: true
  106422. });
  106423. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  106424. /**
  106425. * Gets the perf counter used for frame time capture
  106426. */
  106427. get: function () {
  106428. return this._frameTime;
  106429. },
  106430. enumerable: true,
  106431. configurable: true
  106432. });
  106433. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  106434. /**
  106435. * Gets the frame time capture status
  106436. */
  106437. get: function () {
  106438. return this._captureFrameTime;
  106439. },
  106440. /**
  106441. * Enable or disable the frame time capture
  106442. */
  106443. set: function (value) {
  106444. this._captureFrameTime = value;
  106445. },
  106446. enumerable: true,
  106447. configurable: true
  106448. });
  106449. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  106450. /**
  106451. * Gets the perf counter used for inter-frames time capture
  106452. */
  106453. get: function () {
  106454. return this._interFrameTime;
  106455. },
  106456. enumerable: true,
  106457. configurable: true
  106458. });
  106459. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  106460. /**
  106461. * Gets the inter-frames time capture status
  106462. */
  106463. get: function () {
  106464. return this._captureInterFrameTime;
  106465. },
  106466. /**
  106467. * Enable or disable the inter-frames time capture
  106468. */
  106469. set: function (value) {
  106470. this._captureInterFrameTime = value;
  106471. },
  106472. enumerable: true,
  106473. configurable: true
  106474. });
  106475. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  106476. /**
  106477. * Gets the perf counter used for render time capture
  106478. */
  106479. get: function () {
  106480. return this._renderTime;
  106481. },
  106482. enumerable: true,
  106483. configurable: true
  106484. });
  106485. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  106486. /**
  106487. * Gets the render time capture status
  106488. */
  106489. get: function () {
  106490. return this._captureRenderTime;
  106491. },
  106492. /**
  106493. * Enable or disable the render time capture
  106494. */
  106495. set: function (value) {
  106496. var _this = this;
  106497. if (value === this._captureRenderTime) {
  106498. return;
  106499. }
  106500. this._captureRenderTime = value;
  106501. if (value) {
  106502. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  106503. _this._renderTime.beginMonitoring();
  106504. BABYLON.Tools.StartPerformanceCounter("Main render");
  106505. });
  106506. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  106507. _this._renderTime.endMonitoring(false);
  106508. BABYLON.Tools.EndPerformanceCounter("Main render");
  106509. });
  106510. }
  106511. else {
  106512. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  106513. this._onBeforeDrawPhaseObserver = null;
  106514. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  106515. this._onAfterDrawPhaseObserver = null;
  106516. }
  106517. },
  106518. enumerable: true,
  106519. configurable: true
  106520. });
  106521. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  106522. /**
  106523. * Gets the perf counter used for camera render time capture
  106524. */
  106525. get: function () {
  106526. return this._cameraRenderTime;
  106527. },
  106528. enumerable: true,
  106529. configurable: true
  106530. });
  106531. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  106532. /**
  106533. * Gets the camera render time capture status
  106534. */
  106535. get: function () {
  106536. return this._captureCameraRenderTime;
  106537. },
  106538. /**
  106539. * Enable or disable the camera render time capture
  106540. */
  106541. set: function (value) {
  106542. var _this = this;
  106543. if (value === this._captureCameraRenderTime) {
  106544. return;
  106545. }
  106546. this._captureCameraRenderTime = value;
  106547. if (value) {
  106548. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  106549. _this._cameraRenderTime.beginMonitoring();
  106550. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  106551. });
  106552. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  106553. _this._cameraRenderTime.endMonitoring(false);
  106554. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  106555. });
  106556. }
  106557. else {
  106558. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  106559. this._onBeforeCameraRenderObserver = null;
  106560. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  106561. this._onAfterCameraRenderObserver = null;
  106562. }
  106563. },
  106564. enumerable: true,
  106565. configurable: true
  106566. });
  106567. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  106568. /**
  106569. * Gets the perf counter used for draw calls
  106570. */
  106571. get: function () {
  106572. return this.scene.getEngine()._drawCalls;
  106573. },
  106574. enumerable: true,
  106575. configurable: true
  106576. });
  106577. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  106578. /**
  106579. * Gets the perf counter used for texture collisions
  106580. */
  106581. get: function () {
  106582. return this.scene.getEngine()._textureCollisions;
  106583. },
  106584. enumerable: true,
  106585. configurable: true
  106586. });
  106587. SceneInstrumentation.prototype.dispose = function () {
  106588. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  106589. this._onAfterRenderObserver = null;
  106590. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106591. this._onBeforeActiveMeshesEvaluationObserver = null;
  106592. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106593. this._onAfterActiveMeshesEvaluationObserver = null;
  106594. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106595. this._onBeforeRenderTargetsRenderObserver = null;
  106596. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106597. this._onAfterRenderTargetsRenderObserver = null;
  106598. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  106599. this._onBeforeAnimationsObserver = null;
  106600. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106601. this._onBeforeParticlesRenderingObserver = null;
  106602. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106603. this._onAfterParticlesRenderingObserver = null;
  106604. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106605. this._onBeforeSpritesRenderingObserver = null;
  106606. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106607. this._onAfterSpritesRenderingObserver = null;
  106608. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  106609. this._onBeforeDrawPhaseObserver = null;
  106610. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  106611. this._onAfterDrawPhaseObserver = null;
  106612. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106613. this._onBeforePhysicsObserver = null;
  106614. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106615. this._onAfterPhysicsObserver = null;
  106616. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106617. this._onAfterAnimationsObserver = null;
  106618. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  106619. this._onBeforeCameraRenderObserver = null;
  106620. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  106621. this._onAfterCameraRenderObserver = null;
  106622. this.scene = null;
  106623. };
  106624. return SceneInstrumentation;
  106625. }());
  106626. BABYLON.SceneInstrumentation = SceneInstrumentation;
  106627. })(BABYLON || (BABYLON = {}));
  106628. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  106629. var BABYLON;
  106630. (function (BABYLON) {
  106631. /**
  106632. * @hidden
  106633. **/
  106634. var _TimeToken = /** @class */ (function () {
  106635. function _TimeToken() {
  106636. this._timeElapsedQueryEnded = false;
  106637. }
  106638. return _TimeToken;
  106639. }());
  106640. BABYLON._TimeToken = _TimeToken;
  106641. })(BABYLON || (BABYLON = {}));
  106642. //# sourceMappingURL=babylon.timeToken.js.map
  106643. var BABYLON;
  106644. (function (BABYLON) {
  106645. /**
  106646. * Background material defines definition.
  106647. * @hidden Mainly internal Use
  106648. */
  106649. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  106650. __extends(BackgroundMaterialDefines, _super);
  106651. /**
  106652. * Constructor of the defines.
  106653. */
  106654. function BackgroundMaterialDefines() {
  106655. var _this = _super.call(this) || this;
  106656. /**
  106657. * True if the diffuse texture is in use.
  106658. */
  106659. _this.DIFFUSE = false;
  106660. /**
  106661. * The direct UV channel to use.
  106662. */
  106663. _this.DIFFUSEDIRECTUV = 0;
  106664. /**
  106665. * True if the diffuse texture is in gamma space.
  106666. */
  106667. _this.GAMMADIFFUSE = false;
  106668. /**
  106669. * True if the diffuse texture has opacity in the alpha channel.
  106670. */
  106671. _this.DIFFUSEHASALPHA = false;
  106672. /**
  106673. * True if you want the material to fade to transparent at grazing angle.
  106674. */
  106675. _this.OPACITYFRESNEL = false;
  106676. /**
  106677. * True if an extra blur needs to be added in the reflection.
  106678. */
  106679. _this.REFLECTIONBLUR = false;
  106680. /**
  106681. * True if you want the material to fade to reflection at grazing angle.
  106682. */
  106683. _this.REFLECTIONFRESNEL = false;
  106684. /**
  106685. * True if you want the material to falloff as far as you move away from the scene center.
  106686. */
  106687. _this.REFLECTIONFALLOFF = false;
  106688. /**
  106689. * False if the current Webgl implementation does not support the texture lod extension.
  106690. */
  106691. _this.TEXTURELODSUPPORT = false;
  106692. /**
  106693. * True to ensure the data are premultiplied.
  106694. */
  106695. _this.PREMULTIPLYALPHA = false;
  106696. /**
  106697. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  106698. */
  106699. _this.USERGBCOLOR = false;
  106700. /**
  106701. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  106702. * stays aligned with the desired configuration.
  106703. */
  106704. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  106705. /**
  106706. * True to add noise in order to reduce the banding effect.
  106707. */
  106708. _this.NOISE = false;
  106709. /**
  106710. * is the reflection texture in BGR color scheme?
  106711. * Mainly used to solve a bug in ios10 video tag
  106712. */
  106713. _this.REFLECTIONBGR = false;
  106714. _this.IMAGEPROCESSING = false;
  106715. _this.VIGNETTE = false;
  106716. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  106717. _this.VIGNETTEBLENDMODEOPAQUE = false;
  106718. _this.TONEMAPPING = false;
  106719. _this.TONEMAPPING_ACES = false;
  106720. _this.CONTRAST = false;
  106721. _this.COLORCURVES = false;
  106722. _this.COLORGRADING = false;
  106723. _this.COLORGRADING3D = false;
  106724. _this.SAMPLER3DGREENDEPTH = false;
  106725. _this.SAMPLER3DBGRMAP = false;
  106726. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  106727. _this.EXPOSURE = false;
  106728. // Reflection.
  106729. _this.REFLECTION = false;
  106730. _this.REFLECTIONMAP_3D = false;
  106731. _this.REFLECTIONMAP_SPHERICAL = false;
  106732. _this.REFLECTIONMAP_PLANAR = false;
  106733. _this.REFLECTIONMAP_CUBIC = false;
  106734. _this.REFLECTIONMAP_PROJECTION = false;
  106735. _this.REFLECTIONMAP_SKYBOX = false;
  106736. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  106737. _this.REFLECTIONMAP_EXPLICIT = false;
  106738. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  106739. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  106740. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  106741. _this.INVERTCUBICMAP = false;
  106742. _this.REFLECTIONMAP_OPPOSITEZ = false;
  106743. _this.LODINREFLECTIONALPHA = false;
  106744. _this.GAMMAREFLECTION = false;
  106745. _this.RGBDREFLECTION = false;
  106746. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  106747. // Default BJS.
  106748. _this.MAINUV1 = false;
  106749. _this.MAINUV2 = false;
  106750. _this.UV1 = false;
  106751. _this.UV2 = false;
  106752. _this.CLIPPLANE = false;
  106753. _this.CLIPPLANE2 = false;
  106754. _this.CLIPPLANE3 = false;
  106755. _this.CLIPPLANE4 = false;
  106756. _this.POINTSIZE = false;
  106757. _this.FOG = false;
  106758. _this.NORMAL = false;
  106759. _this.NUM_BONE_INFLUENCERS = 0;
  106760. _this.BonesPerMesh = 0;
  106761. _this.INSTANCES = false;
  106762. _this.SHADOWFLOAT = false;
  106763. _this.rebuild();
  106764. return _this;
  106765. }
  106766. return BackgroundMaterialDefines;
  106767. }(BABYLON.MaterialDefines));
  106768. /**
  106769. * Background material used to create an efficient environement around your scene.
  106770. */
  106771. var BackgroundMaterial = /** @class */ (function (_super) {
  106772. __extends(BackgroundMaterial, _super);
  106773. /**
  106774. * Instantiates a Background Material in the given scene
  106775. * @param name The friendly name of the material
  106776. * @param scene The scene to add the material to
  106777. */
  106778. function BackgroundMaterial(name, scene) {
  106779. var _this = _super.call(this, name, scene) || this;
  106780. /**
  106781. * Key light Color (multiply against the environement texture)
  106782. */
  106783. _this.primaryColor = BABYLON.Color3.White();
  106784. _this._primaryColorShadowLevel = 0;
  106785. _this._primaryColorHighlightLevel = 0;
  106786. /**
  106787. * Reflection Texture used in the material.
  106788. * Should be author in a specific way for the best result (refer to the documentation).
  106789. */
  106790. _this.reflectionTexture = null;
  106791. /**
  106792. * Reflection Texture level of blur.
  106793. *
  106794. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  106795. * texture twice.
  106796. */
  106797. _this.reflectionBlur = 0;
  106798. /**
  106799. * Diffuse Texture used in the material.
  106800. * Should be author in a specific way for the best result (refer to the documentation).
  106801. */
  106802. _this.diffuseTexture = null;
  106803. _this._shadowLights = null;
  106804. /**
  106805. * Specify the list of lights casting shadow on the material.
  106806. * All scene shadow lights will be included if null.
  106807. */
  106808. _this.shadowLights = null;
  106809. /**
  106810. * Helps adjusting the shadow to a softer level if required.
  106811. * 0 means black shadows and 1 means no shadows.
  106812. */
  106813. _this.shadowLevel = 0;
  106814. /**
  106815. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  106816. * It is usually zero but might be interesting to modify according to your setup.
  106817. */
  106818. _this.sceneCenter = BABYLON.Vector3.Zero();
  106819. /**
  106820. * This helps specifying that the material is falling off to the sky box at grazing angle.
  106821. * This helps ensuring a nice transition when the camera goes under the ground.
  106822. */
  106823. _this.opacityFresnel = true;
  106824. /**
  106825. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  106826. * This helps adding a mirror texture on the ground.
  106827. */
  106828. _this.reflectionFresnel = false;
  106829. /**
  106830. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  106831. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  106832. */
  106833. _this.reflectionFalloffDistance = 0.0;
  106834. /**
  106835. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  106836. */
  106837. _this.reflectionAmount = 1.0;
  106838. /**
  106839. * This specifies the weight of the reflection at grazing angle.
  106840. */
  106841. _this.reflectionReflectance0 = 0.05;
  106842. /**
  106843. * This specifies the weight of the reflection at a perpendicular point of view.
  106844. */
  106845. _this.reflectionReflectance90 = 0.5;
  106846. /**
  106847. * Helps to directly use the maps channels instead of their level.
  106848. */
  106849. _this.useRGBColor = true;
  106850. /**
  106851. * This helps reducing the banding effect that could occur on the background.
  106852. */
  106853. _this.enableNoise = false;
  106854. _this._fovMultiplier = 1.0;
  106855. /**
  106856. * Enable the FOV adjustment feature controlled by fovMultiplier.
  106857. */
  106858. _this.useEquirectangularFOV = false;
  106859. _this._maxSimultaneousLights = 4;
  106860. /**
  106861. * Number of Simultaneous lights allowed on the material.
  106862. */
  106863. _this.maxSimultaneousLights = 4;
  106864. /**
  106865. * Keep track of the image processing observer to allow dispose and replace.
  106866. */
  106867. _this._imageProcessingObserver = null;
  106868. /**
  106869. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  106870. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  106871. */
  106872. _this.switchToBGR = false;
  106873. // Temp values kept as cache in the material.
  106874. _this._renderTargets = new BABYLON.SmartArray(16);
  106875. _this._reflectionControls = BABYLON.Vector4.Zero();
  106876. _this._white = BABYLON.Color3.White();
  106877. _this._primaryShadowColor = BABYLON.Color3.Black();
  106878. _this._primaryHighlightColor = BABYLON.Color3.Black();
  106879. // Setup the default processing configuration to the scene.
  106880. _this._attachImageProcessingConfiguration(null);
  106881. _this.getRenderTargetTextures = function () {
  106882. _this._renderTargets.reset();
  106883. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  106884. _this._renderTargets.push(_this._diffuseTexture);
  106885. }
  106886. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  106887. _this._renderTargets.push(_this._reflectionTexture);
  106888. }
  106889. return _this._renderTargets;
  106890. };
  106891. return _this;
  106892. }
  106893. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  106894. /**
  106895. * Experimental Internal Use Only.
  106896. *
  106897. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  106898. * This acts as a helper to set the primary color to a more "human friendly" value.
  106899. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  106900. * output color as close as possible from the chosen value.
  106901. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  106902. * part of lighting setup.)
  106903. */
  106904. get: function () {
  106905. return this.__perceptualColor;
  106906. },
  106907. set: function (value) {
  106908. this.__perceptualColor = value;
  106909. this._computePrimaryColorFromPerceptualColor();
  106910. this._markAllSubMeshesAsLightsDirty();
  106911. },
  106912. enumerable: true,
  106913. configurable: true
  106914. });
  106915. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  106916. /**
  106917. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  106918. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  106919. */
  106920. get: function () {
  106921. return this._primaryColorShadowLevel;
  106922. },
  106923. set: function (value) {
  106924. this._primaryColorShadowLevel = value;
  106925. this._computePrimaryColors();
  106926. this._markAllSubMeshesAsLightsDirty();
  106927. },
  106928. enumerable: true,
  106929. configurable: true
  106930. });
  106931. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  106932. /**
  106933. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  106934. * The primary color is used at the level chosen to define what the white area would look.
  106935. */
  106936. get: function () {
  106937. return this._primaryColorHighlightLevel;
  106938. },
  106939. set: function (value) {
  106940. this._primaryColorHighlightLevel = value;
  106941. this._computePrimaryColors();
  106942. this._markAllSubMeshesAsLightsDirty();
  106943. },
  106944. enumerable: true,
  106945. configurable: true
  106946. });
  106947. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  106948. /**
  106949. * Sets the reflection reflectance fresnel values according to the default standard
  106950. * empirically know to work well :-)
  106951. */
  106952. set: function (value) {
  106953. var reflectionWeight = value;
  106954. if (reflectionWeight < 0.5) {
  106955. reflectionWeight = reflectionWeight * 2.0;
  106956. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  106957. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  106958. }
  106959. else {
  106960. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  106961. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  106962. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  106963. }
  106964. },
  106965. enumerable: true,
  106966. configurable: true
  106967. });
  106968. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  106969. /**
  106970. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106971. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  106972. * Recommended to be keep at 1.0 except for special cases.
  106973. */
  106974. get: function () {
  106975. return this._fovMultiplier;
  106976. },
  106977. set: function (value) {
  106978. if (isNaN(value)) {
  106979. value = 1.0;
  106980. }
  106981. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  106982. },
  106983. enumerable: true,
  106984. configurable: true
  106985. });
  106986. /**
  106987. * Attaches a new image processing configuration to the PBR Material.
  106988. * @param configuration (if null the scene configuration will be use)
  106989. */
  106990. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  106991. var _this = this;
  106992. if (configuration === this._imageProcessingConfiguration) {
  106993. return;
  106994. }
  106995. // Detaches observer.
  106996. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  106997. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  106998. }
  106999. // Pick the scene configuration if needed.
  107000. if (!configuration) {
  107001. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  107002. }
  107003. else {
  107004. this._imageProcessingConfiguration = configuration;
  107005. }
  107006. // Attaches observer.
  107007. if (this._imageProcessingConfiguration) {
  107008. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  107009. _this._computePrimaryColorFromPerceptualColor();
  107010. _this._markAllSubMeshesAsImageProcessingDirty();
  107011. });
  107012. }
  107013. };
  107014. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  107015. /**
  107016. * Gets the image processing configuration used either in this material.
  107017. */
  107018. get: function () {
  107019. return this._imageProcessingConfiguration;
  107020. },
  107021. /**
  107022. * Sets the Default image processing configuration used either in the this material.
  107023. *
  107024. * If sets to null, the scene one is in use.
  107025. */
  107026. set: function (value) {
  107027. this._attachImageProcessingConfiguration(value);
  107028. // Ensure the effect will be rebuilt.
  107029. this._markAllSubMeshesAsTexturesDirty();
  107030. },
  107031. enumerable: true,
  107032. configurable: true
  107033. });
  107034. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  107035. /**
  107036. * Gets wether the color curves effect is enabled.
  107037. */
  107038. get: function () {
  107039. return this.imageProcessingConfiguration.colorCurvesEnabled;
  107040. },
  107041. /**
  107042. * Sets wether the color curves effect is enabled.
  107043. */
  107044. set: function (value) {
  107045. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  107046. },
  107047. enumerable: true,
  107048. configurable: true
  107049. });
  107050. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  107051. /**
  107052. * Gets wether the color grading effect is enabled.
  107053. */
  107054. get: function () {
  107055. return this.imageProcessingConfiguration.colorGradingEnabled;
  107056. },
  107057. /**
  107058. * Gets wether the color grading effect is enabled.
  107059. */
  107060. set: function (value) {
  107061. this.imageProcessingConfiguration.colorGradingEnabled = value;
  107062. },
  107063. enumerable: true,
  107064. configurable: true
  107065. });
  107066. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  107067. /**
  107068. * Gets wether tonemapping is enabled or not.
  107069. */
  107070. get: function () {
  107071. return this._imageProcessingConfiguration.toneMappingEnabled;
  107072. },
  107073. /**
  107074. * Sets wether tonemapping is enabled or not
  107075. */
  107076. set: function (value) {
  107077. this._imageProcessingConfiguration.toneMappingEnabled = value;
  107078. },
  107079. enumerable: true,
  107080. configurable: true
  107081. });
  107082. ;
  107083. ;
  107084. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  107085. /**
  107086. * The camera exposure used on this material.
  107087. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107088. * This corresponds to a photographic exposure.
  107089. */
  107090. get: function () {
  107091. return this._imageProcessingConfiguration.exposure;
  107092. },
  107093. /**
  107094. * The camera exposure used on this material.
  107095. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107096. * This corresponds to a photographic exposure.
  107097. */
  107098. set: function (value) {
  107099. this._imageProcessingConfiguration.exposure = value;
  107100. },
  107101. enumerable: true,
  107102. configurable: true
  107103. });
  107104. ;
  107105. ;
  107106. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  107107. /**
  107108. * Gets The camera contrast used on this material.
  107109. */
  107110. get: function () {
  107111. return this._imageProcessingConfiguration.contrast;
  107112. },
  107113. /**
  107114. * Sets The camera contrast used on this material.
  107115. */
  107116. set: function (value) {
  107117. this._imageProcessingConfiguration.contrast = value;
  107118. },
  107119. enumerable: true,
  107120. configurable: true
  107121. });
  107122. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  107123. /**
  107124. * Gets the Color Grading 2D Lookup Texture.
  107125. */
  107126. get: function () {
  107127. return this._imageProcessingConfiguration.colorGradingTexture;
  107128. },
  107129. /**
  107130. * Sets the Color Grading 2D Lookup Texture.
  107131. */
  107132. set: function (value) {
  107133. this.imageProcessingConfiguration.colorGradingTexture = value;
  107134. },
  107135. enumerable: true,
  107136. configurable: true
  107137. });
  107138. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  107139. /**
  107140. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107141. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107142. * 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;
  107143. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107144. */
  107145. get: function () {
  107146. return this.imageProcessingConfiguration.colorCurves;
  107147. },
  107148. /**
  107149. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107150. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107151. * 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;
  107152. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107153. */
  107154. set: function (value) {
  107155. this.imageProcessingConfiguration.colorCurves = value;
  107156. },
  107157. enumerable: true,
  107158. configurable: true
  107159. });
  107160. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  107161. /**
  107162. * Gets a boolean indicating that current material needs to register RTT
  107163. */
  107164. get: function () {
  107165. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107166. return true;
  107167. }
  107168. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107169. return true;
  107170. }
  107171. return false;
  107172. },
  107173. enumerable: true,
  107174. configurable: true
  107175. });
  107176. /**
  107177. * The entire material has been created in order to prevent overdraw.
  107178. * @returns false
  107179. */
  107180. BackgroundMaterial.prototype.needAlphaTesting = function () {
  107181. return true;
  107182. };
  107183. /**
  107184. * The entire material has been created in order to prevent overdraw.
  107185. * @returns true if blending is enable
  107186. */
  107187. BackgroundMaterial.prototype.needAlphaBlending = function () {
  107188. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  107189. };
  107190. /**
  107191. * Checks wether the material is ready to be rendered for a given mesh.
  107192. * @param mesh The mesh to render
  107193. * @param subMesh The submesh to check against
  107194. * @param useInstances Specify wether or not the material is used with instances
  107195. * @returns true if all the dependencies are ready (Textures, Effects...)
  107196. */
  107197. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  107198. var _this = this;
  107199. if (useInstances === void 0) { useInstances = false; }
  107200. if (subMesh.effect && this.isFrozen) {
  107201. if (this._wasPreviouslyReady) {
  107202. return true;
  107203. }
  107204. }
  107205. if (!subMesh._materialDefines) {
  107206. subMesh._materialDefines = new BackgroundMaterialDefines();
  107207. }
  107208. var scene = this.getScene();
  107209. var defines = subMesh._materialDefines;
  107210. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  107211. if (defines._renderId === scene.getRenderId()) {
  107212. return true;
  107213. }
  107214. }
  107215. var engine = scene.getEngine();
  107216. // Lights
  107217. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  107218. defines._needNormals = true;
  107219. // Textures
  107220. if (defines._areTexturesDirty) {
  107221. defines._needUVs = false;
  107222. if (scene.texturesEnabled) {
  107223. if (scene.getEngine().getCaps().textureLOD) {
  107224. defines.TEXTURELODSUPPORT = true;
  107225. }
  107226. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107227. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  107228. return false;
  107229. }
  107230. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  107231. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  107232. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  107233. defines.OPACITYFRESNEL = this._opacityFresnel;
  107234. }
  107235. else {
  107236. defines.DIFFUSE = false;
  107237. defines.DIFFUSEHASALPHA = false;
  107238. defines.GAMMADIFFUSE = false;
  107239. defines.OPACITYFRESNEL = false;
  107240. }
  107241. var reflectionTexture = this._reflectionTexture;
  107242. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107243. if (!reflectionTexture.isReadyOrNotBlocking()) {
  107244. return false;
  107245. }
  107246. defines.REFLECTION = true;
  107247. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  107248. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  107249. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  107250. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  107251. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  107252. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  107253. defines.REFLECTIONBGR = this.switchToBGR;
  107254. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  107255. defines.INVERTCUBICMAP = true;
  107256. }
  107257. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  107258. switch (reflectionTexture.coordinatesMode) {
  107259. case BABYLON.Texture.EXPLICIT_MODE:
  107260. defines.REFLECTIONMAP_EXPLICIT = true;
  107261. break;
  107262. case BABYLON.Texture.PLANAR_MODE:
  107263. defines.REFLECTIONMAP_PLANAR = true;
  107264. break;
  107265. case BABYLON.Texture.PROJECTION_MODE:
  107266. defines.REFLECTIONMAP_PROJECTION = true;
  107267. break;
  107268. case BABYLON.Texture.SKYBOX_MODE:
  107269. defines.REFLECTIONMAP_SKYBOX = true;
  107270. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  107271. break;
  107272. case BABYLON.Texture.SPHERICAL_MODE:
  107273. defines.REFLECTIONMAP_SPHERICAL = true;
  107274. break;
  107275. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  107276. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  107277. break;
  107278. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  107279. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  107280. break;
  107281. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  107282. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  107283. break;
  107284. case BABYLON.Texture.CUBIC_MODE:
  107285. case BABYLON.Texture.INVCUBIC_MODE:
  107286. default:
  107287. defines.REFLECTIONMAP_CUBIC = true;
  107288. break;
  107289. }
  107290. if (this.reflectionFresnel) {
  107291. defines.REFLECTIONFRESNEL = true;
  107292. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  107293. this._reflectionControls.x = this.reflectionAmount;
  107294. this._reflectionControls.y = this.reflectionReflectance0;
  107295. this._reflectionControls.z = this.reflectionReflectance90;
  107296. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  107297. }
  107298. else {
  107299. defines.REFLECTIONFRESNEL = false;
  107300. defines.REFLECTIONFALLOFF = false;
  107301. }
  107302. }
  107303. else {
  107304. defines.REFLECTION = false;
  107305. defines.REFLECTIONFRESNEL = false;
  107306. defines.REFLECTIONFALLOFF = false;
  107307. defines.REFLECTIONBLUR = false;
  107308. defines.REFLECTIONMAP_3D = false;
  107309. defines.REFLECTIONMAP_SPHERICAL = false;
  107310. defines.REFLECTIONMAP_PLANAR = false;
  107311. defines.REFLECTIONMAP_CUBIC = false;
  107312. defines.REFLECTIONMAP_PROJECTION = false;
  107313. defines.REFLECTIONMAP_SKYBOX = false;
  107314. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107315. defines.REFLECTIONMAP_EXPLICIT = false;
  107316. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107317. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107318. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107319. defines.INVERTCUBICMAP = false;
  107320. defines.REFLECTIONMAP_OPPOSITEZ = false;
  107321. defines.LODINREFLECTIONALPHA = false;
  107322. defines.GAMMAREFLECTION = false;
  107323. defines.RGBDREFLECTION = false;
  107324. }
  107325. }
  107326. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  107327. defines.USERGBCOLOR = this._useRGBColor;
  107328. defines.NOISE = this._enableNoise;
  107329. }
  107330. if (defines._areLightsDirty) {
  107331. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  107332. }
  107333. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  107334. if (!this._imageProcessingConfiguration.isReady()) {
  107335. return false;
  107336. }
  107337. this._imageProcessingConfiguration.prepareDefines(defines);
  107338. }
  107339. // Misc.
  107340. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  107341. // Values that need to be evaluated on every frame
  107342. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  107343. // Attribs
  107344. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  107345. if (mesh) {
  107346. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  107347. mesh.createNormals(true);
  107348. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  107349. }
  107350. }
  107351. }
  107352. // Get correct effect
  107353. if (defines.isDirty) {
  107354. defines.markAsProcessed();
  107355. scene.resetCachedMaterial();
  107356. // Fallbacks
  107357. var fallbacks = new BABYLON.EffectFallbacks();
  107358. if (defines.FOG) {
  107359. fallbacks.addFallback(0, "FOG");
  107360. }
  107361. if (defines.POINTSIZE) {
  107362. fallbacks.addFallback(1, "POINTSIZE");
  107363. }
  107364. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  107365. if (defines.NUM_BONE_INFLUENCERS > 0) {
  107366. fallbacks.addCPUSkinningFallback(0, mesh);
  107367. }
  107368. //Attributes
  107369. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107370. if (defines.NORMAL) {
  107371. attribs.push(BABYLON.VertexBuffer.NormalKind);
  107372. }
  107373. if (defines.UV1) {
  107374. attribs.push(BABYLON.VertexBuffer.UVKind);
  107375. }
  107376. if (defines.UV2) {
  107377. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107378. }
  107379. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  107380. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  107381. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  107382. "vFogInfos", "vFogColor", "pointSize",
  107383. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  107384. "vPrimaryColor", "vPrimaryColorShadow",
  107385. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  107386. "shadowLevel", "alpha",
  107387. "vBackgroundCenter", "vReflectionControl",
  107388. "vDiffuseInfos", "diffuseMatrix",
  107389. ];
  107390. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  107391. var uniformBuffers = ["Material", "Scene"];
  107392. if (BABYLON.ImageProcessingConfiguration) {
  107393. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  107394. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  107395. }
  107396. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  107397. uniformsNames: uniforms,
  107398. uniformBuffersNames: uniformBuffers,
  107399. samplers: samplers,
  107400. defines: defines,
  107401. maxSimultaneousLights: this._maxSimultaneousLights
  107402. });
  107403. var onCompiled = function (effect) {
  107404. if (_this.onCompiled) {
  107405. _this.onCompiled(effect);
  107406. }
  107407. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  107408. };
  107409. var join = defines.toString();
  107410. subMesh.setEffect(scene.getEngine().createEffect("background", {
  107411. attributes: attribs,
  107412. uniformsNames: uniforms,
  107413. uniformBuffersNames: uniformBuffers,
  107414. samplers: samplers,
  107415. defines: join,
  107416. fallbacks: fallbacks,
  107417. onCompiled: onCompiled,
  107418. onError: this.onError,
  107419. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  107420. }, engine), defines);
  107421. this.buildUniformLayout();
  107422. }
  107423. if (!subMesh.effect || !subMesh.effect.isReady()) {
  107424. return false;
  107425. }
  107426. defines._renderId = scene.getRenderId();
  107427. this._wasPreviouslyReady = true;
  107428. return true;
  107429. };
  107430. /**
  107431. * Compute the primary color according to the chosen perceptual color.
  107432. */
  107433. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  107434. if (!this.__perceptualColor) {
  107435. return;
  107436. }
  107437. this._primaryColor.copyFrom(this.__perceptualColor);
  107438. // Revert gamma space.
  107439. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  107440. // Revert image processing configuration.
  107441. if (this._imageProcessingConfiguration) {
  107442. // Revert Exposure.
  107443. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  107444. }
  107445. this._computePrimaryColors();
  107446. };
  107447. /**
  107448. * Compute the highlights and shadow colors according to their chosen levels.
  107449. */
  107450. BackgroundMaterial.prototype._computePrimaryColors = function () {
  107451. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  107452. return;
  107453. }
  107454. // Find the highlight color based on the configuration.
  107455. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  107456. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  107457. // Find the shadow color based on the configuration.
  107458. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  107459. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  107460. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  107461. };
  107462. /**
  107463. * Build the uniform buffer used in the material.
  107464. */
  107465. BackgroundMaterial.prototype.buildUniformLayout = function () {
  107466. // Order is important !
  107467. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  107468. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  107469. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  107470. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  107471. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  107472. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  107473. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  107474. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  107475. this._uniformBuffer.addUniform("pointSize", 1);
  107476. this._uniformBuffer.addUniform("shadowLevel", 1);
  107477. this._uniformBuffer.addUniform("alpha", 1);
  107478. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  107479. this._uniformBuffer.addUniform("vReflectionControl", 4);
  107480. this._uniformBuffer.create();
  107481. };
  107482. /**
  107483. * Unbind the material.
  107484. */
  107485. BackgroundMaterial.prototype.unbind = function () {
  107486. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107487. this._uniformBuffer.setTexture("diffuseSampler", null);
  107488. }
  107489. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107490. this._uniformBuffer.setTexture("reflectionSampler", null);
  107491. }
  107492. _super.prototype.unbind.call(this);
  107493. };
  107494. /**
  107495. * Bind only the world matrix to the material.
  107496. * @param world The world matrix to bind.
  107497. */
  107498. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  107499. this._activeEffect.setMatrix("world", world);
  107500. };
  107501. /**
  107502. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  107503. * @param world The world matrix to bind.
  107504. * @param subMesh The submesh to bind for.
  107505. */
  107506. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  107507. var scene = this.getScene();
  107508. var defines = subMesh._materialDefines;
  107509. if (!defines) {
  107510. return;
  107511. }
  107512. var effect = subMesh.effect;
  107513. if (!effect) {
  107514. return;
  107515. }
  107516. this._activeEffect = effect;
  107517. // Matrices
  107518. this.bindOnlyWorldMatrix(world);
  107519. // Bones
  107520. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  107521. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  107522. if (mustRebind) {
  107523. this._uniformBuffer.bindToEffect(effect, "Material");
  107524. this.bindViewProjection(effect);
  107525. var reflectionTexture = this._reflectionTexture;
  107526. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  107527. // Texture uniforms
  107528. if (scene.texturesEnabled) {
  107529. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107530. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  107531. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  107532. }
  107533. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107534. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  107535. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  107536. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  107537. }
  107538. }
  107539. if (this.shadowLevel > 0) {
  107540. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  107541. }
  107542. this._uniformBuffer.updateFloat("alpha", this.alpha);
  107543. // Point size
  107544. if (this.pointsCloud) {
  107545. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  107546. }
  107547. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  107548. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  107549. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  107550. }
  107551. else {
  107552. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  107553. }
  107554. }
  107555. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  107556. // Textures
  107557. if (scene.texturesEnabled) {
  107558. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107559. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  107560. }
  107561. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107562. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  107563. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  107564. }
  107565. else if (!defines.REFLECTIONBLUR) {
  107566. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  107567. }
  107568. else {
  107569. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  107570. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  107571. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  107572. }
  107573. if (defines.REFLECTIONFRESNEL) {
  107574. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  107575. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  107576. }
  107577. }
  107578. }
  107579. // Clip plane
  107580. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  107581. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  107582. }
  107583. if (mustRebind || !this.isFrozen) {
  107584. if (scene.lightsEnabled) {
  107585. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  107586. }
  107587. // View
  107588. this.bindView(effect);
  107589. // Fog
  107590. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  107591. // image processing
  107592. if (this._imageProcessingConfiguration) {
  107593. this._imageProcessingConfiguration.bind(this._activeEffect);
  107594. }
  107595. }
  107596. this._uniformBuffer.update();
  107597. this._afterBind(mesh, this._activeEffect);
  107598. };
  107599. /**
  107600. * Dispose the material.
  107601. * @param forceDisposeEffect Force disposal of the associated effect.
  107602. * @param forceDisposeTextures Force disposal of the associated textures.
  107603. */
  107604. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  107605. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  107606. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  107607. if (forceDisposeTextures) {
  107608. if (this.diffuseTexture) {
  107609. this.diffuseTexture.dispose();
  107610. }
  107611. if (this.reflectionTexture) {
  107612. this.reflectionTexture.dispose();
  107613. }
  107614. }
  107615. this._renderTargets.dispose();
  107616. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107617. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107618. }
  107619. _super.prototype.dispose.call(this, forceDisposeEffect);
  107620. };
  107621. /**
  107622. * Clones the material.
  107623. * @param name The cloned name.
  107624. * @returns The cloned material.
  107625. */
  107626. BackgroundMaterial.prototype.clone = function (name) {
  107627. var _this = this;
  107628. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  107629. };
  107630. /**
  107631. * Serializes the current material to its JSON representation.
  107632. * @returns The JSON representation.
  107633. */
  107634. BackgroundMaterial.prototype.serialize = function () {
  107635. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107636. serializationObject.customType = "BABYLON.BackgroundMaterial";
  107637. return serializationObject;
  107638. };
  107639. /**
  107640. * Gets the class name of the material
  107641. * @returns "BackgroundMaterial"
  107642. */
  107643. BackgroundMaterial.prototype.getClassName = function () {
  107644. return "BackgroundMaterial";
  107645. };
  107646. /**
  107647. * Parse a JSON input to create back a background material.
  107648. * @param source The JSON data to parse
  107649. * @param scene The scene to create the parsed material in
  107650. * @param rootUrl The root url of the assets the material depends upon
  107651. * @returns the instantiated BackgroundMaterial.
  107652. */
  107653. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  107654. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  107655. };
  107656. /**
  107657. * Standard reflectance value at parallel view angle.
  107658. */
  107659. BackgroundMaterial.StandardReflectance0 = 0.05;
  107660. /**
  107661. * Standard reflectance value at grazing angle.
  107662. */
  107663. BackgroundMaterial.StandardReflectance90 = 0.5;
  107664. __decorate([
  107665. BABYLON.serializeAsColor3()
  107666. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  107667. __decorate([
  107668. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  107669. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  107670. __decorate([
  107671. BABYLON.serializeAsColor3()
  107672. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  107673. __decorate([
  107674. BABYLON.serialize()
  107675. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  107676. __decorate([
  107677. BABYLON.serialize()
  107678. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  107679. __decorate([
  107680. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  107681. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  107682. __decorate([
  107683. BABYLON.serializeAsTexture()
  107684. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  107685. __decorate([
  107686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107687. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  107688. __decorate([
  107689. BABYLON.serialize()
  107690. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  107691. __decorate([
  107692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107693. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  107694. __decorate([
  107695. BABYLON.serializeAsTexture()
  107696. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  107697. __decorate([
  107698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107699. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  107700. __decorate([
  107701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107702. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  107703. __decorate([
  107704. BABYLON.serialize()
  107705. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  107706. __decorate([
  107707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107708. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  107709. __decorate([
  107710. BABYLON.serializeAsVector3()
  107711. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  107712. __decorate([
  107713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107714. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  107715. __decorate([
  107716. BABYLON.serialize()
  107717. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  107718. __decorate([
  107719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107720. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  107721. __decorate([
  107722. BABYLON.serialize()
  107723. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  107724. __decorate([
  107725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107726. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  107727. __decorate([
  107728. BABYLON.serialize()
  107729. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  107730. __decorate([
  107731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107732. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  107733. __decorate([
  107734. BABYLON.serialize()
  107735. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  107736. __decorate([
  107737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107738. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  107739. __decorate([
  107740. BABYLON.serialize()
  107741. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  107742. __decorate([
  107743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107744. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  107745. __decorate([
  107746. BABYLON.serialize()
  107747. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  107748. __decorate([
  107749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107750. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  107751. __decorate([
  107752. BABYLON.serialize()
  107753. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  107754. __decorate([
  107755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107756. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  107757. __decorate([
  107758. BABYLON.serialize()
  107759. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  107760. __decorate([
  107761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107762. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  107763. __decorate([
  107764. BABYLON.serialize()
  107765. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  107766. __decorate([
  107767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107768. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  107769. __decorate([
  107770. BABYLON.serializeAsImageProcessingConfiguration()
  107771. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  107772. return BackgroundMaterial;
  107773. }(BABYLON.PushMaterial));
  107774. BABYLON.BackgroundMaterial = BackgroundMaterial;
  107775. })(BABYLON || (BABYLON = {}));
  107776. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  107777. var __assign = (this && this.__assign) || function () {
  107778. __assign = Object.assign || function(t) {
  107779. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107780. s = arguments[i];
  107781. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107782. t[p] = s[p];
  107783. }
  107784. return t;
  107785. };
  107786. return __assign.apply(this, arguments);
  107787. };
  107788. var BABYLON;
  107789. (function (BABYLON) {
  107790. /**
  107791. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  107792. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  107793. * It also helps with the default setup of your imageProcessing configuration.
  107794. */
  107795. var EnvironmentHelper = /** @class */ (function () {
  107796. /**
  107797. * constructor
  107798. * @param options
  107799. * @param scene The scene to add the material to
  107800. */
  107801. function EnvironmentHelper(options, scene) {
  107802. var _this = this;
  107803. this._errorHandler = function (message, exception) {
  107804. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  107805. };
  107806. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  107807. this._scene = scene;
  107808. this.onErrorObservable = new BABYLON.Observable();
  107809. this._setupBackground();
  107810. this._setupImageProcessing();
  107811. }
  107812. /**
  107813. * Creates the default options for the helper.
  107814. */
  107815. EnvironmentHelper._getDefaultOptions = function () {
  107816. return {
  107817. createGround: true,
  107818. groundSize: 15,
  107819. groundTexture: this._groundTextureCDNUrl,
  107820. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107821. groundOpacity: 0.9,
  107822. enableGroundShadow: true,
  107823. groundShadowLevel: 0.5,
  107824. enableGroundMirror: false,
  107825. groundMirrorSizeRatio: 0.3,
  107826. groundMirrorBlurKernel: 64,
  107827. groundMirrorAmount: 1,
  107828. groundMirrorFresnelWeight: 1,
  107829. groundMirrorFallOffDistance: 0,
  107830. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  107831. groundYBias: 0.00001,
  107832. createSkybox: true,
  107833. skyboxSize: 20,
  107834. skyboxTexture: this._skyboxTextureCDNUrl,
  107835. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107836. backgroundYRotation: 0,
  107837. sizeAuto: true,
  107838. rootPosition: BABYLON.Vector3.Zero(),
  107839. setupImageProcessing: true,
  107840. environmentTexture: this._environmentTextureCDNUrl,
  107841. cameraExposure: 0.8,
  107842. cameraContrast: 1.2,
  107843. toneMappingEnabled: true,
  107844. };
  107845. };
  107846. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  107847. /**
  107848. * Gets the root mesh created by the helper.
  107849. */
  107850. get: function () {
  107851. return this._rootMesh;
  107852. },
  107853. enumerable: true,
  107854. configurable: true
  107855. });
  107856. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  107857. /**
  107858. * Gets the skybox created by the helper.
  107859. */
  107860. get: function () {
  107861. return this._skybox;
  107862. },
  107863. enumerable: true,
  107864. configurable: true
  107865. });
  107866. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  107867. /**
  107868. * Gets the skybox texture created by the helper.
  107869. */
  107870. get: function () {
  107871. return this._skyboxTexture;
  107872. },
  107873. enumerable: true,
  107874. configurable: true
  107875. });
  107876. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  107877. /**
  107878. * Gets the skybox material created by the helper.
  107879. */
  107880. get: function () {
  107881. return this._skyboxMaterial;
  107882. },
  107883. enumerable: true,
  107884. configurable: true
  107885. });
  107886. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  107887. /**
  107888. * Gets the ground mesh created by the helper.
  107889. */
  107890. get: function () {
  107891. return this._ground;
  107892. },
  107893. enumerable: true,
  107894. configurable: true
  107895. });
  107896. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  107897. /**
  107898. * Gets the ground texture created by the helper.
  107899. */
  107900. get: function () {
  107901. return this._groundTexture;
  107902. },
  107903. enumerable: true,
  107904. configurable: true
  107905. });
  107906. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  107907. /**
  107908. * Gets the ground mirror created by the helper.
  107909. */
  107910. get: function () {
  107911. return this._groundMirror;
  107912. },
  107913. enumerable: true,
  107914. configurable: true
  107915. });
  107916. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  107917. /**
  107918. * Gets the ground mirror render list to helps pushing the meshes
  107919. * you wish in the ground reflection.
  107920. */
  107921. get: function () {
  107922. if (this._groundMirror) {
  107923. return this._groundMirror.renderList;
  107924. }
  107925. return null;
  107926. },
  107927. enumerable: true,
  107928. configurable: true
  107929. });
  107930. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  107931. /**
  107932. * Gets the ground material created by the helper.
  107933. */
  107934. get: function () {
  107935. return this._groundMaterial;
  107936. },
  107937. enumerable: true,
  107938. configurable: true
  107939. });
  107940. /**
  107941. * Updates the background according to the new options
  107942. * @param options
  107943. */
  107944. EnvironmentHelper.prototype.updateOptions = function (options) {
  107945. var newOptions = __assign({}, this._options, options);
  107946. if (this._ground && !newOptions.createGround) {
  107947. this._ground.dispose();
  107948. this._ground = null;
  107949. }
  107950. if (this._groundMaterial && !newOptions.createGround) {
  107951. this._groundMaterial.dispose();
  107952. this._groundMaterial = null;
  107953. }
  107954. if (this._groundTexture) {
  107955. if (this._options.groundTexture != newOptions.groundTexture) {
  107956. this._groundTexture.dispose();
  107957. this._groundTexture = null;
  107958. }
  107959. }
  107960. if (this._skybox && !newOptions.createSkybox) {
  107961. this._skybox.dispose();
  107962. this._skybox = null;
  107963. }
  107964. if (this._skyboxMaterial && !newOptions.createSkybox) {
  107965. this._skyboxMaterial.dispose();
  107966. this._skyboxMaterial = null;
  107967. }
  107968. if (this._skyboxTexture) {
  107969. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  107970. this._skyboxTexture.dispose();
  107971. this._skyboxTexture = null;
  107972. }
  107973. }
  107974. if (this._groundMirror && !newOptions.enableGroundMirror) {
  107975. this._groundMirror.dispose();
  107976. this._groundMirror = null;
  107977. }
  107978. if (this._scene.environmentTexture) {
  107979. if (this._options.environmentTexture != newOptions.environmentTexture) {
  107980. this._scene.environmentTexture.dispose();
  107981. }
  107982. }
  107983. this._options = newOptions;
  107984. this._setupBackground();
  107985. this._setupImageProcessing();
  107986. };
  107987. /**
  107988. * Sets the primary color of all the available elements.
  107989. * @param color the main color to affect to the ground and the background
  107990. */
  107991. EnvironmentHelper.prototype.setMainColor = function (color) {
  107992. if (this.groundMaterial) {
  107993. this.groundMaterial.primaryColor = color;
  107994. }
  107995. if (this.skyboxMaterial) {
  107996. this.skyboxMaterial.primaryColor = color;
  107997. }
  107998. if (this.groundMirror) {
  107999. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  108000. }
  108001. };
  108002. /**
  108003. * Setup the image processing according to the specified options.
  108004. */
  108005. EnvironmentHelper.prototype._setupImageProcessing = function () {
  108006. if (this._options.setupImageProcessing) {
  108007. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  108008. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  108009. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  108010. this._setupEnvironmentTexture();
  108011. }
  108012. };
  108013. /**
  108014. * Setup the environment texture according to the specified options.
  108015. */
  108016. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  108017. if (this._scene.environmentTexture) {
  108018. return;
  108019. }
  108020. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  108021. this._scene.environmentTexture = this._options.environmentTexture;
  108022. return;
  108023. }
  108024. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  108025. this._scene.environmentTexture = environmentTexture;
  108026. };
  108027. /**
  108028. * Setup the background according to the specified options.
  108029. */
  108030. EnvironmentHelper.prototype._setupBackground = function () {
  108031. if (!this._rootMesh) {
  108032. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  108033. }
  108034. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  108035. var sceneSize = this._getSceneSize();
  108036. if (this._options.createGround) {
  108037. this._setupGround(sceneSize);
  108038. this._setupGroundMaterial();
  108039. this._setupGroundDiffuseTexture();
  108040. if (this._options.enableGroundMirror) {
  108041. this._setupGroundMirrorTexture(sceneSize);
  108042. }
  108043. this._setupMirrorInGroundMaterial();
  108044. }
  108045. if (this._options.createSkybox) {
  108046. this._setupSkybox(sceneSize);
  108047. this._setupSkyboxMaterial();
  108048. this._setupSkyboxReflectionTexture();
  108049. }
  108050. this._rootMesh.position.x = sceneSize.rootPosition.x;
  108051. this._rootMesh.position.z = sceneSize.rootPosition.z;
  108052. this._rootMesh.position.y = sceneSize.rootPosition.y;
  108053. };
  108054. /**
  108055. * Get the scene sizes according to the setup.
  108056. */
  108057. EnvironmentHelper.prototype._getSceneSize = function () {
  108058. var _this = this;
  108059. var groundSize = this._options.groundSize;
  108060. var skyboxSize = this._options.skyboxSize;
  108061. var rootPosition = this._options.rootPosition;
  108062. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  108063. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108064. }
  108065. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  108066. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  108067. });
  108068. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108069. if (this._options.sizeAuto) {
  108070. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  108071. this._scene.activeCamera.upperRadiusLimit) {
  108072. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  108073. skyboxSize = groundSize;
  108074. }
  108075. var sceneDiagonalLenght = sceneDiagonal.length();
  108076. if (sceneDiagonalLenght > groundSize) {
  108077. groundSize = sceneDiagonalLenght * 2;
  108078. skyboxSize = groundSize;
  108079. }
  108080. // 10 % bigger.
  108081. groundSize *= 1.1;
  108082. skyboxSize *= 1.5;
  108083. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  108084. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  108085. }
  108086. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108087. };
  108088. /**
  108089. * Setup the ground according to the specified options.
  108090. */
  108091. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  108092. var _this = this;
  108093. if (!this._ground || this._ground.isDisposed()) {
  108094. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  108095. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  108096. this._ground.parent = this._rootMesh;
  108097. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  108098. }
  108099. this._ground.receiveShadows = this._options.enableGroundShadow;
  108100. };
  108101. /**
  108102. * Setup the ground material according to the specified options.
  108103. */
  108104. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  108105. if (!this._groundMaterial) {
  108106. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  108107. }
  108108. this._groundMaterial.alpha = this._options.groundOpacity;
  108109. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108110. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  108111. this._groundMaterial.primaryColor = this._options.groundColor;
  108112. this._groundMaterial.useRGBColor = false;
  108113. this._groundMaterial.enableNoise = true;
  108114. if (this._ground) {
  108115. this._ground.material = this._groundMaterial;
  108116. }
  108117. };
  108118. /**
  108119. * Setup the ground diffuse texture according to the specified options.
  108120. */
  108121. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  108122. if (!this._groundMaterial) {
  108123. return;
  108124. }
  108125. if (this._groundTexture) {
  108126. return;
  108127. }
  108128. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  108129. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  108130. return;
  108131. }
  108132. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108133. diffuseTexture.gammaSpace = false;
  108134. diffuseTexture.hasAlpha = true;
  108135. this._groundMaterial.diffuseTexture = diffuseTexture;
  108136. };
  108137. /**
  108138. * Setup the ground mirror texture according to the specified options.
  108139. */
  108140. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  108141. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108142. if (!this._groundMirror) {
  108143. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  108144. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  108145. this._groundMirror.anisotropicFilteringLevel = 1;
  108146. this._groundMirror.wrapU = wrapping;
  108147. this._groundMirror.wrapV = wrapping;
  108148. this._groundMirror.gammaSpace = false;
  108149. if (this._groundMirror.renderList) {
  108150. for (var i = 0; i < this._scene.meshes.length; i++) {
  108151. var mesh = this._scene.meshes[i];
  108152. if (mesh !== this._ground &&
  108153. mesh !== this._skybox &&
  108154. mesh !== this._rootMesh) {
  108155. this._groundMirror.renderList.push(mesh);
  108156. }
  108157. }
  108158. }
  108159. }
  108160. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  108161. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  108162. };
  108163. /**
  108164. * Setup the ground to receive the mirror texture.
  108165. */
  108166. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  108167. if (this._groundMaterial) {
  108168. this._groundMaterial.reflectionTexture = this._groundMirror;
  108169. this._groundMaterial.reflectionFresnel = true;
  108170. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  108171. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  108172. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  108173. }
  108174. };
  108175. /**
  108176. * Setup the skybox according to the specified options.
  108177. */
  108178. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  108179. var _this = this;
  108180. if (!this._skybox || this._skybox.isDisposed()) {
  108181. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  108182. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  108183. }
  108184. this._skybox.parent = this._rootMesh;
  108185. };
  108186. /**
  108187. * Setup the skybox material according to the specified options.
  108188. */
  108189. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  108190. if (!this._skybox) {
  108191. return;
  108192. }
  108193. if (!this._skyboxMaterial) {
  108194. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  108195. }
  108196. this._skyboxMaterial.useRGBColor = false;
  108197. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  108198. this._skyboxMaterial.enableNoise = true;
  108199. this._skybox.material = this._skyboxMaterial;
  108200. };
  108201. /**
  108202. * Setup the skybox reflection texture according to the specified options.
  108203. */
  108204. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  108205. if (!this._skyboxMaterial) {
  108206. return;
  108207. }
  108208. if (this._skyboxTexture) {
  108209. return;
  108210. }
  108211. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  108212. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  108213. return;
  108214. }
  108215. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108216. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  108217. this._skyboxTexture.gammaSpace = false;
  108218. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  108219. };
  108220. /**
  108221. * Dispose all the elements created by the Helper.
  108222. */
  108223. EnvironmentHelper.prototype.dispose = function () {
  108224. if (this._groundMaterial) {
  108225. this._groundMaterial.dispose(true, true);
  108226. }
  108227. if (this._skyboxMaterial) {
  108228. this._skyboxMaterial.dispose(true, true);
  108229. }
  108230. this._rootMesh.dispose(false);
  108231. };
  108232. /**
  108233. * Default ground texture URL.
  108234. */
  108235. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  108236. /**
  108237. * Default skybox texture URL.
  108238. */
  108239. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  108240. /**
  108241. * Default environment texture URL.
  108242. */
  108243. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  108244. return EnvironmentHelper;
  108245. }());
  108246. BABYLON.EnvironmentHelper = EnvironmentHelper;
  108247. })(BABYLON || (BABYLON = {}));
  108248. //# sourceMappingURL=babylon.environmentHelper.js.map
  108249. var BABYLON;
  108250. (function (BABYLON) {
  108251. /** Internal class used to store shapes for emitters */
  108252. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  108253. function ParticleSystemSetEmitterCreationOptions() {
  108254. }
  108255. return ParticleSystemSetEmitterCreationOptions;
  108256. }());
  108257. /**
  108258. * Represents a set of particle systems working together to create a specific effect
  108259. */
  108260. var ParticleSystemSet = /** @class */ (function () {
  108261. function ParticleSystemSet() {
  108262. /**
  108263. * Gets the particle system list
  108264. */
  108265. this.systems = new Array();
  108266. }
  108267. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  108268. /**
  108269. * Gets the emitter node used with this set
  108270. */
  108271. get: function () {
  108272. return this._emitterNode;
  108273. },
  108274. enumerable: true,
  108275. configurable: true
  108276. });
  108277. /**
  108278. * Creates a new emitter mesh as a sphere
  108279. * @param options defines the options used to create the sphere
  108280. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  108281. * @param scene defines the hosting scene
  108282. */
  108283. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  108284. if (this._emitterNode) {
  108285. this._emitterNode.dispose();
  108286. }
  108287. this._emitterCreationOptions = {
  108288. kind: "Sphere",
  108289. options: options,
  108290. renderingGroupId: renderingGroupId
  108291. };
  108292. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  108293. emitterMesh.renderingGroupId = renderingGroupId;
  108294. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  108295. material.emissiveColor = options.color;
  108296. emitterMesh.material = material;
  108297. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108298. var system = _a[_i];
  108299. system.emitter = emitterMesh;
  108300. }
  108301. this._emitterNode = emitterMesh;
  108302. };
  108303. /**
  108304. * Starts all particle systems of the set
  108305. * @param emitter defines an optional mesh to use as emitter for the particle systems
  108306. */
  108307. ParticleSystemSet.prototype.start = function (emitter) {
  108308. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108309. var system = _a[_i];
  108310. if (emitter) {
  108311. system.emitter = emitter;
  108312. }
  108313. system.start();
  108314. }
  108315. };
  108316. /**
  108317. * Release all associated resources
  108318. */
  108319. ParticleSystemSet.prototype.dispose = function () {
  108320. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108321. var system = _a[_i];
  108322. system.dispose();
  108323. }
  108324. this.systems = [];
  108325. if (this._emitterNode) {
  108326. this._emitterNode.dispose();
  108327. this._emitterNode = null;
  108328. }
  108329. };
  108330. /**
  108331. * Serialize the set into a JSON compatible object
  108332. * @returns a JSON compatible representation of the set
  108333. */
  108334. ParticleSystemSet.prototype.serialize = function () {
  108335. var result = {};
  108336. result.systems = [];
  108337. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108338. var system = _a[_i];
  108339. result.systems.push(system.serialize());
  108340. }
  108341. if (this._emitterNode) {
  108342. result.emitter = this._emitterCreationOptions;
  108343. }
  108344. return result;
  108345. };
  108346. /**
  108347. * Parse a new ParticleSystemSet from a serialized source
  108348. * @param data defines a JSON compatible representation of the set
  108349. * @param scene defines the hosting scene
  108350. * @param gpu defines if we want GPU particles or CPU particles
  108351. * @returns a new ParticleSystemSet
  108352. */
  108353. ParticleSystemSet.Parse = function (data, scene, gpu) {
  108354. if (gpu === void 0) { gpu = false; }
  108355. var result = new ParticleSystemSet();
  108356. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  108357. scene = scene || BABYLON.Engine.LastCreatedScene;
  108358. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  108359. var system = _a[_i];
  108360. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  108361. }
  108362. if (data.emitter) {
  108363. var options = data.emitter.options;
  108364. switch (data.emitter.kind) {
  108365. case "Sphere":
  108366. result.setEmitterAsSphere({
  108367. diameter: options.diameter,
  108368. segments: options.segments,
  108369. color: BABYLON.Color3.FromArray(options.color)
  108370. }, data.emitter.renderingGroupId, scene);
  108371. break;
  108372. }
  108373. }
  108374. return result;
  108375. };
  108376. return ParticleSystemSet;
  108377. }());
  108378. BABYLON.ParticleSystemSet = ParticleSystemSet;
  108379. })(BABYLON || (BABYLON = {}));
  108380. //# sourceMappingURL=babylon.particleSystemSet.js.map
  108381. var BABYLON;
  108382. (function (BABYLON) {
  108383. /**
  108384. * This class is made for on one-liner static method to help creating particle system set.
  108385. */
  108386. var ParticleHelper = /** @class */ (function () {
  108387. function ParticleHelper() {
  108388. }
  108389. /**
  108390. * Create a default particle system that you can tweak
  108391. * @param emitter defines the emitter to use
  108392. * @param capacity defines the system capacity (default is 500 particles)
  108393. * @param scene defines the hosting scene
  108394. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  108395. * @returns the new Particle system
  108396. */
  108397. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  108398. if (capacity === void 0) { capacity = 500; }
  108399. if (useGPU === void 0) { useGPU = false; }
  108400. var system;
  108401. if (useGPU) {
  108402. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  108403. }
  108404. else {
  108405. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  108406. }
  108407. system.emitter = emitter;
  108408. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  108409. system.createConeEmitter(0.1, Math.PI / 4);
  108410. // Particle color
  108411. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108412. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108413. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  108414. // Particle Size
  108415. system.minSize = 0.1;
  108416. system.maxSize = 0.1;
  108417. // Emission speed
  108418. system.minEmitPower = 2;
  108419. system.maxEmitPower = 2;
  108420. // Update speed
  108421. system.updateSpeed = 1 / 60;
  108422. system.emitRate = 30;
  108423. return system;
  108424. };
  108425. /**
  108426. * This is the main static method (one-liner) of this helper to create different particle systems
  108427. * @param type This string represents the type to the particle system to create
  108428. * @param scene The scene where the particle system should live
  108429. * @param gpu If the system will use gpu
  108430. * @returns the ParticleSystemSet created
  108431. */
  108432. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  108433. if (gpu === void 0) { gpu = false; }
  108434. if (!scene) {
  108435. scene = BABYLON.Engine.LastCreatedScene;
  108436. ;
  108437. }
  108438. var token = {};
  108439. scene._addPendingData(token);
  108440. return new Promise(function (resolve, reject) {
  108441. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  108442. scene._removePendingData(token);
  108443. return reject("Particle system with GPU is not supported.");
  108444. }
  108445. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  108446. scene._removePendingData(token);
  108447. var newData = JSON.parse(data.toString());
  108448. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  108449. }, undefined, undefined, undefined, function (req, exception) {
  108450. scene._removePendingData(token);
  108451. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  108452. });
  108453. });
  108454. };
  108455. /**
  108456. * Static function used to export a particle system to a ParticleSystemSet variable.
  108457. * Please note that the emitter shape is not exported
  108458. * @param system defines the particle systems to export
  108459. */
  108460. ParticleHelper.ExportSet = function (systems) {
  108461. var set = new BABYLON.ParticleSystemSet();
  108462. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  108463. var system = systems_1[_i];
  108464. set.systems.push(system);
  108465. }
  108466. return set;
  108467. };
  108468. /**
  108469. * Gets or sets base Assets URL
  108470. */
  108471. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  108472. return ParticleHelper;
  108473. }());
  108474. BABYLON.ParticleHelper = ParticleHelper;
  108475. })(BABYLON || (BABYLON = {}));
  108476. //# sourceMappingURL=babylon.particleHelper.js.map
  108477. var BABYLON;
  108478. (function (BABYLON) {
  108479. /**
  108480. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  108481. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  108482. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  108483. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  108484. */
  108485. var VideoDome = /** @class */ (function (_super) {
  108486. __extends(VideoDome, _super);
  108487. /**
  108488. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  108489. * @param name Element's name, child elements will append suffixes for their own names.
  108490. * @param urlsOrVideo defines the url(s) or the video element to use
  108491. * @param options An object containing optional or exposed sub element properties
  108492. */
  108493. function VideoDome(name, urlsOrVideo, options, scene) {
  108494. var _this = _super.call(this, name, scene) || this;
  108495. _this._useDirectMapping = false;
  108496. // set defaults and manage values
  108497. name = name || "videoDome";
  108498. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  108499. options.clickToPlay = Boolean(options.clickToPlay);
  108500. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  108501. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  108502. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  108503. if (options.useDirectMapping === undefined) {
  108504. _this._useDirectMapping = true;
  108505. }
  108506. else {
  108507. _this._useDirectMapping = options.useDirectMapping;
  108508. }
  108509. _this._setReady(false);
  108510. // create
  108511. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  108512. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  108513. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  108514. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  108515. texture.onLoadObservable.addOnce(function () {
  108516. _this._setReady(true);
  108517. });
  108518. // configure material
  108519. material.useEquirectangularFOV = true;
  108520. material.fovMultiplier = 1.0;
  108521. material.opacityFresnel = false;
  108522. if (_this._useDirectMapping) {
  108523. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108524. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108525. material.diffuseTexture = texture;
  108526. }
  108527. else {
  108528. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  108529. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108530. material.reflectionTexture = texture;
  108531. }
  108532. // configure mesh
  108533. _this._mesh.material = material;
  108534. _this._mesh.parent = _this;
  108535. // optional configuration
  108536. if (options.clickToPlay) {
  108537. scene.onPointerUp = function () {
  108538. _this._videoTexture.video.play();
  108539. };
  108540. }
  108541. return _this;
  108542. }
  108543. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  108544. /**
  108545. * Gets the video texture being displayed on the sphere
  108546. */
  108547. get: function () {
  108548. return this._videoTexture;
  108549. },
  108550. enumerable: true,
  108551. configurable: true
  108552. });
  108553. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  108554. /**
  108555. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  108556. * Also see the options.resolution property.
  108557. */
  108558. get: function () {
  108559. return this._material.fovMultiplier;
  108560. },
  108561. set: function (value) {
  108562. this._material.fovMultiplier = value;
  108563. },
  108564. enumerable: true,
  108565. configurable: true
  108566. });
  108567. /**
  108568. * Releases resources associated with this node.
  108569. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  108570. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  108571. */
  108572. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  108573. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  108574. this._videoTexture.dispose();
  108575. this._mesh.dispose();
  108576. this._material.dispose();
  108577. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  108578. };
  108579. return VideoDome;
  108580. }(BABYLON.TransformNode));
  108581. BABYLON.VideoDome = VideoDome;
  108582. })(BABYLON || (BABYLON = {}));
  108583. //# sourceMappingURL=babylon.videoDome.js.map
  108584. var BABYLON;
  108585. (function (BABYLON) {
  108586. /**
  108587. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  108588. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  108589. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  108590. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  108591. */
  108592. var PhotoDome = /** @class */ (function (_super) {
  108593. __extends(PhotoDome, _super);
  108594. /**
  108595. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  108596. * @param name Element's name, child elements will append suffixes for their own names.
  108597. * @param urlsOfPhoto defines the url of the photo to display
  108598. * @param options defines an object containing optional or exposed sub element properties
  108599. * @param onError defines a callback called when an error occured while loading the texture
  108600. */
  108601. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  108602. if (onError === void 0) { onError = null; }
  108603. var _this = _super.call(this, name, scene) || this;
  108604. _this._useDirectMapping = false;
  108605. /**
  108606. * Observable raised when an error occured while loading the 360 image
  108607. */
  108608. _this.onLoadErrorObservable = new BABYLON.Observable();
  108609. // set defaults and manage values
  108610. name = name || "photoDome";
  108611. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  108612. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  108613. if (options.useDirectMapping === undefined) {
  108614. _this._useDirectMapping = true;
  108615. }
  108616. else {
  108617. _this._useDirectMapping = options.useDirectMapping;
  108618. }
  108619. _this._setReady(false);
  108620. // create
  108621. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  108622. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  108623. // configure material
  108624. material.opacityFresnel = false;
  108625. material.useEquirectangularFOV = true;
  108626. material.fovMultiplier = 1.0;
  108627. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  108628. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  108629. if (onError) {
  108630. onError(message, exception);
  108631. }
  108632. });
  108633. _this.photoTexture.onLoadObservable.addOnce(function () {
  108634. _this._setReady(true);
  108635. });
  108636. // configure mesh
  108637. _this._mesh.material = material;
  108638. _this._mesh.parent = _this;
  108639. return _this;
  108640. }
  108641. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  108642. /**
  108643. * Gets or sets the texture being displayed on the sphere
  108644. */
  108645. get: function () {
  108646. return this._photoTexture;
  108647. },
  108648. set: function (value) {
  108649. if (this._photoTexture === value) {
  108650. return;
  108651. }
  108652. this._photoTexture = value;
  108653. if (this._useDirectMapping) {
  108654. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108655. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108656. this._material.diffuseTexture = this._photoTexture;
  108657. }
  108658. else {
  108659. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  108660. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108661. this._material.reflectionTexture = this._photoTexture;
  108662. }
  108663. },
  108664. enumerable: true,
  108665. configurable: true
  108666. });
  108667. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  108668. /**
  108669. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  108670. * Also see the options.resolution property.
  108671. */
  108672. get: function () {
  108673. return this._material.fovMultiplier;
  108674. },
  108675. set: function (value) {
  108676. this._material.fovMultiplier = value;
  108677. },
  108678. enumerable: true,
  108679. configurable: true
  108680. });
  108681. /**
  108682. * Releases resources associated with this node.
  108683. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  108684. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  108685. */
  108686. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  108687. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  108688. this._photoTexture.dispose();
  108689. this._mesh.dispose();
  108690. this._material.dispose();
  108691. this.onLoadErrorObservable.clear();
  108692. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  108693. };
  108694. return PhotoDome;
  108695. }(BABYLON.TransformNode));
  108696. BABYLON.PhotoDome = PhotoDome;
  108697. })(BABYLON || (BABYLON = {}));
  108698. //# sourceMappingURL=babylon.photoDome.js.map
  108699. var BABYLON;
  108700. (function (BABYLON) {
  108701. BABYLON.Engine.prototype.createQuery = function () {
  108702. return this._gl.createQuery();
  108703. };
  108704. BABYLON.Engine.prototype.deleteQuery = function (query) {
  108705. this._gl.deleteQuery(query);
  108706. return this;
  108707. };
  108708. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  108709. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  108710. };
  108711. BABYLON.Engine.prototype.getQueryResult = function (query) {
  108712. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  108713. };
  108714. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  108715. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108716. this._gl.beginQuery(glAlgorithm, query);
  108717. return this;
  108718. };
  108719. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  108720. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108721. this._gl.endQuery(glAlgorithm);
  108722. return this;
  108723. };
  108724. BABYLON.Engine.prototype._createTimeQuery = function () {
  108725. var timerQuery = this.getCaps().timerQuery;
  108726. if (timerQuery.createQueryEXT) {
  108727. return timerQuery.createQueryEXT();
  108728. }
  108729. return this.createQuery();
  108730. };
  108731. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  108732. var timerQuery = this.getCaps().timerQuery;
  108733. if (timerQuery.deleteQueryEXT) {
  108734. timerQuery.deleteQueryEXT(query);
  108735. return;
  108736. }
  108737. this.deleteQuery(query);
  108738. };
  108739. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  108740. var timerQuery = this.getCaps().timerQuery;
  108741. if (timerQuery.getQueryObjectEXT) {
  108742. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  108743. }
  108744. return this.getQueryResult(query);
  108745. };
  108746. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  108747. var timerQuery = this.getCaps().timerQuery;
  108748. if (timerQuery.getQueryObjectEXT) {
  108749. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  108750. }
  108751. return this.isQueryResultAvailable(query);
  108752. };
  108753. BABYLON.Engine.prototype.startTimeQuery = function () {
  108754. var caps = this.getCaps();
  108755. var timerQuery = caps.timerQuery;
  108756. if (!timerQuery) {
  108757. return null;
  108758. }
  108759. var token = new BABYLON._TimeToken();
  108760. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108761. if (caps.canUseTimestampForTimerQuery) {
  108762. token._startTimeQuery = this._createTimeQuery();
  108763. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  108764. }
  108765. else {
  108766. if (this._currentNonTimestampToken) {
  108767. return this._currentNonTimestampToken;
  108768. }
  108769. token._timeElapsedQuery = this._createTimeQuery();
  108770. if (timerQuery.beginQueryEXT) {
  108771. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108772. }
  108773. else {
  108774. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108775. }
  108776. this._currentNonTimestampToken = token;
  108777. }
  108778. return token;
  108779. };
  108780. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  108781. var caps = this.getCaps();
  108782. var timerQuery = caps.timerQuery;
  108783. if (!timerQuery || !token) {
  108784. return -1;
  108785. }
  108786. if (caps.canUseTimestampForTimerQuery) {
  108787. if (!token._startTimeQuery) {
  108788. return -1;
  108789. }
  108790. if (!token._endTimeQuery) {
  108791. token._endTimeQuery = this._createTimeQuery();
  108792. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  108793. }
  108794. }
  108795. else if (!token._timeElapsedQueryEnded) {
  108796. if (!token._timeElapsedQuery) {
  108797. return -1;
  108798. }
  108799. if (timerQuery.endQueryEXT) {
  108800. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  108801. }
  108802. else {
  108803. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  108804. }
  108805. token._timeElapsedQueryEnded = true;
  108806. }
  108807. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108808. var available = false;
  108809. if (token._endTimeQuery) {
  108810. available = this._getTimeQueryAvailability(token._endTimeQuery);
  108811. }
  108812. else if (token._timeElapsedQuery) {
  108813. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  108814. }
  108815. if (available && !disjoint) {
  108816. var result = 0;
  108817. if (caps.canUseTimestampForTimerQuery) {
  108818. if (!token._startTimeQuery || !token._endTimeQuery) {
  108819. return -1;
  108820. }
  108821. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  108822. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  108823. result = timeEnd - timeStart;
  108824. this._deleteTimeQuery(token._startTimeQuery);
  108825. this._deleteTimeQuery(token._endTimeQuery);
  108826. token._startTimeQuery = null;
  108827. token._endTimeQuery = null;
  108828. }
  108829. else {
  108830. if (!token._timeElapsedQuery) {
  108831. return -1;
  108832. }
  108833. result = this._getTimeQueryResult(token._timeElapsedQuery);
  108834. this._deleteTimeQuery(token._timeElapsedQuery);
  108835. token._timeElapsedQuery = null;
  108836. token._timeElapsedQueryEnded = false;
  108837. this._currentNonTimestampToken = null;
  108838. }
  108839. return result;
  108840. }
  108841. return -1;
  108842. };
  108843. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  108844. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  108845. };
  108846. // We also need to update AbstractMesh as there is a portion of the code there
  108847. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  108848. var engine = this.getEngine();
  108849. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  108850. this._isOccluded = false;
  108851. return;
  108852. }
  108853. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  108854. this._isOccluded = false;
  108855. return;
  108856. }
  108857. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  108858. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  108859. if (isOcclusionQueryAvailable) {
  108860. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  108861. this._isOcclusionQueryInProgress = false;
  108862. this._occlusionInternalRetryCounter = 0;
  108863. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  108864. }
  108865. else {
  108866. this._occlusionInternalRetryCounter++;
  108867. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  108868. this._isOcclusionQueryInProgress = false;
  108869. this._occlusionInternalRetryCounter = 0;
  108870. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  108871. // if strict continue the last state of the object.
  108872. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  108873. }
  108874. else {
  108875. return;
  108876. }
  108877. }
  108878. }
  108879. var scene = this.getScene();
  108880. if (scene.getBoundingBoxRenderer) {
  108881. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  108882. if (!this._occlusionQuery) {
  108883. this._occlusionQuery = engine.createQuery();
  108884. }
  108885. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  108886. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  108887. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  108888. this._isOcclusionQueryInProgress = true;
  108889. }
  108890. };
  108891. })(BABYLON || (BABYLON = {}));
  108892. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  108893. var BABYLON;
  108894. (function (BABYLON) {
  108895. /**
  108896. * Class used to generate noise procedural textures
  108897. */
  108898. var NoiseProceduralTexture = /** @class */ (function (_super) {
  108899. __extends(NoiseProceduralTexture, _super);
  108900. /**
  108901. * Creates a new NoiseProceduralTexture
  108902. * @param name defines the name fo the texture
  108903. * @param size defines the size of the texture (default is 256)
  108904. * @param scene defines the hosting scene
  108905. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  108906. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  108907. */
  108908. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  108909. if (size === void 0) { size = 256; }
  108910. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  108911. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  108912. _this._time = 0;
  108913. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  108914. _this.brightness = 0.2;
  108915. /** Defines the number of octaves to process */
  108916. _this.octaves = 3;
  108917. /** Defines the level of persistence (0.8 by default) */
  108918. _this.persistence = 0.8;
  108919. /** Gets or sets animation speed factor (default is 1) */
  108920. _this.animationSpeedFactor = 1;
  108921. _this._updateShaderUniforms();
  108922. return _this;
  108923. }
  108924. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  108925. var scene = this.getScene();
  108926. if (!scene) {
  108927. return;
  108928. }
  108929. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  108930. this.setFloat("brightness", this.brightness);
  108931. this.setFloat("persistence", this.persistence);
  108932. this.setFloat("timeScale", this._time);
  108933. };
  108934. NoiseProceduralTexture.prototype._getDefines = function () {
  108935. return "#define OCTAVES " + this.octaves;
  108936. };
  108937. /** Generate the current state of the procedural texture */
  108938. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  108939. this._updateShaderUniforms();
  108940. _super.prototype.render.call(this, useCameraPostProcess);
  108941. };
  108942. /**
  108943. * Serializes this noise procedural texture
  108944. * @returns a serialized noise procedural texture object
  108945. */
  108946. NoiseProceduralTexture.prototype.serialize = function () {
  108947. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  108948. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  108949. return serializationObject;
  108950. };
  108951. /**
  108952. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  108953. * @param parsedTexture defines parsed texture data
  108954. * @param scene defines the current scene
  108955. * @param rootUrl defines the root URL containing noise procedural texture information
  108956. * @returns a parsed NoiseProceduralTexture
  108957. */
  108958. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  108959. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  108960. return texture;
  108961. };
  108962. return NoiseProceduralTexture;
  108963. }(BABYLON.ProceduralTexture));
  108964. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  108965. })(BABYLON || (BABYLON = {}));
  108966. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  108967. var __assign = (this && this.__assign) || function () {
  108968. __assign = Object.assign || function(t) {
  108969. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108970. s = arguments[i];
  108971. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108972. t[p] = s[p];
  108973. }
  108974. return t;
  108975. };
  108976. return __assign.apply(this, arguments);
  108977. };
  108978. var BABYLON;
  108979. (function (BABYLON) {
  108980. /**
  108981. * This can helps recording videos from BabylonJS.
  108982. * This is based on the available WebRTC functionalities of the browser.
  108983. *
  108984. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  108985. */
  108986. var VideoRecorder = /** @class */ (function () {
  108987. /**
  108988. * Create a new VideoCapture object which can help converting what you see in Babylon to
  108989. * a video file.
  108990. * @param engine Defines the BabylonJS Engine you wish to record
  108991. * @param options Defines options that can be used to customized the capture
  108992. */
  108993. function VideoRecorder(engine, options) {
  108994. if (options === void 0) { options = null; }
  108995. if (!VideoRecorder.IsSupported(engine)) {
  108996. throw "Your browser does not support recording so far.";
  108997. }
  108998. var canvas = engine.getRenderingCanvas();
  108999. if (!canvas) {
  109000. throw "The babylon engine must have a canvas to be recorded";
  109001. }
  109002. this._canvas = canvas;
  109003. this._canvas.isRecording = false;
  109004. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  109005. var stream = this._canvas.captureStream(this._options.fps);
  109006. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  109007. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  109008. this._mediaRecorder.onerror = this._handleError.bind(this);
  109009. this._mediaRecorder.onstop = this._handleStop.bind(this);
  109010. }
  109011. /**
  109012. * Returns wehther or not the VideoRecorder is available in your browser.
  109013. * @param engine Defines the Babylon Engine to check the support for
  109014. * @returns true if supported otherwise false
  109015. */
  109016. VideoRecorder.IsSupported = function (engine) {
  109017. var canvas = engine.getRenderingCanvas();
  109018. return (!!canvas && typeof canvas.captureStream === "function");
  109019. };
  109020. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  109021. /**
  109022. * True wether a recording is already in progress.
  109023. */
  109024. get: function () {
  109025. return !!this._canvas && this._canvas.isRecording;
  109026. },
  109027. enumerable: true,
  109028. configurable: true
  109029. });
  109030. /**
  109031. * Stops the current recording before the default capture timeout passed in the startRecording
  109032. * functions.
  109033. */
  109034. VideoRecorder.prototype.stopRecording = function () {
  109035. if (!this._canvas || !this._mediaRecorder) {
  109036. return;
  109037. }
  109038. if (!this.isRecording) {
  109039. return;
  109040. }
  109041. this._canvas.isRecording = false;
  109042. this._mediaRecorder.stop();
  109043. };
  109044. /**
  109045. * Starts recording the canvas for a max duration specified in parameters.
  109046. * @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.
  109047. * @param maxDuration Defines the maximum recording time in seconds.
  109048. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  109049. * @return a promise callback at the end of the recording with the video data in Blob.
  109050. */
  109051. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  109052. var _this = this;
  109053. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  109054. if (maxDuration === void 0) { maxDuration = 7; }
  109055. if (!this._canvas || !this._mediaRecorder) {
  109056. throw "Recorder has already been disposed";
  109057. }
  109058. if (this.isRecording) {
  109059. throw "Recording already in progress";
  109060. }
  109061. if (maxDuration > 0) {
  109062. setTimeout(function () {
  109063. _this.stopRecording();
  109064. }, maxDuration * 1000);
  109065. }
  109066. this._fileName = fileName;
  109067. this._recordedChunks = [];
  109068. this._resolve = null;
  109069. this._reject = null;
  109070. this._canvas.isRecording = true;
  109071. this._mediaRecorder.start(this._options.recordChunckSize);
  109072. return new Promise(function (resolve, reject) {
  109073. _this._resolve = resolve;
  109074. _this._reject = reject;
  109075. });
  109076. };
  109077. /**
  109078. * Releases internal resources used during the recording.
  109079. */
  109080. VideoRecorder.prototype.dispose = function () {
  109081. this._canvas = null;
  109082. this._mediaRecorder = null;
  109083. this._recordedChunks = [];
  109084. this._fileName = null;
  109085. this._resolve = null;
  109086. this._reject = null;
  109087. };
  109088. VideoRecorder.prototype._handleDataAvailable = function (event) {
  109089. if (event.data.size > 0) {
  109090. this._recordedChunks.push(event.data);
  109091. }
  109092. };
  109093. VideoRecorder.prototype._handleError = function (event) {
  109094. this.stopRecording();
  109095. if (this._reject) {
  109096. this._reject(event.error);
  109097. }
  109098. else {
  109099. throw new event.error;
  109100. }
  109101. };
  109102. VideoRecorder.prototype._handleStop = function () {
  109103. this.stopRecording();
  109104. var superBuffer = new Blob(this._recordedChunks);
  109105. if (this._resolve) {
  109106. this._resolve(superBuffer);
  109107. }
  109108. window.URL.createObjectURL(superBuffer);
  109109. if (this._fileName) {
  109110. BABYLON.Tools.Download(superBuffer, this._fileName);
  109111. }
  109112. };
  109113. VideoRecorder._defaultOptions = {
  109114. mimeType: "video/webm",
  109115. fps: 25,
  109116. recordChunckSize: 3000
  109117. };
  109118. return VideoRecorder;
  109119. }());
  109120. BABYLON.VideoRecorder = VideoRecorder;
  109121. })(BABYLON || (BABYLON = {}));
  109122. //# sourceMappingURL=babylon.videoRecorder.js.map
  109123. var BABYLON;
  109124. (function (BABYLON) {
  109125. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  109126. if (replace === void 0) { replace = false; }
  109127. // Dispose existing light in replace mode.
  109128. if (replace) {
  109129. if (this.lights) {
  109130. for (var i = 0; i < this.lights.length; i++) {
  109131. this.lights[i].dispose();
  109132. }
  109133. }
  109134. }
  109135. // Light
  109136. if (this.lights.length === 0) {
  109137. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  109138. }
  109139. };
  109140. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  109141. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109142. if (replace === void 0) { replace = false; }
  109143. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109144. // Dispose existing camera in replace mode.
  109145. if (replace) {
  109146. if (this.activeCamera) {
  109147. this.activeCamera.dispose();
  109148. this.activeCamera = null;
  109149. }
  109150. }
  109151. // Camera
  109152. if (!this.activeCamera) {
  109153. var worldExtends = this.getWorldExtends();
  109154. var worldSize = worldExtends.max.subtract(worldExtends.min);
  109155. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  109156. var camera;
  109157. var radius = worldSize.length() * 1.5;
  109158. // empty scene scenario!
  109159. if (!isFinite(radius)) {
  109160. radius = 1;
  109161. worldCenter.copyFromFloats(0, 0, 0);
  109162. }
  109163. if (createArcRotateCamera) {
  109164. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  109165. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  109166. arcRotateCamera.wheelPrecision = 100 / radius;
  109167. camera = arcRotateCamera;
  109168. }
  109169. else {
  109170. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  109171. freeCamera.setTarget(worldCenter);
  109172. camera = freeCamera;
  109173. }
  109174. camera.minZ = radius * 0.01;
  109175. camera.maxZ = radius * 1000;
  109176. camera.speed = radius * 0.2;
  109177. this.activeCamera = camera;
  109178. var canvas = this.getEngine().getRenderingCanvas();
  109179. if (attachCameraControls && canvas) {
  109180. camera.attachControl(canvas);
  109181. }
  109182. }
  109183. };
  109184. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  109185. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109186. if (replace === void 0) { replace = false; }
  109187. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109188. this.createDefaultLight(replace);
  109189. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  109190. };
  109191. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  109192. if (pbr === void 0) { pbr = false; }
  109193. if (scale === void 0) { scale = 1000; }
  109194. if (blur === void 0) { blur = 0; }
  109195. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  109196. if (!environmentTexture) {
  109197. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  109198. return null;
  109199. }
  109200. if (setGlobalEnvTexture) {
  109201. if (environmentTexture) {
  109202. this.environmentTexture = environmentTexture;
  109203. }
  109204. }
  109205. // Skybox
  109206. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  109207. if (pbr) {
  109208. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  109209. hdrSkyboxMaterial.backFaceCulling = false;
  109210. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  109211. if (hdrSkyboxMaterial.reflectionTexture) {
  109212. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109213. }
  109214. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  109215. hdrSkyboxMaterial.disableLighting = true;
  109216. hdrSkyboxMaterial.twoSidedLighting = true;
  109217. hdrSkybox.infiniteDistance = true;
  109218. hdrSkybox.material = hdrSkyboxMaterial;
  109219. }
  109220. else {
  109221. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  109222. skyboxMaterial.backFaceCulling = false;
  109223. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  109224. if (skyboxMaterial.reflectionTexture) {
  109225. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109226. }
  109227. skyboxMaterial.disableLighting = true;
  109228. hdrSkybox.infiniteDistance = true;
  109229. hdrSkybox.material = skyboxMaterial;
  109230. }
  109231. return hdrSkybox;
  109232. };
  109233. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  109234. if (BABYLON.EnvironmentHelper) {
  109235. return new BABYLON.EnvironmentHelper(options, this);
  109236. }
  109237. return null;
  109238. };
  109239. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  109240. if (webVROptions === void 0) { webVROptions = {}; }
  109241. return new BABYLON.VRExperienceHelper(this, webVROptions);
  109242. };
  109243. })(BABYLON || (BABYLON = {}));
  109244. //# sourceMappingURL=babylon.sceneHelpers.js.map
  109245. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=textureColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nbaseColor.rgb*=texture2D(rampSampler,vec2(remappedColorIndex,0.)).rgb;\n\nbaseColor.a=clamp((alpha-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta;\n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  109246. 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};"};
  109247. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  109248. globalObject["BABYLON"] = BABYLON;
  109249. //backwards compatibility
  109250. if(typeof earcut !== 'undefined') {
  109251. globalObject["Earcut"] = {
  109252. earcut: earcut
  109253. };
  109254. }
  109255. return BABYLON;
  109256. });